This commit is contained in:
2026-11-02 12:42:04 +00:00
commit e4e28174bf
5498 changed files with 1735888 additions and 0 deletions

19
node_modules/@cacheable/memory/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,19 @@
MIT License & © Jared Wray
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

517
node_modules/@cacheable/memory/README.md generated vendored Normal file
View File

@@ -0,0 +1,517 @@
[<img align="center" src="https://cacheable.org/logo.svg" alt="Cacheable" />](https://github.com/jaredwray/cacheable)
> High Performance Layer 1 / Layer 2 Caching with Keyv Storage
[![codecov](https://codecov.io/gh/jaredwray/cacheable/branch/main/graph/badge.svg?token=lWZ9OBQ7GM)](https://codecov.io/gh/jaredwray/cacheable)
[![tests](https://github.com/jaredwray/cacheable/actions/workflows/tests.yml/badge.svg)](https://github.com/jaredwray/cacheable/actions/workflows/tests.yml)
[![npm](https://img.shields.io/npm/dm/@cacheable/memory.svg)](https://www.npmjs.com/package/@cacheable/memory)
[![npm](https://img.shields.io/npm/v/@cacheable/memory.svg)](https://www.npmjs.com/package/@cacheable/memory)
[![license](https://img.shields.io/github/license/jaredwray/cacheable)](https://github.com/jaredwray/cacheable/blob/main/LICENSE)
You can use `CacheableMemory` as a standalone cache or as a primary store for `cacheable`. You can also set the `useClones` property to `false` if you want to use the same reference for the values. This is useful if you are using large objects and want to save memory. The `lruSize` property is the size of the LRU cache and is set to `0` by default, which disables the LRU cache (no LRU eviction is performed and the cache size is bounded only by the underlying `Map` stores). When the `lruSize` property is set to a value greater than `0`, it limits the number of keys in the cache and evicts the least recently used entries when full.
This simple in-memory cache uses multiple Map objects and a with `expiration` and `lru` policies if set to manage the in memory cache at scale.
By default we use lazy expiration deletion which means on `get` and `getMany` type functions we look if it is expired and then delete it. If you want to have a more aggressive expiration policy you can set the `checkInterval` property to a value greater than `0` which will check for expired keys at the interval you set.
Here are some of the main features of `CacheableMemory`:
* High performance in-memory cache with a robust API and feature set. 🚀
* Can scale past the `16,777,216 (2^24) keys` limit of a single `Map` via `hashStoreSize`. Default is `16` Map objects.
* LRU (Least Recently Used) cache feature to limit the number of keys in the cache via `lruSize`. Limit to `16,777,216 (2^24) keys` total.
* Expiration policy to delete expired keys with lazy deletion or aggressive deletion via `checkInterval`.
* `Wrap` feature to memoize `sync` and `async` functions with stampede protection.
* Ability to do many operations at once such as `setMany`, `getMany`, `deleteMany`, and `takeMany`.
* Supports `raw` data retrieval with `getRaw` and `getManyRaw` methods to get the full metadata of the cache entry.
# Table of Contents
* [Getting Started](#getting-started)
* [CacheableMemory - In-Memory Cache](#cacheablememory---in-memory-cache)
* [CacheableMemory Store Hashing](#cacheablememory-store-hashing)
* [CacheableMemory LRU Feature](#cacheablememory-lru-feature)
* [CacheableMemory Performance](#cacheablememory-performance)
* [CacheableMemory Statistics](#cacheablememory-statistics)
* [CacheableMemory Hooks and Events](#cacheablememory-hooks-and-events)
* [CacheableMemory Options](#cacheablememory-options)
* [CacheableMemory - API](#cacheablememory---api)
* [Keyv Storage Adapter - KeyvCacheableMemory](#keyv-storage-adapter---keyvcacheablememory)
* [Wrap / Memoization for Sync and Async Functions](#wrap--memoization-for-sync-and-async-functions)
* [Get Or Set Memoization Function](#get-or-set-memoization-function)
* [How to Contribute](#how-to-contribute)
* [License and Copyright](#license-and-copyright)
# Getting Started
```bash
npm install @cacheable/memory
```
# Basic Usage
```javascript
import { CacheableMemory } from '@cacheable/memory';
const cacheable = new CacheableMemory();
await cacheable.set('key', 'value', 1000);
const value = await cacheable.get('key');
```
In this example, the primary store we will use `lru-cache` and the secondary store is Redis. You can also set multiple stores in the options:
```javascript
import { CacheableMemory } from '@cacheable/memory';
// we set the storeHashSize to 1 so that we only use a single Map object as the lru is limited to a single Map size
const cache = new CacheableMemory({storeHashSize: 1, lruSize: 80000});
cache.set('key1', 'value1');
const result = cache.get('key1');
console.log(result); // 'value1'
```
This is a more advanced example and not needed for most use cases.
# Shorthand for Time to Live (ttl)
By default `Cacheable` and `CacheableMemory` the `ttl` is in milliseconds but you can use shorthand for the time to live. Here are the following shorthand values:
* `ms`: Milliseconds such as (1ms = 1)
* `s`: Seconds such as (1s = 1000)
* `m`: Minutes such as (1m = 60000)
* `h` or `hr`: Hours such as (1h = 3600000)
* `d`: Days such as (1d = 86400000)
Here is an example of how to use the shorthand for the `ttl`:
```javascript
import { CacheableMemory } from 'cacheable';
const cache = new CacheableMemory({ ttl: '15m' }); //sets the default ttl to 15 minutes (900000 ms)
cache.set('key', 'value', '1h'); //sets the ttl to 1 hour (3600000 ms) and overrides the default
```
if you want to disable the `ttl` you can set it to `0` or `undefined`:
```javascript
import { CacheableMemory } from 'cacheable';
const cache = new CacheableMemory({ ttl: 0 }); //sets the default ttl to 0 which is disabled
cache.set('key', 'value', 0); //sets the ttl to 0 which is disabled
```
If you set the ttl to anything below `0` or `undefined` it will disable the ttl for the cache and the value that returns will be `undefined`. With no ttl set the value will be stored `indefinitely`.
```javascript
import { CacheableMemory } from 'cacheable';
const cache = new CacheableMemory({ ttl: 0 }); //sets the default ttl to 0 which is disabled
console.log(cache.ttl); // undefined
cache.ttl = '1h'; // sets the default ttl to 1 hour (3600000 ms)
console.log(cache.ttl); // '1h'
cache.ttl = -1; // sets the default ttl to 0 which is disabled
console.log(cache.ttl); // undefined
```
## Retrieving raw cache entries
The `getRaw` and `getManyRaw` methods return the full stored metadata (`StoredDataRaw<T>`) instead of just the value:
```typescript
import { CacheableMemory } from 'cacheable';
const cache = new CacheableMemory();
// store a value
await cache.set('user:1', { name: 'Alice' }, '1h'); // 1 hour
// default: only the value
const user = await cache.get<{ name: string }>('user:1');
console.log(user); // { name: 'Alice' }
// with raw: full record including expiration
const raw = await cache.getRaw('user:1');
console.log(raw.value); // { name: 'Alice' }
console.log(raw.expires); // e.g. 1677628495000 or null
```
## CacheableMemory Store Hashing
`CacheableMemory` uses `Map` objects to store the keys and values. To make this scale past the `16,777,216 (2^24) keys` limit of a single `Map` we use a hash to balance the data across multiple `Map` objects. This is done by hashing the key and using the hash to determine which `Map` object to use. The default hashing algorithm is `djb2` but you can change it by setting the `storeHashAlgorithm` property in the options. Supported algorithms include DJB2, FNV1, MURMER, and CRC32. By default we set the amount of `Map` objects to `16`.
NOTE: if you are using the LRU cache feature the `lruSize` no matter how many `Map` objects you have it will be limited to the `16,777,216 (2^24) keys` limit of a single `Map` object. This is because we use a double linked list to manage the LRU cache and it is not possible to have more than `16,777,216 (2^24) keys` in a single `Map` object.
Here is an example of how to set the number of `Map` objects and the hashing algorithm:
```javascript
import { CacheableMemory } from '@cacheable/memory';
const cache = new CacheableMemory({
storeSize: 32, // set the number of Map objects to 32
});
cache.set('key', 'value');
const value = cache.get('key'); // value
```
Here is an example of how to use the `storeHashAlgorithm` property with supported algorithms:
```javascript
import { CacheableMemory, HashAlgorithm } from '@cacheable/memory';
// Using DJB2 (default)
const cache = new CacheableMemory({ storeHashAlgorithm: HashAlgorithm.DJB2 });
// Or other non-cryptographic algorithms for better performance
const cache2 = new CacheableMemory({ storeHashAlgorithm: HashAlgorithm.FNV1 });
const cache3 = new CacheableMemory({ storeHashAlgorithm: HashAlgorithm.MURMER });
const cache4 = new CacheableMemory({ storeHashAlgorithm: HashAlgorithm.CRC32 });
cache.set('key', 'value');
const value = cache.get('key'); // value
```
**Available algorithms:** DJB2 (default), FNV1, MURMER, CRC32. Note: Cryptographic algorithms (SHA-256, SHA-384, SHA-512) are not recommended for store hashing due to performance overhead.
If you want to provide your own hashing function you can set the `storeHashAlgorithm` property to a function that takes an object and returns a `number` that is in the range of the amount of `Map` stores you have.
```javascript
import { CacheableMemory } from 'cacheable';
/**
* Custom hash function that takes a key and the size of the store
* and returns a number between 0 and storeHashSize - 1.
* @param {string} key - The key to hash.
* @param {number} storeHashSize - The size of the store (number of Map objects).
* @returns {number} - A number between 0 and storeHashSize - 1.
*/
const customHash = (key, storeHashSize) => {
// custom hashing logic
return key.length % storeHashSize; // returns a number between 0 and 31 for 32 Map objects
};
const cache = new CacheableMemory({ storeHashAlgorithm: customHash, storeSize: 32 });
cache.set('key', 'value');
const value = cache.get('key'); // value
```
## CacheableMemory LRU Feature
You can enable the LRU (Least Recently Used) feature in `CacheableMemory` by setting the `lruSize` property in the options. This will limit the number of keys in the cache to the size you set. When the cache reaches the limit it will remove the least recently used keys from the cache. This is useful if you want to limit the memory usage of the cache.
When you set the `lruSize`, we use a doubly linked list to track the LRU order across the underlying `Map` stores. The `lruSize` itself is capped at `16,777,216 (2^24) keys` — values above this limit are rejected and an `error` event is emitted. Setting `lruSize` does not change `storeHashSize`; the underlying stores keep whatever `storeHashSize` you configured (default `16`).
```javascript
import { CacheableMemory } from 'cacheable';
const cache = new CacheableMemory({ lruSize: 1 }); // sets the LRU cache size to 1 key
cache.set('key1', 'value1');
cache.set('key2', 'value2');
const value1 = cache.get('key1');
console.log(value1); // undefined if the cache is full and key1 is the least recently used
const value2 = cache.get('key2');
console.log(value2); // value2 if key2 is still in the cache
console.log(cache.size()); // 1
```
NOTE: if you set the `lruSize` property to `0` after it was enabled it will disable the LRU cache feature and will not limit the number of keys in the cache. This will remove the `16,777,216 (2^24) keys` limit of a single `Map` object and will allow you to store more keys in the cache.
## CacheableMemory Performance
Our goal with `cacheable` and `CacheableMemory` is to provide a high performance caching engine that is simple to use and has a robust API. We test it against other cacheing engines such that are less feature rich to make sure there is little difference. Here are some of the benchmarks we have run:
*Memory Benchmark Results:*
| name | summary | ops/sec | time/op | margin | samples |
|------------------------------------------|:---------:|----------:|----------:|:--------:|----------:|
| Cacheable Memory (v1.10.0) - set / get | 🥇 | 152K | 7µs | ±0.94% | 147K |
| Map (v22) - set / get | -1.1% | 151K | 7µs | ±0.69% | 145K |
| Node Cache - set / get | -4.3% | 146K | 7µs | ±1.13% | 142K |
| bentocache (v1.4.0) - set / get | -20% | 121K | 8µs | ±0.40% | 119K |
*Memory LRU Benchmark Results:*
| name | summary | ops/sec | time/op | margin | samples |
|------------------------------------------|:---------:|----------:|----------:|:--------:|----------:|
| quick-lru (v7.0.1) - set / get | 🥇 | 118K | 9µs | ±0.85% | 112K |
| Map (v22) - set / get | -0.56% | 117K | 9µs | ±1.35% | 110K |
| lru.min (v1.1.2) - set / get | -1.7% | 116K | 9µs | ±0.90% | 110K |
| Cacheable Memory (v1.10.0) - set / get | -3.3% | 114K | 9µs | ±1.16% | 108K |
As you can see from the benchmarks `CacheableMemory` is on par with other caching engines such as `Map`, `Node Cache`, and `bentocache`. We have also tested it against other LRU caching engines such as `quick-lru` and `lru.min` and it performs well against them too.
## Maximum Time to Live (maxTtl)
You can set a `maxTtl` option to enforce an upper bound on any TTL in the cache. When `maxTtl` is set:
- Any per-entry TTL that exceeds `maxTtl` will be capped to `maxTtl`.
- Entries with no TTL (that would otherwise live indefinitely) will be capped to `maxTtl`.
- The default TTL is still respected if it is within the `maxTtl` limit.
This is useful when you want to guarantee that no cache entry lives longer than a certain duration, regardless of what TTL is passed to individual `set()` calls.
```javascript
import { CacheableMemory } from '@cacheable/memory';
// No entry can live longer than 1 hour
const cache = new CacheableMemory({ maxTtl: '1h' });
cache.set('key1', 'value1', '2h'); // capped to 1 hour
cache.set('key2', 'value2'); // also capped to 1 hour (would otherwise be indefinite)
cache.set('key3', 'value3', '30m'); // 30 minutes is within maxTtl, so it stays as-is
```
You can also set `maxTtl` after construction:
```javascript
const cache = new CacheableMemory();
cache.maxTtl = 5000; // 5 seconds max
cache.maxTtl = '10m'; // 10 minutes max
cache.maxTtl = undefined; // disable maxTtl (no upper bound)
```
## CacheableMemory Statistics
`CacheableMemory` can track runtime statistics using the shared [`Stats`](https://cacheable.org/docs/utils/) implementation from `@cacheable/utils` (the same engine used by `cacheable` and `@cacheable/node-cache`). Statistics are disabled by default. Enable them with the `stats` option or by setting `cache.stats.enabled = true` at any time:
```javascript
import { CacheableMemory } from '@cacheable/memory';
const cache = new CacheableMemory({ stats: true });
cache.set('key', 'value');
cache.get('key'); // hit
cache.get('missing'); // miss
console.log(cache.stats.hits); // 1
console.log(cache.stats.misses); // 1
console.log(cache.stats.gets); // 2
console.log(cache.stats.sets); // 1
console.log(cache.stats.count); // 1
console.log(cache.stats.hitRate); // 0.5
```
The `stats` property exposes the following counters:
* `hits`: The number of reads that found a (non-expired) value.
* `misses`: The number of reads that did not find a value.
* `gets`: The number of read operations. Every key read counts as one get, so `getMany(['a', 'b'])` records two gets.
* `sets`: The number of writes. Every key written counts as one set, including overwrites.
* `deletes`: The number of keys removed via `delete`/`deleteMany`/`take`, as well as keys evicted by the LRU.
* `clears`: The number of times `clear()` was called.
* `count`: The number of keys currently tracked in the cache.
* `ksize`: The estimated byte size of the keys in the cache.
* `vsize`: The estimated byte size of the values in the cache.
* `hitRate` / `missRate`: The ratio of hits / misses to total lookups.
You can get a plain-object snapshot via `cache.stats.toJSON()` and reset all counters with `cache.stats.reset()`.
The `count`, `ksize`, and `vsize` values are kept in sync as entries are added, removed, overwritten, and lazily expired, so they reflect the current contents of the cache. (Expired entries are not counted as `deletes`, since their removal is not user-initiated.) Methods that perform a read internally — such as `has()`, `take()`, and the `wrap()` / `getOrSet()` memoization helpers — flow through `get`/`set`, so they update the statistics as well.
For accurate size counters, enable statistics before populating the cache: `count`/`ksize`/`vsize` only account for entries written while statistics were enabled, and are clamped at `0` so they never go negative if you enable stats after the cache already has data. Changing `storeHashSize` recreates the underlying stores and clears all entries, so the size counters are reset to `0` accordingly.
## CacheableMemory Hooks and Events
`CacheableMemory` extends [`Hookified`](https://github.com/jaredwray/hookified), so you can register handlers that run around cache operations via the `CacheableMemoryHooks` enum and the `onHook()` method:
* `BEFORE_SET`: Called before `set()`. The handler receives `{ key, value, ttl }` and can reassign any of them to change what gets stored.
* `AFTER_SET`: Called after `set()` with the (possibly modified) `{ key, value, ttl }`.
* `BEFORE_SET_MANY`: Called before `setMany()` with the array of `CacheableItem`s. Items can be mutated.
* `AFTER_SET_MANY`: Called after `setMany()` with the array of items.
* `BEFORE_GET`: Called before `get()` with the `key`.
* `AFTER_GET`: Called after `get()` with `{ key, result }` (`result` is `undefined` on a cache miss).
* `BEFORE_GET_MANY`: Called before `getMany()` with the array of `keys`.
* `AFTER_GET_MANY`: Called after `getMany()` with `{ keys, result }`.
* `BEFORE_DELETE`: Called before `delete()` with the `key`.
* `AFTER_DELETE`: Called after `delete()` with the `key`.
* `BEFORE_DELETE_MANY`: Called before `deleteMany()` with the array of `keys`.
* `AFTER_DELETE_MANY`: Called after `deleteMany()` with the array of `keys`.
* `BEFORE_CLEAR`: Called before `clear()`.
* `AFTER_CLEAR`: Called after `clear()`.
An example of how to use these hooks:
```javascript
import { CacheableMemory, CacheableMemoryHooks } from '@cacheable/memory';
const cache = new CacheableMemory();
cache.onHook(CacheableMemoryHooks.BEFORE_SET, (item) => {
console.log(`before set: ${item.key} ${item.value}`);
});
cache.onHook(CacheableMemoryHooks.AFTER_GET, (item) => {
console.log(`after get: ${item.key} = ${item.result}`);
});
```
A `BEFORE_SET` handler can change the `key`, `value`, or `ttl` before the entry is stored. The `ttl` accepts a number (milliseconds), a [shorthand string](#shorthand-for-time-to-live-ttl), or a `SetOptions` object (`{ ttl, expire }`):
```javascript
cache.onHook(CacheableMemoryHooks.BEFORE_SET, (item) => {
item.key = `user:${item.key}`;
item.ttl = '1h';
});
```
Hooks are dispatched synchronously via `hookSync`, which **skips `async` handler functions entirely** — an `async` handler will not run at all (not merely run un-awaited), so register only synchronous handlers.
> **TypeScript:** the hook payload types are exported so you can annotate your handlers — `CacheableMemoryHookItem`, `CacheableMemoryAfterGetItem`, and `CacheableMemoryAfterGetManyItem`. For example:
> ```ts
> cache.onHook(CacheableMemoryHooks.BEFORE_SET, (item: CacheableMemoryHookItem) => {
> item.ttl = '1h';
> });
> ```
## CacheableMemory Options
* `ttl`: The time to live for the cache in milliseconds. Default is `undefined` which is means indefinitely.
* `maxTtl`: The maximum time to live for any cache entry. When set, TTLs exceeding this value are capped. Default is `undefined` (no maximum).
* `useClones`: If the cache should use clones for the values. Default is `true`.
* `lruSize`: The size of the LRU cache. Default is `0`, which disables the LRU cache (no LRU eviction is performed). Maximum is `16,777,216 (2^24)`.
* `checkInterval`: The interval to check for expired keys in milliseconds. Default is `0` which is disabled.
* `storeHashSize`: The number of `Map` objects to use for the cache. Default is `16`.
* `storeHashAlgorithm`: The hashing algorithm to use for the cache. Default is `djb2`. Supported: DJB2, FNV1, MURMER, CRC32.
* `stats`: Whether to track runtime statistics (`hits`, `misses`, `gets`, `sets`, `deletes`, `clears`, `count`, `ksize`, `vsize`). Default is `false`.
## CacheableMemory - API
* `set(key, value, ttl?)`: Sets a value in the cache.
* `setMany([{key, value, ttl?}])`: Sets multiple values in the cache from `CacheableItem`.
* `get(key)`: Gets a value from the cache.
* `getMany([keys])`: Gets multiple values from the cache.
* `getRaw(key)`: Gets a value from the cache as `CacheableStoreItem`.
* `getManyRaw([keys])`: Gets multiple values from the cache as `CacheableStoreItem`.
* `has(key)`: Checks if a value exists in the cache.
* `hasMany([keys])`: Checks if multiple values exist in the cache.
* `delete(key)`: Deletes a value from the cache.
* `deleteMany([keys])`: Deletes multiple values from the cache.
* `take(key)`: Takes a value from the cache and deletes it.
* `takeMany([keys])`: Takes multiple values from the cache and deletes them.
* `wrap(function, WrapSyncOptions)`: Wraps a `sync` function in a cache.
* `clear()`: Clears the cache.
* `onHook(hook, handler)`: Registers a handler for a `CacheableMemoryHooks` event. See [CacheableMemory Hooks and Events](#cacheablememory-hooks-and-events).
* `ttl`: The default time to live for the cache in milliseconds. Default is `undefined` which is disabled.
* `maxTtl`: The maximum time to live for any cache entry. When set, TTLs exceeding this value are capped. Default is `undefined` (no maximum).
* `useClones`: If the cache should use clones for the values. Default is `true`.
* `lruSize`: The size of the LRU cache. Default is `0`, which disables the LRU cache (no LRU eviction is performed). Maximum is `16,777,216 (2^24)`.
* `size`: The number of keys in the cache.
* `checkInterval`: The interval to check for expired keys in milliseconds. Default is `0` which is disabled.
* `storeHashSize`: The number of `Map` objects to use for the cache. Default is `16`.
* `storeHashAlgorithm`: The hashing algorithm to use for the cache. Default is `djb2`. Supported: DJB2, FNV1, MURMER, CRC32.
* `stats`: The statistics for this instance which includes `hits`, `misses`, `gets`, `sets`, `deletes`, `clears`, `count`, `vsize`, and `ksize`. Disabled by default; enable via the `stats` option or `cache.stats.enabled = true`.
* `keys`: Get the keys in the cache. Not able to be set.
* `items`: Get the items in the cache as `CacheableStoreItem` example `{ key, value, expires? }`.
* `store`: The hash store for the cache which is an array of `Map` objects.
* `checkExpired()`: Checks for expired keys in the cache. This is used by the `checkInterval` property.
* `startIntervalCheck()`: Starts the interval check for expired keys if `checkInterval` is above 0 ms.
* `stopIntervalCheck()`: Stops the interval check for expired keys.
# Keyv Storage Adapter - KeyvCacheableMemory
`cacheable` comes with a built-in storage adapter for Keyv called `KeyvCacheableMemory`. This takes `CacheableMemory` and creates a storage adapter for Keyv. This is useful if you want to use `CacheableMemory` as a storage adapter for Keyv. Here is an example of how to use `KeyvCacheableMemory`:
```javascript
import { Keyv } from 'keyv';
import { KeyvCacheableMemory } from 'cacheable';
const keyv = new Keyv({ store: new KeyvCacheableMemory() });
await keyv.set('foo', 'bar');
const value = await keyv.get('foo');
console.log(value); // bar
```
# Wrap / Memoization for Sync and Async Functions
`CacheableMemory` has a feature called `wrap` that allows you to wrap a function in a cache. This is useful for memoization and caching the results of a function. You can wrap a `sync` function in a cache. Here is an example of how to use the `wrap` function:
```javascript
import { CacheableMemory } from 'cacheable';
const syncFunction = (value: number) => {
return value * 2;
};
const cache = new CacheableMemory();
const wrappedFunction = cache.wrap(syncFunction, { ttl: '1h', key: 'syncFunction' });
console.log(wrappedFunction(2)); // 4
console.log(wrappedFunction(2)); // 4 from cache
```
In this example we are wrapping a `sync` function in a cache with a `ttl` of `1 hour`. This will cache the result of the function for `1 hour` and then expire the value. You can also set the `key` property in the `wrap()` options to set a custom key for the cache.
When an error occurs in the function it will not cache the value and will return the error. This is useful if you want to cache the results of a function but not cache the error. If you want it to cache the error you can set the `cacheError` property to `true` in the `wrap()` options. This is disabled by default.
```javascript
import { CacheableMemory } from 'cacheable';
const syncFunction = (value: number) => {
throw new Error('error');
};
const cache = new CacheableMemory();
const wrappedFunction = cache.wrap(syncFunction, { ttl: '1h', key: 'syncFunction', cacheError: true });
console.log(wrappedFunction()); // error
console.log(wrappedFunction()); // error from cache
```
If you would like to generate your own key for the wrapped function you can set the `createKey` property in the `wrap()` options. This is useful if you want to generate a key based on the arguments of the function or any other criteria.
```javascript
const cache = new CacheableMemory();
const options: WrapOptions = {
cache,
keyPrefix: 'test',
createKey: (function_, arguments_, options: WrapOptions) => `customKey:${options?.keyPrefix}:${arguments_[0]}`,
};
const wrapped = wrap((argument: string) => `Result for ${argument}`, options);
const result1 = wrapped('arg1');
const result2 = wrapped('arg1'); // Should hit the cache
console.log(result1); // Result for arg1
console.log(result2); // Result for arg1 (from cache)
```
We will pass in the `function` that is being wrapped, the `arguments` passed to the function, and the `options` used to wrap the function. You can then use these to generate a custom key for the cache.
# Get Or Set Memoization Function
`CacheableMemory` also has a `getOrSet` method that implements the cache-aside pattern in a single synchronous call. It attempts to retrieve a value from the cache, and if it is not found it calls the provided function to compute the value, stores it, and returns it. This is the synchronous counterpart to the `getOrSet` method on `cacheable` and is backed by `getOrSetSync` from [@cacheable/utils](https://cacheable.org/docs/utils/).
```javascript
import { CacheableMemory } from '@cacheable/memory';
const cache = new CacheableMemory();
const getUser = () => ({ id: 1, name: 'Alice' });
// First call computes the value and stores it
const user1 = cache.getOrSet('user:1', getUser, { ttl: '1h' });
// Second call returns the cached value without calling getUser again
const user2 = cache.getOrSet('user:1', getUser, { ttl: '1h' });
console.log(user1); // { id: 1, name: 'Alice' }
console.log(user1 === user2); // true (served from cache)
```
The third argument accepts the following options:
```typescript
export type GetOrSetFunctionOptions = {
ttl?: number | string;
cacheErrors?: boolean;
throwErrors?: boolean | 'function' | 'store';
};
```
* `ttl`: The time to live for the stored value. If omitted it falls back to the instance default `ttl`. Accepts milliseconds or the [shorthand](#shorthand-for-time-to-live-ttl) format such as `1h`.
* `cacheErrors`: When `true`, errors thrown by the function are cached so the function is not retried until the entry expires. Default is `false`.
* `throwErrors`: Controls whether errors are rethrown. `false` (default) emits errors on the `error` event and returns `undefined`; `true` rethrows any error; `'function'` only rethrows errors from the provided function; `'store'` only rethrows errors from reading/writing the cache.
Because `CacheableMemory` is synchronous there is no request coalescing — synchronous code runs to completion without interleaving, so concurrent callers cannot stampede the setter the way they can with the async `getOrSet` on `cacheable`.
You can also pass a function to compute the key:
```javascript
import { CacheableMemory, GetOrSetSyncKey } from '@cacheable/memory';
const cache = new CacheableMemory();
const generateKey: GetOrSetSyncKey = (options) => `user:${options?.ttl}`;
const value = cache.getOrSet(generateKey, () => Math.random() * 100, { ttl: '1h' });
```
# How to Contribute
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`.
# License and Copyright
[MIT © Jared Wray](./LICENSE)

877
node_modules/@cacheable/memory/dist/index.cjs generated vendored Normal file
View File

@@ -0,0 +1,877 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
let _cacheable_utils = require("@cacheable/utils");
let hookified = require("hookified");
let keyv = require("keyv");
//#region src/memory-lru.ts
var ListNode = class {
value;
prev = void 0;
next = void 0;
constructor(value) {
this.value = value;
}
};
var DoublyLinkedList = class {
head = void 0;
tail = void 0;
nodesMap = /* @__PURE__ */ new Map();
addToFront(value) {
const newNode = new ListNode(value);
if (this.head) {
newNode.next = this.head;
this.head.prev = newNode;
this.head = newNode;
} else this.head = this.tail = newNode;
this.nodesMap.set(value, newNode);
}
moveToFront(value) {
const node = this.nodesMap.get(value);
if (!node || this.head === node) return;
/* v8 ignore next -- @preserve */
if (node.prev) node.prev.next = node.next;
/* v8 ignore next -- @preserve */
if (node.next) node.next.prev = node.prev;
/* v8 ignore next -- @preserve */
if (node === this.tail) this.tail = node.prev;
node.prev = void 0;
node.next = this.head;
/* v8 ignore next -- @preserve */
if (this.head) this.head.prev = node;
this.head = node;
this.tail ??= node;
}
getOldest() {
/* v8 ignore next -- @preserve */
return this.tail ? this.tail.value : void 0;
}
removeOldest() {
/* v8 ignore next -- @preserve */
if (!this.tail) return;
const oldValue = this.tail.value;
/* v8 ignore next -- @preserve */
if (this.tail.prev) {
this.tail = this.tail.prev;
this.tail.next = void 0;
} else
/* v8 ignore next -- @preserve */
this.head = this.tail = void 0;
this.nodesMap.delete(oldValue);
return oldValue;
}
remove(value) {
const node = this.nodesMap.get(value);
if (!node) return false;
if (node.prev) node.prev.next = node.next;
else {
this.head = node.next;
if (this.head) this.head.prev = void 0;
}
if (node.next) node.next.prev = node.prev;
else {
this.tail = node.prev;
if (this.tail) this.tail.next = void 0;
}
this.nodesMap.delete(value);
return true;
}
get size() {
return this.nodesMap.size;
}
};
//#endregion
//#region src/keyv-memory.ts
var KeyvCacheableMemory = class {
opts = {
ttl: 0,
useClone: true,
lruSize: 0,
checkInterval: 0
};
_defaultCache = new CacheableMemory();
_nCache = /* @__PURE__ */ new Map();
_namespace;
constructor(options) {
if (options) {
this.opts = options;
this._defaultCache = new CacheableMemory(options);
if (options.namespace) {
this._namespace = options.namespace;
this._nCache.set(this._namespace, new CacheableMemory(options));
}
}
}
get namespace() {
return this._namespace;
}
set namespace(value) {
this._namespace = value;
}
get store() {
return this.getStore(this._namespace);
}
async get(key) {
const result = this.getStore(this._namespace).get(key);
if (result) return result;
}
async getMany(keys) {
return this.getStore(this._namespace).getMany(keys);
}
async set(key, value, ttl) {
this.getStore(this._namespace).set(key, value, ttl);
}
async setMany(values) {
this.getStore(this._namespace).setMany(values);
}
async delete(key) {
this.getStore(this._namespace).delete(key);
return true;
}
async deleteMany(key) {
this.getStore(this._namespace).deleteMany(key);
return true;
}
async clear() {
this.getStore(this._namespace).clear();
}
async has(key) {
return this.getStore(this._namespace).has(key);
}
on(event, listener) {
this.getStore(this._namespace).on(event, listener);
return this;
}
getStore(namespace) {
if (!namespace) return this._defaultCache;
if (!this._nCache.has(namespace)) this._nCache.set(namespace, new CacheableMemory(this.opts));
return this._nCache.get(namespace);
}
};
/**
* Creates a new Keyv instance with a new KeyvCacheableMemory store. This also removes the serialize/deserialize methods from the Keyv instance for optimization.
* @param options
* @returns
*/
function createKeyv(options) {
const store = new KeyvCacheableMemory(options);
const namespace = options?.namespace;
let ttl;
/* v8 ignore next -- @preserve */
if (options?.ttl && Number.isInteger(options.ttl)) ttl = options?.ttl;
const keyv$1 = new keyv.Keyv({
store,
namespace,
ttl
});
keyv$1.serialize = void 0;
keyv$1.deserialize = void 0;
return keyv$1;
}
//#endregion
//#region src/index.ts
/**
* Lifecycle hooks fired by {@link CacheableMemory}. Register handlers with the inherited
* `onHook(hook, handler)` method. Hooks are dispatched synchronously via `hookSync`, which skips
* `async` handler functions entirely — register only synchronous handlers.
*/
let CacheableMemoryHooks = /* @__PURE__ */ function(CacheableMemoryHooks) {
CacheableMemoryHooks["BEFORE_SET"] = "BEFORE_SET";
CacheableMemoryHooks["AFTER_SET"] = "AFTER_SET";
CacheableMemoryHooks["BEFORE_SET_MANY"] = "BEFORE_SET_MANY";
CacheableMemoryHooks["AFTER_SET_MANY"] = "AFTER_SET_MANY";
CacheableMemoryHooks["BEFORE_GET"] = "BEFORE_GET";
CacheableMemoryHooks["AFTER_GET"] = "AFTER_GET";
CacheableMemoryHooks["BEFORE_GET_MANY"] = "BEFORE_GET_MANY";
CacheableMemoryHooks["AFTER_GET_MANY"] = "AFTER_GET_MANY";
CacheableMemoryHooks["BEFORE_DELETE"] = "BEFORE_DELETE";
CacheableMemoryHooks["AFTER_DELETE"] = "AFTER_DELETE";
CacheableMemoryHooks["BEFORE_DELETE_MANY"] = "BEFORE_DELETE_MANY";
CacheableMemoryHooks["AFTER_DELETE_MANY"] = "AFTER_DELETE_MANY";
CacheableMemoryHooks["BEFORE_CLEAR"] = "BEFORE_CLEAR";
CacheableMemoryHooks["AFTER_CLEAR"] = "AFTER_CLEAR";
return CacheableMemoryHooks;
}({});
const defaultStoreHashSize = 16;
const maximumMapSize = 16777216;
var CacheableMemory = class extends hookified.Hookified {
_lru = new DoublyLinkedList();
_storeHashSize = 16;
_storeHashAlgorithm = _cacheable_utils.HashAlgorithm.DJB2;
_store = Array.from({ length: this._storeHashSize }, () => /* @__PURE__ */ new Map());
_ttl;
_maxTtl;
_useClone = true;
_lruSize = 0;
_checkInterval = 0;
_interval = 0;
_stats = new _cacheable_utils.Stats({ enabled: false });
/**
* @constructor
* @param {CacheableMemoryOptions} [options] - The options for the CacheableMemory
*/
constructor(options) {
super();
if (options?.ttl) this.setTtl(options.ttl);
if (options?.maxTtl !== void 0) this.setMaxTtl(options.maxTtl);
if (options?.useClone !== void 0) this._useClone = options.useClone;
if (options?.stats) this._stats.enabled = options.stats;
if (options?.storeHashSize && options.storeHashSize > 0) this._storeHashSize = options.storeHashSize;
if (options?.lruSize) if (options.lruSize > 16777216) this.emit("error", /* @__PURE__ */ new Error(`LRU size cannot be larger than ${maximumMapSize} due to Map limitations.`));
else this._lruSize = options.lruSize;
if (options?.checkInterval) this._checkInterval = options.checkInterval;
if (options?.storeHashAlgorithm) this._storeHashAlgorithm = options.storeHashAlgorithm;
this._store = Array.from({ length: this._storeHashSize }, () => /* @__PURE__ */ new Map());
this.startIntervalCheck();
}
/**
* Gets the time-to-live
* @returns {number|string|undefined} - The time-to-live in miliseconds or a human-readable format. If undefined, it will not have a time-to-live.
*/
get ttl() {
return this._ttl;
}
/**
* Sets the time-to-live
* @param {number|string|undefined} value - The time-to-live in miliseconds or a human-readable format (example '1s' = 1 second, '1h' = 1 hour). If undefined, it will not have a time-to-live.
*/
set ttl(value) {
this.setTtl(value);
}
/**
* Gets the maximum time-to-live. When set, any TTL that exceeds this value is capped to maxTtl.
* Entries with no TTL will also be capped to maxTtl. Default is `undefined` (no maximum).
* @returns {number|string|undefined} - The maximum TTL in milliseconds, human-readable format, or undefined.
*/
get maxTtl() {
return this._maxTtl;
}
/**
* Sets the maximum time-to-live. When set, any TTL that exceeds this value is capped to maxTtl.
* Entries with no TTL will also be capped to maxTtl.
* @param {number|string|undefined} value - The maximum TTL in milliseconds or human-readable format (e.g. '1s', '1h'). If undefined, no maximum is enforced.
*/
set maxTtl(value) {
this.setMaxTtl(value);
}
/**
* Gets whether to use clone
* @returns {boolean} - If true, it will clone the value before returning it. If false, it will return the value directly. Default is true.
*/
get useClone() {
return this._useClone;
}
/**
* Sets whether to use clone
* @param {boolean} value - If true, it will clone the value before returning it. If false, it will return the value directly. Default is true.
*/
set useClone(value) {
this._useClone = value;
}
/**
* Gets the size of the LRU cache
* @returns {number} - The size of the LRU cache. If set to 0, it will not use LRU cache. Default is 0. If you are using LRU then the limit is based on Map() size 17mm.
*/
get lruSize() {
return this._lruSize;
}
/**
* Sets the size of the LRU cache
* @param {number} value - The size of the LRU cache. If set to 0, it will not use LRU cache. Default is 0. If you are using LRU then the limit is based on Map() size 17mm.
*/
set lruSize(value) {
if (value > 16777216) {
this.emit("error", /* @__PURE__ */ new Error(`LRU size cannot be larger than ${maximumMapSize} due to Map limitations.`));
return;
}
this._lruSize = value;
if (this._lruSize === 0) {
this._lru = new DoublyLinkedList();
return;
}
this.lruResize();
}
/**
* Gets the check interval
* @returns {number} - The interval to check for expired items. If set to 0, it will not check for expired items. Default is 0.
*/
get checkInterval() {
return this._checkInterval;
}
/**
* Sets the check interval
* @param {number} value - The interval to check for expired items. If set to 0, it will not check for expired items. Default is 0.
*/
set checkInterval(value) {
this._checkInterval = value;
}
/**
* Gets the size of the cache
* @returns {number} - The size of the cache
*/
get size() {
let size = 0;
for (const store of this._store) size += store.size;
return size;
}
/**
* Gets the statistics of the cache. Statistics track aggregate counters such as `hits`, `misses`,
* `gets`, `sets`, `deletes`, `clears`, `count`, `ksize`, and `vsize`. They are disabled by default;
* enable them via the `stats` option or by setting `cache.stats.enabled = true`.
* @returns {Stats} - The statistics for this CacheableMemory instance
*/
get stats() {
return this._stats;
}
/**
* Gets the number of hash stores
* @returns {number} - The number of hash stores
*/
get storeHashSize() {
return this._storeHashSize;
}
/**
* Sets the number of hash stores. This will recreate the store and all data will be cleared
* @param {number} value - The number of hash stores
*/
set storeHashSize(value) {
if (value === this._storeHashSize) return;
this._storeHashSize = value;
this._store = Array.from({ length: this._storeHashSize }, () => /* @__PURE__ */ new Map());
if (this._stats.enabled) this._stats.resetStoreValues();
}
/**
* Gets the store hash algorithm
* @returns {HashAlgorithm | StoreHashAlgorithmFunction} - The store hash algorithm
*/
get storeHashAlgorithm() {
return this._storeHashAlgorithm;
}
/**
* Sets the store hash algorithm. This will recreate the store and all data will be cleared
* @param {HashAlgorithm | HashAlgorithmFunction} value - The store hash algorithm
*/
set storeHashAlgorithm(value) {
this._storeHashAlgorithm = value;
}
/**
* Gets the keys
* @returns {IterableIterator<string>} - The keys
*/
get keys() {
const keys = [];
for (const store of this._store) for (const key of store.keys()) {
const item = store.get(key);
if (item && this.hasExpired(item)) {
this.recordExpiration(item);
store.delete(key);
this.lruRemove(key);
continue;
}
keys.push(key);
}
return keys.values();
}
/**
* Gets the items
* @returns {IterableIterator<CacheableStoreItem>} - The items
*/
get items() {
const items = [];
for (const store of this._store) for (const item of store.values()) {
if (this.hasExpired(item)) {
this.recordExpiration(item);
store.delete(item.key);
this.lruRemove(item.key);
continue;
}
items.push(item);
}
return items.values();
}
/**
* Gets the store
* @returns {Array<Map<string, CacheableStoreItem>>} - The store
*/
get store() {
return this._store;
}
/**
* Gets the value of the key
* @param {string} key - The key to get the value
* @returns {T | undefined} - The value of the key
*/
get(key) {
this.hookSync("BEFORE_GET", key);
const store = this.getStore(key);
const item = store.get(key);
if (!item) {
this.recordRead(false);
this.hookSync("AFTER_GET", {
key,
result: void 0
});
return;
}
if (item.expires && Date.now() > item.expires) {
this.recordExpiration(item);
store.delete(key);
this.lruRemove(key);
this.recordRead(false);
this.hookSync("AFTER_GET", {
key,
result: void 0
});
return;
}
this.lruMoveToFront(key);
let result;
if (!this._useClone) result = item.value;
else result = this.clone(item.value);
this.recordRead(true);
this.hookSync("AFTER_GET", {
key,
result
});
return result;
}
/**
* Gets the values of the keys
* @param {string[]} keys - The keys to get the values
* @returns {T[]} - The values of the keys
*/
getMany(keys) {
this.hookSync("BEFORE_GET_MANY", keys);
const result = [];
for (const key of keys) result.push(this.get(key));
this.hookSync("AFTER_GET_MANY", {
keys,
result
});
return result;
}
/**
* Gets the raw value of the key
* @param {string} key - The key to get the value
* @returns {CacheableStoreItem | undefined} - The raw value of the key
*/
getRaw(key) {
const store = this.getStore(key);
const item = store.get(key);
if (!item) {
this.recordRead(false);
return;
}
if (item.expires && Date.now() > item.expires) {
this.recordExpiration(item);
store.delete(key);
this.lruRemove(key);
this.recordRead(false);
return;
}
this.lruMoveToFront(key);
this.recordRead(true);
return item;
}
/**
* Gets the raw values of the keys
* @param {string[]} keys - The keys to get the values
* @returns {CacheableStoreItem[]} - The raw values of the keys
*/
getManyRaw(keys) {
const result = [];
for (const key of keys) result.push(this.getRaw(key));
return result;
}
/**
* Sets the value of the key
* @param {string} key - The key to set the value
* @param {any} value - The value to set
* @param {number|string|SetOptions} [ttl] - Time to Live - If you set a number it is miliseconds, if you set a string it is a human-readable.
* If you want to set expire directly you can do that by setting the expire property in the SetOptions.
* If you set undefined, it will use the default time-to-live. If both are undefined then it will not have a time-to-live.
* @returns {void}
*/
set(key, value, ttl) {
const hookItem = {
key,
value,
ttl
};
this.hookSync("BEFORE_SET", hookItem);
const store = this.getStore(hookItem.key);
let expires;
const effectiveTtl = hookItem.ttl;
if (effectiveTtl !== void 0 || this._ttl !== void 0) if (typeof effectiveTtl === "object") {
if (effectiveTtl.expire) expires = typeof effectiveTtl.expire === "number" ? effectiveTtl.expire : effectiveTtl.expire.getTime();
if (effectiveTtl.ttl) {
const finalTtl = (0, _cacheable_utils.shorthandToTime)(effectiveTtl.ttl);
/* v8 ignore next -- @preserve */
if (finalTtl !== void 0) expires = finalTtl;
}
} else {
const finalTtl = (0, _cacheable_utils.shorthandToTime)(effectiveTtl ?? this._ttl);
/* v8 ignore next -- @preserve */
if (finalTtl !== void 0) expires = finalTtl;
}
if (this._maxTtl !== void 0) {
const maxExpires = (0, _cacheable_utils.shorthandToTime)(this._maxTtl);
if (expires === void 0) expires = maxExpires;
else if (expires > maxExpires) expires = maxExpires;
}
if (this._lruSize > 0) if (store.has(hookItem.key)) this.lruMoveToFront(hookItem.key);
else {
this.lruAddToFront(hookItem.key);
if (this._lru.size > this._lruSize) {
const oldestKey = this._lru.getOldest();
/* v8 ignore next -- @preserve */
if (oldestKey) {
this._lru.removeOldest();
this.delete(oldestKey);
}
}
}
if (this._stats.enabled) {
const existing = store.get(hookItem.key);
if (existing) this._stats.decreaseVSize(existing.value);
else {
this._stats.incrementKSize(hookItem.key);
this._stats.incrementCount();
}
this._stats.incrementVSize(hookItem.value);
this._stats.incrementSets();
}
const item = {
key: hookItem.key,
value: hookItem.value,
expires
};
store.set(hookItem.key, item);
this.hookSync("AFTER_SET", hookItem);
}
/**
* Sets the values of the keys
* @param {CacheableItem[]} items - The items to set
* @returns {void}
*/
setMany(items) {
this.hookSync("BEFORE_SET_MANY", items);
for (const item of items) this.set(item.key, item.value, item.ttl);
this.hookSync("AFTER_SET_MANY", items);
}
/**
* Checks if the key exists
* @param {string} key - The key to check
* @returns {boolean} - If true, the key exists. If false, the key does not exist.
*/
has(key) {
const item = this.get(key);
return Boolean(item);
}
/**
* @function hasMany
* @param {string[]} keys - The keys to check
* @returns {boolean[]} - If true, the key exists. If false, the key does not exist.
*/
hasMany(keys) {
const result = [];
for (const key of keys) {
const item = this.get(key);
result.push(Boolean(item));
}
return result;
}
/**
* Take will get the key and delete the entry from cache
* @param {string} key - The key to take
* @returns {T | undefined} - The value of the key
*/
take(key) {
const item = this.get(key);
if (!item) return;
this.delete(key);
return item;
}
/**
* TakeMany will get the keys and delete the entries from cache
* @param {string[]} keys - The keys to take
* @returns {T[]} - The values of the keys
*/
takeMany(keys) {
const result = [];
for (const key of keys) result.push(this.take(key));
return result;
}
/**
* Delete the key
* @param {string} key - The key to delete
* @returns {void}
*/
delete(key) {
this.hookSync("BEFORE_DELETE", key);
const store = this.getStore(key);
if (this._stats.enabled) {
const item = store.get(key);
if (item) {
this._stats.decreaseKSize(key);
this._stats.decreaseVSize(item.value);
this._stats.decreaseCount();
this._stats.incrementDeletes();
}
}
store.delete(key);
this.lruRemove(key);
this.hookSync("AFTER_DELETE", key);
}
/**
* Delete the keys
* @param {string[]} keys - The keys to delete
* @returns {void}
*/
deleteMany(keys) {
this.hookSync("BEFORE_DELETE_MANY", keys);
for (const key of keys) this.delete(key);
this.hookSync("AFTER_DELETE_MANY", keys);
}
/**
* Clear the cache
* @returns {void}
*/
clear() {
this.hookSync("BEFORE_CLEAR");
this._store = Array.from({ length: this._storeHashSize }, () => /* @__PURE__ */ new Map());
this._lru = new DoublyLinkedList();
if (this._stats.enabled) {
this._stats.resetStoreValues();
this._stats.incrementClears();
}
this.hookSync("AFTER_CLEAR");
}
/**
* Get the store based on the key (internal use)
* @param {string} key - The key to get the store
* @returns {CacheableHashStore} - The store
*/
getStore(key) {
const hash = this.getKeyStoreHash(key);
this._store[hash] ||= /* @__PURE__ */ new Map();
return this._store[hash];
}
/**
* Hash the key for which store to go to (internal use)
* @param {string} key - The key to hash
* Available algorithms are: SHA256, SHA1, MD5, and djb2Hash.
* @returns {number} - The hashed key as a number
*/
getKeyStoreHash(key) {
if (this._store.length === 1) return 0;
if (typeof this._storeHashAlgorithm === "function") return this._storeHashAlgorithm(key, this._storeHashSize);
return (0, _cacheable_utils.hashToNumberSync)(key, {
min: 0,
max: this._storeHashSize - 1,
algorithm: this._storeHashAlgorithm
});
}
/**
* Clone the value. This is for internal use
* @param {any} value - The value to clone
* @returns {any} - The cloned value
*/
clone(value) {
if (this.isPrimitive(value)) return value;
return structuredClone(value);
}
/**
* Add to the front of the LRU cache. This is for internal use
* @param {string} key - The key to add to the front
* @returns {void}
*/
lruAddToFront(key) {
if (this._lruSize === 0) return;
this._lru.addToFront(key);
}
/**
* Move to the front of the LRU cache. This is for internal use
* @param {string} key - The key to move to the front
* @returns {void}
*/
lruMoveToFront(key) {
if (this._lruSize === 0) return;
this._lru.moveToFront(key);
}
/**
* Remove a key from the LRU cache. This is for internal use
* @param {string} key - The key to remove
* @returns {void}
*/
lruRemove(key) {
if (this._lruSize === 0) return;
this._lru.remove(key);
}
/**
* Resize the LRU cache. This is for internal use.
* @returns {void}
*/
lruResize() {
while (this._lru.size > this._lruSize) {
const oldestKey = this._lru.getOldest();
/* v8 ignore next -- @preserve */
if (oldestKey) {
this._lru.removeOldest();
this.delete(oldestKey);
}
}
}
/**
* Check for expiration. This is for internal use
* @returns {void}
*/
checkExpiration() {
for (const store of this._store) for (const item of store.values()) if (item.expires && Date.now() > item.expires) {
this.recordExpiration(item);
store.delete(item.key);
this.lruRemove(item.key);
}
}
/**
* Start the interval check. This is for internal use
* @returns {void}
*/
startIntervalCheck() {
if (this._checkInterval > 0) {
/* v8 ignore next -- @preserve */
if (this._interval)
/* v8 ignore next -- @preserve */
clearInterval(this._interval);
this._interval = setInterval(() => {
this.checkExpiration();
}, this._checkInterval).unref();
}
}
/**
* Stop the interval check. This is for internal use
* @returns {void}
*/
stopIntervalCheck() {
/* v8 ignore next -- @preserve */
if (this._interval) clearInterval(this._interval);
this._interval = 0;
this._checkInterval = 0;
}
/**
* Wrap the function for caching
* @param {Function} function_ - The function to wrap
* @param {Object} [options] - The options to wrap
* @returns {Function} - The wrapped function
*/
wrap(function_, options) {
return (0, _cacheable_utils.wrapSync)(function_, {
ttl: options?.ttl ?? this._ttl,
keyPrefix: options?.keyPrefix,
createKey: options?.createKey,
cache: this
});
}
/**
* Gets the value of the key, or computes and stores it on a cache miss. This is the synchronous
* cache-aside helper: if the key is present its value is returned, otherwise `function_` is
* invoked, its result is stored, and that result is returned.
*
* The value is stored using `options.ttl`, falling back to the instance default `ttl`. Because
* the cache is synchronous there is no request coalescing — concurrent callers cannot stampede
* the setter the way they can with an async cache.
* @param {GetOrSetSyncKey} key - The key to get or set. Can also be a function that returns the key.
* @param {() => T} function_ - The function that computes the value on a cache miss.
* @param {GetOrSetFunctionOptions} [options] - Options such as `ttl`, `cacheErrors`, and `throwErrors`.
* @returns {T | undefined} - The cached or freshly computed value
*/
getOrSet(key, function_, options) {
return (0, _cacheable_utils.getOrSetSync)(key, function_, {
cache: this,
ttl: options?.ttl ?? this._ttl,
cacheErrors: options?.cacheErrors,
throwErrors: options?.throwErrors
});
}
/**
* Records a single read against the statistics counters. Each read increments `gets` and either
* `hits` or `misses`. No-op when statistics are disabled. This is for internal use.
* @param {boolean} hit - Whether the read found a (non-expired) value
* @returns {void}
*/
recordRead(hit) {
if (!this._stats.enabled) return;
if (hit) this._stats.incrementHits();
else this._stats.incrementMisses();
this._stats.incrementGets();
}
/**
* Decrements the size statistics (`count`, `ksize`, and `vsize`) for an entry that is being removed
* because it expired. Expirations are not counted as `deletes` since they are not user-initiated.
* No-op when statistics are disabled. This is for internal use.
* @param {CacheableStoreItem} item - The expired item being removed from the store
* @returns {void}
*/
recordExpiration(item) {
if (!this._stats.enabled) return;
this._stats.decreaseKSize(item.key);
this._stats.decreaseVSize(item.value);
this._stats.decreaseCount();
}
isPrimitive(value) {
const result = false;
/* v8 ignore next -- @preserve */
if (value === null || value === void 0) return true;
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return true;
return result;
}
setTtl(ttl) {
if (typeof ttl === "string" || ttl === void 0) this._ttl = ttl;
else if (ttl > 0) this._ttl = ttl;
else this._ttl = void 0;
}
setMaxTtl(maxTtl) {
if (typeof maxTtl === "string" || maxTtl === void 0) this._maxTtl = maxTtl;
else if (maxTtl > 0) this._maxTtl = maxTtl;
else this._maxTtl = void 0;
}
hasExpired(item) {
if (item.expires && Date.now() > item.expires) return true;
return false;
}
};
//#endregion
exports.CacheableMemory = CacheableMemory;
exports.CacheableMemoryHooks = CacheableMemoryHooks;
Object.defineProperty(exports, "HashAlgorithm", {
enumerable: true,
get: function() {
return _cacheable_utils.HashAlgorithm;
}
});
exports.KeyvCacheableMemory = KeyvCacheableMemory;
Object.defineProperty(exports, "Stats", {
enumerable: true,
get: function() {
return _cacheable_utils.Stats;
}
});
exports.createKeyv = createKeyv;
exports.defaultStoreHashSize = defaultStoreHashSize;
Object.defineProperty(exports, "getOrSetSync", {
enumerable: true,
get: function() {
return _cacheable_utils.getOrSetSync;
}
});
Object.defineProperty(exports, "hash", {
enumerable: true,
get: function() {
return _cacheable_utils.hash;
}
});
Object.defineProperty(exports, "hashToNumber", {
enumerable: true,
get: function() {
return _cacheable_utils.hashToNumber;
}
});
exports.maximumMapSize = maximumMapSize;

412
node_modules/@cacheable/memory/dist/index.d.cts generated vendored Normal file
View File

@@ -0,0 +1,412 @@
import { CacheableItem, CacheableItem as CacheableItem$1, CacheableStoreItem, CacheableStoreItem as CacheableStoreItem$1, GetOrSetFunctionOptions, GetOrSetFunctionOptions as GetOrSetFunctionOptions$1, GetOrSetSyncKey, GetOrSetSyncKey as GetOrSetSyncKey$1, GetOrSetSyncOptions, HashAlgorithm, HashAlgorithm as HashAlgorithm$1, Stats, Stats as Stats$1, StatsOptions, StatsSnapshot, WrapFunctionOptions, getOrSetSync, hash, hashToNumber } from "@cacheable/utils";
import { Hookified } from "hookified";
import { Keyv, KeyvStoreAdapter, StoredData } from "keyv";
//#region src/keyv-memory.d.ts
type KeyvCacheableMemoryOptions = CacheableMemoryOptions & {
namespace?: string;
};
declare class KeyvCacheableMemory implements KeyvStoreAdapter {
opts: CacheableMemoryOptions;
private readonly _defaultCache;
private readonly _nCache;
private _namespace?;
constructor(options?: KeyvCacheableMemoryOptions);
get namespace(): string | undefined;
set namespace(value: string | undefined);
get store(): CacheableMemory;
get<Value>(key: string): Promise<StoredData<Value> | undefined>;
getMany<Value>(keys: string[]): Promise<Array<StoredData<Value | undefined>>>;
set(key: string, value: any, ttl?: number): Promise<void>;
setMany(values: Array<{
key: string;
value: any;
ttl?: number;
}>): Promise<void>;
delete(key: string): Promise<boolean>;
deleteMany?(key: string[]): Promise<boolean>;
clear(): Promise<void>;
has?(key: string): Promise<boolean>;
on(event: string, listener: (...arguments_: any[]) => void): this;
getStore(namespace?: string): CacheableMemory;
}
/**
* Creates a new Keyv instance with a new KeyvCacheableMemory store. This also removes the serialize/deserialize methods from the Keyv instance for optimization.
* @param options
* @returns
*/
declare function createKeyv(options?: KeyvCacheableMemoryOptions): Keyv;
//#endregion
//#region src/index.d.ts
/**
* Lifecycle hooks fired by {@link CacheableMemory}. Register handlers with the inherited
* `onHook(hook, handler)` method. Hooks are dispatched synchronously via `hookSync`, which skips
* `async` handler functions entirely — register only synchronous handlers.
*/
declare enum CacheableMemoryHooks {
BEFORE_SET = "BEFORE_SET",
AFTER_SET = "AFTER_SET",
BEFORE_SET_MANY = "BEFORE_SET_MANY",
AFTER_SET_MANY = "AFTER_SET_MANY",
BEFORE_GET = "BEFORE_GET",
AFTER_GET = "AFTER_GET",
BEFORE_GET_MANY = "BEFORE_GET_MANY",
AFTER_GET_MANY = "AFTER_GET_MANY",
BEFORE_DELETE = "BEFORE_DELETE",
AFTER_DELETE = "AFTER_DELETE",
BEFORE_DELETE_MANY = "BEFORE_DELETE_MANY",
AFTER_DELETE_MANY = "AFTER_DELETE_MANY",
BEFORE_CLEAR = "BEFORE_CLEAR",
AFTER_CLEAR = "AFTER_CLEAR"
}
type StoreHashAlgorithmFunction = (key: string, storeHashSize: number) => number;
/**
* @typedef {Object} CacheableMemoryOptions
* @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
* 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
* undefined then it will not have a time-to-live.
* @property {number|string} [maxTtl] - Maximum Time to Live - The upper bound for any TTL set on a cache entry. If a TTL (whether from the
* default or per-entry) exceeds this value, the entry's TTL is capped to maxTtl. Can be a number in milliseconds or a human-readable
* format such as `1s`, `1m`, `1h`, `1d`. Default is `undefined` (no maximum).
* @property {boolean} [useClone] - If true, it will clone the value before returning it. If false, it will return the value directly. Default is true.
* @property {number} [lruSize] - The size of the LRU cache. If set to 0, it will not use LRU cache. Default is 0. If you are using LRU then the limit is based on Map() size 17mm.
* @property {number} [checkInterval] - The interval to check for expired items. If set to 0, it will not check for expired items. Default is 0.
* @property {number} [storeHashSize] - The number of how many Map stores we have for the hash. Default is 10.
* @property {boolean} [stats] - If true, it will track statistics such as hits, misses, gets, sets, and deletes for this
* instance. Statistics are accessible via the `stats` property. Default is `false`.
*/
type CacheableMemoryOptions = {
ttl?: number | string;
maxTtl?: number | string;
useClone?: boolean;
lruSize?: number;
checkInterval?: number;
storeHashSize?: number;
storeHashAlgorithm?: HashAlgorithm$1 | ((key: string, storeHashSize: number) => number);
stats?: boolean;
};
type SetOptions = {
ttl?: number | string;
expire?: number | Date;
};
/**
* The payload passed to the `BEFORE_SET` and `AFTER_SET` hooks. Inside a `BEFORE_SET` handler
* you can reassign `key`, `value`, or `ttl` to change what gets stored.
*/
type CacheableMemoryHookItem<T = unknown> = {
key: string;
value: T;
ttl?: number | string | SetOptions;
};
/** The payload passed to the `AFTER_GET` hook. `result` is `undefined` on a cache miss. */
type CacheableMemoryAfterGetItem<T = unknown> = {
key: string;
result: T | undefined;
};
/**
* The payload passed to the `AFTER_GET_MANY` hook. Entries are `undefined` for keys that were
* missing or expired, mirroring what `getMany` collects.
*/
type CacheableMemoryAfterGetManyItem<T = unknown> = {
keys: string[];
result: Array<T | undefined>;
};
declare const defaultStoreHashSize = 16;
declare const maximumMapSize = 16777216;
declare class CacheableMemory extends Hookified {
private _lru;
private _storeHashSize;
private _storeHashAlgorithm;
private _store;
private _ttl;
private _maxTtl;
private _useClone;
private _lruSize;
private _checkInterval;
private _interval;
private readonly _stats;
/**
* @constructor
* @param {CacheableMemoryOptions} [options] - The options for the CacheableMemory
*/
constructor(options?: CacheableMemoryOptions);
/**
* Gets the time-to-live
* @returns {number|string|undefined} - The time-to-live in miliseconds or a human-readable format. If undefined, it will not have a time-to-live.
*/
get ttl(): number | string | undefined;
/**
* Sets the time-to-live
* @param {number|string|undefined} value - The time-to-live in miliseconds or a human-readable format (example '1s' = 1 second, '1h' = 1 hour). If undefined, it will not have a time-to-live.
*/
set ttl(value: number | string | undefined);
/**
* Gets the maximum time-to-live. When set, any TTL that exceeds this value is capped to maxTtl.
* Entries with no TTL will also be capped to maxTtl. Default is `undefined` (no maximum).
* @returns {number|string|undefined} - The maximum TTL in milliseconds, human-readable format, or undefined.
*/
get maxTtl(): number | string | undefined;
/**
* Sets the maximum time-to-live. When set, any TTL that exceeds this value is capped to maxTtl.
* Entries with no TTL will also be capped to maxTtl.
* @param {number|string|undefined} value - The maximum TTL in milliseconds or human-readable format (e.g. '1s', '1h'). If undefined, no maximum is enforced.
*/
set maxTtl(value: number | string | undefined);
/**
* Gets whether to use clone
* @returns {boolean} - If true, it will clone the value before returning it. If false, it will return the value directly. Default is true.
*/
get useClone(): boolean;
/**
* Sets whether to use clone
* @param {boolean} value - If true, it will clone the value before returning it. If false, it will return the value directly. Default is true.
*/
set useClone(value: boolean);
/**
* Gets the size of the LRU cache
* @returns {number} - The size of the LRU cache. If set to 0, it will not use LRU cache. Default is 0. If you are using LRU then the limit is based on Map() size 17mm.
*/
get lruSize(): number;
/**
* Sets the size of the LRU cache
* @param {number} value - The size of the LRU cache. If set to 0, it will not use LRU cache. Default is 0. If you are using LRU then the limit is based on Map() size 17mm.
*/
set lruSize(value: number);
/**
* Gets the check interval
* @returns {number} - The interval to check for expired items. If set to 0, it will not check for expired items. Default is 0.
*/
get checkInterval(): number;
/**
* Sets the check interval
* @param {number} value - The interval to check for expired items. If set to 0, it will not check for expired items. Default is 0.
*/
set checkInterval(value: number);
/**
* Gets the size of the cache
* @returns {number} - The size of the cache
*/
get size(): number;
/**
* Gets the statistics of the cache. Statistics track aggregate counters such as `hits`, `misses`,
* `gets`, `sets`, `deletes`, `clears`, `count`, `ksize`, and `vsize`. They are disabled by default;
* enable them via the `stats` option or by setting `cache.stats.enabled = true`.
* @returns {Stats} - The statistics for this CacheableMemory instance
*/
get stats(): Stats$1;
/**
* Gets the number of hash stores
* @returns {number} - The number of hash stores
*/
get storeHashSize(): number;
/**
* Sets the number of hash stores. This will recreate the store and all data will be cleared
* @param {number} value - The number of hash stores
*/
set storeHashSize(value: number);
/**
* Gets the store hash algorithm
* @returns {HashAlgorithm | StoreHashAlgorithmFunction} - The store hash algorithm
*/
get storeHashAlgorithm(): HashAlgorithm$1 | StoreHashAlgorithmFunction;
/**
* Sets the store hash algorithm. This will recreate the store and all data will be cleared
* @param {HashAlgorithm | HashAlgorithmFunction} value - The store hash algorithm
*/
set storeHashAlgorithm(value: HashAlgorithm$1 | StoreHashAlgorithmFunction);
/**
* Gets the keys
* @returns {IterableIterator<string>} - The keys
*/
get keys(): IterableIterator<string>;
/**
* Gets the items
* @returns {IterableIterator<CacheableStoreItem>} - The items
*/
get items(): IterableIterator<CacheableStoreItem$1>;
/**
* Gets the store
* @returns {Array<Map<string, CacheableStoreItem>>} - The store
*/
get store(): Array<Map<string, CacheableStoreItem$1>>;
/**
* Gets the value of the key
* @param {string} key - The key to get the value
* @returns {T | undefined} - The value of the key
*/
get<T>(key: string): T | undefined;
/**
* Gets the values of the keys
* @param {string[]} keys - The keys to get the values
* @returns {T[]} - The values of the keys
*/
getMany<T>(keys: string[]): T[];
/**
* Gets the raw value of the key
* @param {string} key - The key to get the value
* @returns {CacheableStoreItem | undefined} - The raw value of the key
*/
getRaw(key: string): CacheableStoreItem$1 | undefined;
/**
* Gets the raw values of the keys
* @param {string[]} keys - The keys to get the values
* @returns {CacheableStoreItem[]} - The raw values of the keys
*/
getManyRaw(keys: string[]): Array<CacheableStoreItem$1 | undefined>;
/**
* Sets the value of the key
* @param {string} key - The key to set the value
* @param {any} value - The value to set
* @param {number|string|SetOptions} [ttl] - Time to Live - If you set a number it is miliseconds, if you set a string it is a human-readable.
* If you want to set expire directly you can do that by setting the expire property in the SetOptions.
* If you set undefined, it will use the default time-to-live. If both are undefined then it will not have a time-to-live.
* @returns {void}
*/
set(key: string, value: any, ttl?: number | string | SetOptions): void;
/**
* Sets the values of the keys
* @param {CacheableItem[]} items - The items to set
* @returns {void}
*/
setMany(items: CacheableItem$1[]): void;
/**
* Checks if the key exists
* @param {string} key - The key to check
* @returns {boolean} - If true, the key exists. If false, the key does not exist.
*/
has(key: string): boolean;
/**
* @function hasMany
* @param {string[]} keys - The keys to check
* @returns {boolean[]} - If true, the key exists. If false, the key does not exist.
*/
hasMany(keys: string[]): boolean[];
/**
* Take will get the key and delete the entry from cache
* @param {string} key - The key to take
* @returns {T | undefined} - The value of the key
*/
take<T>(key: string): T | undefined;
/**
* TakeMany will get the keys and delete the entries from cache
* @param {string[]} keys - The keys to take
* @returns {T[]} - The values of the keys
*/
takeMany<T>(keys: string[]): T[];
/**
* Delete the key
* @param {string} key - The key to delete
* @returns {void}
*/
delete(key: string): void;
/**
* Delete the keys
* @param {string[]} keys - The keys to delete
* @returns {void}
*/
deleteMany(keys: string[]): void;
/**
* Clear the cache
* @returns {void}
*/
clear(): void;
/**
* Get the store based on the key (internal use)
* @param {string} key - The key to get the store
* @returns {CacheableHashStore} - The store
*/
getStore(key: string): Map<string, CacheableStoreItem$1>;
/**
* Hash the key for which store to go to (internal use)
* @param {string} key - The key to hash
* Available algorithms are: SHA256, SHA1, MD5, and djb2Hash.
* @returns {number} - The hashed key as a number
*/
getKeyStoreHash(key: string): number;
/**
* Clone the value. This is for internal use
* @param {any} value - The value to clone
* @returns {any} - The cloned value
*/
clone(value: any): any;
/**
* Add to the front of the LRU cache. This is for internal use
* @param {string} key - The key to add to the front
* @returns {void}
*/
lruAddToFront(key: string): void;
/**
* Move to the front of the LRU cache. This is for internal use
* @param {string} key - The key to move to the front
* @returns {void}
*/
lruMoveToFront(key: string): void;
/**
* Remove a key from the LRU cache. This is for internal use
* @param {string} key - The key to remove
* @returns {void}
*/
lruRemove(key: string): void;
/**
* Resize the LRU cache. This is for internal use.
* @returns {void}
*/
lruResize(): void;
/**
* Check for expiration. This is for internal use
* @returns {void}
*/
checkExpiration(): void;
/**
* Start the interval check. This is for internal use
* @returns {void}
*/
startIntervalCheck(): void;
/**
* Stop the interval check. This is for internal use
* @returns {void}
*/
stopIntervalCheck(): void;
/**
* Wrap the function for caching
* @param {Function} function_ - The function to wrap
* @param {Object} [options] - The options to wrap
* @returns {Function} - The wrapped function
*/
wrap<T, Arguments extends any[]>(function_: (...arguments_: Arguments) => T, options?: WrapFunctionOptions): (...arguments_: Arguments) => T;
/**
* Gets the value of the key, or computes and stores it on a cache miss. This is the synchronous
* cache-aside helper: if the key is present its value is returned, otherwise `function_` is
* invoked, its result is stored, and that result is returned.
*
* The value is stored using `options.ttl`, falling back to the instance default `ttl`. Because
* the cache is synchronous there is no request coalescing — concurrent callers cannot stampede
* the setter the way they can with an async cache.
* @param {GetOrSetSyncKey} key - The key to get or set. Can also be a function that returns the key.
* @param {() => T} function_ - The function that computes the value on a cache miss.
* @param {GetOrSetFunctionOptions} [options] - Options such as `ttl`, `cacheErrors`, and `throwErrors`.
* @returns {T | undefined} - The cached or freshly computed value
*/
getOrSet<T>(key: GetOrSetSyncKey$1, function_: () => T, options?: GetOrSetFunctionOptions$1): T | undefined;
/**
* Records a single read against the statistics counters. Each read increments `gets` and either
* `hits` or `misses`. No-op when statistics are disabled. This is for internal use.
* @param {boolean} hit - Whether the read found a (non-expired) value
* @returns {void}
*/
private recordRead;
/**
* Decrements the size statistics (`count`, `ksize`, and `vsize`) for an entry that is being removed
* because it expired. Expirations are not counted as `deletes` since they are not user-initiated.
* No-op when statistics are disabled. This is for internal use.
* @param {CacheableStoreItem} item - The expired item being removed from the store
* @returns {void}
*/
private recordExpiration;
private isPrimitive;
private setTtl;
private setMaxTtl;
private hasExpired;
}
//#endregion
export { type CacheableItem, CacheableMemory, CacheableMemoryAfterGetItem, CacheableMemoryAfterGetManyItem, CacheableMemoryHookItem, CacheableMemoryHooks, CacheableMemoryOptions, type CacheableStoreItem, type GetOrSetFunctionOptions, type GetOrSetSyncKey, type GetOrSetSyncOptions, HashAlgorithm, KeyvCacheableMemory, type KeyvCacheableMemoryOptions, SetOptions, Stats, type StatsOptions, type StatsSnapshot, StoreHashAlgorithmFunction, createKeyv, defaultStoreHashSize, getOrSetSync, hash, hashToNumber, maximumMapSize };

412
node_modules/@cacheable/memory/dist/index.d.mts generated vendored Normal file
View File

@@ -0,0 +1,412 @@
import { CacheableItem, CacheableItem as CacheableItem$1, CacheableStoreItem, CacheableStoreItem as CacheableStoreItem$1, GetOrSetFunctionOptions, GetOrSetFunctionOptions as GetOrSetFunctionOptions$1, GetOrSetSyncKey, GetOrSetSyncKey as GetOrSetSyncKey$1, GetOrSetSyncOptions, HashAlgorithm, HashAlgorithm as HashAlgorithm$1, Stats, Stats as Stats$1, StatsOptions, StatsSnapshot, WrapFunctionOptions, getOrSetSync, hash, hashToNumber } from "@cacheable/utils";
import { Hookified } from "hookified";
import { Keyv, KeyvStoreAdapter, StoredData } from "keyv";
//#region src/keyv-memory.d.ts
type KeyvCacheableMemoryOptions = CacheableMemoryOptions & {
namespace?: string;
};
declare class KeyvCacheableMemory implements KeyvStoreAdapter {
opts: CacheableMemoryOptions;
private readonly _defaultCache;
private readonly _nCache;
private _namespace?;
constructor(options?: KeyvCacheableMemoryOptions);
get namespace(): string | undefined;
set namespace(value: string | undefined);
get store(): CacheableMemory;
get<Value>(key: string): Promise<StoredData<Value> | undefined>;
getMany<Value>(keys: string[]): Promise<Array<StoredData<Value | undefined>>>;
set(key: string, value: any, ttl?: number): Promise<void>;
setMany(values: Array<{
key: string;
value: any;
ttl?: number;
}>): Promise<void>;
delete(key: string): Promise<boolean>;
deleteMany?(key: string[]): Promise<boolean>;
clear(): Promise<void>;
has?(key: string): Promise<boolean>;
on(event: string, listener: (...arguments_: any[]) => void): this;
getStore(namespace?: string): CacheableMemory;
}
/**
* Creates a new Keyv instance with a new KeyvCacheableMemory store. This also removes the serialize/deserialize methods from the Keyv instance for optimization.
* @param options
* @returns
*/
declare function createKeyv(options?: KeyvCacheableMemoryOptions): Keyv;
//#endregion
//#region src/index.d.ts
/**
* Lifecycle hooks fired by {@link CacheableMemory}. Register handlers with the inherited
* `onHook(hook, handler)` method. Hooks are dispatched synchronously via `hookSync`, which skips
* `async` handler functions entirely — register only synchronous handlers.
*/
declare enum CacheableMemoryHooks {
BEFORE_SET = "BEFORE_SET",
AFTER_SET = "AFTER_SET",
BEFORE_SET_MANY = "BEFORE_SET_MANY",
AFTER_SET_MANY = "AFTER_SET_MANY",
BEFORE_GET = "BEFORE_GET",
AFTER_GET = "AFTER_GET",
BEFORE_GET_MANY = "BEFORE_GET_MANY",
AFTER_GET_MANY = "AFTER_GET_MANY",
BEFORE_DELETE = "BEFORE_DELETE",
AFTER_DELETE = "AFTER_DELETE",
BEFORE_DELETE_MANY = "BEFORE_DELETE_MANY",
AFTER_DELETE_MANY = "AFTER_DELETE_MANY",
BEFORE_CLEAR = "BEFORE_CLEAR",
AFTER_CLEAR = "AFTER_CLEAR"
}
type StoreHashAlgorithmFunction = (key: string, storeHashSize: number) => number;
/**
* @typedef {Object} CacheableMemoryOptions
* @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
* 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
* undefined then it will not have a time-to-live.
* @property {number|string} [maxTtl] - Maximum Time to Live - The upper bound for any TTL set on a cache entry. If a TTL (whether from the
* default or per-entry) exceeds this value, the entry's TTL is capped to maxTtl. Can be a number in milliseconds or a human-readable
* format such as `1s`, `1m`, `1h`, `1d`. Default is `undefined` (no maximum).
* @property {boolean} [useClone] - If true, it will clone the value before returning it. If false, it will return the value directly. Default is true.
* @property {number} [lruSize] - The size of the LRU cache. If set to 0, it will not use LRU cache. Default is 0. If you are using LRU then the limit is based on Map() size 17mm.
* @property {number} [checkInterval] - The interval to check for expired items. If set to 0, it will not check for expired items. Default is 0.
* @property {number} [storeHashSize] - The number of how many Map stores we have for the hash. Default is 10.
* @property {boolean} [stats] - If true, it will track statistics such as hits, misses, gets, sets, and deletes for this
* instance. Statistics are accessible via the `stats` property. Default is `false`.
*/
type CacheableMemoryOptions = {
ttl?: number | string;
maxTtl?: number | string;
useClone?: boolean;
lruSize?: number;
checkInterval?: number;
storeHashSize?: number;
storeHashAlgorithm?: HashAlgorithm$1 | ((key: string, storeHashSize: number) => number);
stats?: boolean;
};
type SetOptions = {
ttl?: number | string;
expire?: number | Date;
};
/**
* The payload passed to the `BEFORE_SET` and `AFTER_SET` hooks. Inside a `BEFORE_SET` handler
* you can reassign `key`, `value`, or `ttl` to change what gets stored.
*/
type CacheableMemoryHookItem<T = unknown> = {
key: string;
value: T;
ttl?: number | string | SetOptions;
};
/** The payload passed to the `AFTER_GET` hook. `result` is `undefined` on a cache miss. */
type CacheableMemoryAfterGetItem<T = unknown> = {
key: string;
result: T | undefined;
};
/**
* The payload passed to the `AFTER_GET_MANY` hook. Entries are `undefined` for keys that were
* missing or expired, mirroring what `getMany` collects.
*/
type CacheableMemoryAfterGetManyItem<T = unknown> = {
keys: string[];
result: Array<T | undefined>;
};
declare const defaultStoreHashSize = 16;
declare const maximumMapSize = 16777216;
declare class CacheableMemory extends Hookified {
private _lru;
private _storeHashSize;
private _storeHashAlgorithm;
private _store;
private _ttl;
private _maxTtl;
private _useClone;
private _lruSize;
private _checkInterval;
private _interval;
private readonly _stats;
/**
* @constructor
* @param {CacheableMemoryOptions} [options] - The options for the CacheableMemory
*/
constructor(options?: CacheableMemoryOptions);
/**
* Gets the time-to-live
* @returns {number|string|undefined} - The time-to-live in miliseconds or a human-readable format. If undefined, it will not have a time-to-live.
*/
get ttl(): number | string | undefined;
/**
* Sets the time-to-live
* @param {number|string|undefined} value - The time-to-live in miliseconds or a human-readable format (example '1s' = 1 second, '1h' = 1 hour). If undefined, it will not have a time-to-live.
*/
set ttl(value: number | string | undefined);
/**
* Gets the maximum time-to-live. When set, any TTL that exceeds this value is capped to maxTtl.
* Entries with no TTL will also be capped to maxTtl. Default is `undefined` (no maximum).
* @returns {number|string|undefined} - The maximum TTL in milliseconds, human-readable format, or undefined.
*/
get maxTtl(): number | string | undefined;
/**
* Sets the maximum time-to-live. When set, any TTL that exceeds this value is capped to maxTtl.
* Entries with no TTL will also be capped to maxTtl.
* @param {number|string|undefined} value - The maximum TTL in milliseconds or human-readable format (e.g. '1s', '1h'). If undefined, no maximum is enforced.
*/
set maxTtl(value: number | string | undefined);
/**
* Gets whether to use clone
* @returns {boolean} - If true, it will clone the value before returning it. If false, it will return the value directly. Default is true.
*/
get useClone(): boolean;
/**
* Sets whether to use clone
* @param {boolean} value - If true, it will clone the value before returning it. If false, it will return the value directly. Default is true.
*/
set useClone(value: boolean);
/**
* Gets the size of the LRU cache
* @returns {number} - The size of the LRU cache. If set to 0, it will not use LRU cache. Default is 0. If you are using LRU then the limit is based on Map() size 17mm.
*/
get lruSize(): number;
/**
* Sets the size of the LRU cache
* @param {number} value - The size of the LRU cache. If set to 0, it will not use LRU cache. Default is 0. If you are using LRU then the limit is based on Map() size 17mm.
*/
set lruSize(value: number);
/**
* Gets the check interval
* @returns {number} - The interval to check for expired items. If set to 0, it will not check for expired items. Default is 0.
*/
get checkInterval(): number;
/**
* Sets the check interval
* @param {number} value - The interval to check for expired items. If set to 0, it will not check for expired items. Default is 0.
*/
set checkInterval(value: number);
/**
* Gets the size of the cache
* @returns {number} - The size of the cache
*/
get size(): number;
/**
* Gets the statistics of the cache. Statistics track aggregate counters such as `hits`, `misses`,
* `gets`, `sets`, `deletes`, `clears`, `count`, `ksize`, and `vsize`. They are disabled by default;
* enable them via the `stats` option or by setting `cache.stats.enabled = true`.
* @returns {Stats} - The statistics for this CacheableMemory instance
*/
get stats(): Stats$1;
/**
* Gets the number of hash stores
* @returns {number} - The number of hash stores
*/
get storeHashSize(): number;
/**
* Sets the number of hash stores. This will recreate the store and all data will be cleared
* @param {number} value - The number of hash stores
*/
set storeHashSize(value: number);
/**
* Gets the store hash algorithm
* @returns {HashAlgorithm | StoreHashAlgorithmFunction} - The store hash algorithm
*/
get storeHashAlgorithm(): HashAlgorithm$1 | StoreHashAlgorithmFunction;
/**
* Sets the store hash algorithm. This will recreate the store and all data will be cleared
* @param {HashAlgorithm | HashAlgorithmFunction} value - The store hash algorithm
*/
set storeHashAlgorithm(value: HashAlgorithm$1 | StoreHashAlgorithmFunction);
/**
* Gets the keys
* @returns {IterableIterator<string>} - The keys
*/
get keys(): IterableIterator<string>;
/**
* Gets the items
* @returns {IterableIterator<CacheableStoreItem>} - The items
*/
get items(): IterableIterator<CacheableStoreItem$1>;
/**
* Gets the store
* @returns {Array<Map<string, CacheableStoreItem>>} - The store
*/
get store(): Array<Map<string, CacheableStoreItem$1>>;
/**
* Gets the value of the key
* @param {string} key - The key to get the value
* @returns {T | undefined} - The value of the key
*/
get<T>(key: string): T | undefined;
/**
* Gets the values of the keys
* @param {string[]} keys - The keys to get the values
* @returns {T[]} - The values of the keys
*/
getMany<T>(keys: string[]): T[];
/**
* Gets the raw value of the key
* @param {string} key - The key to get the value
* @returns {CacheableStoreItem | undefined} - The raw value of the key
*/
getRaw(key: string): CacheableStoreItem$1 | undefined;
/**
* Gets the raw values of the keys
* @param {string[]} keys - The keys to get the values
* @returns {CacheableStoreItem[]} - The raw values of the keys
*/
getManyRaw(keys: string[]): Array<CacheableStoreItem$1 | undefined>;
/**
* Sets the value of the key
* @param {string} key - The key to set the value
* @param {any} value - The value to set
* @param {number|string|SetOptions} [ttl] - Time to Live - If you set a number it is miliseconds, if you set a string it is a human-readable.
* If you want to set expire directly you can do that by setting the expire property in the SetOptions.
* If you set undefined, it will use the default time-to-live. If both are undefined then it will not have a time-to-live.
* @returns {void}
*/
set(key: string, value: any, ttl?: number | string | SetOptions): void;
/**
* Sets the values of the keys
* @param {CacheableItem[]} items - The items to set
* @returns {void}
*/
setMany(items: CacheableItem$1[]): void;
/**
* Checks if the key exists
* @param {string} key - The key to check
* @returns {boolean} - If true, the key exists. If false, the key does not exist.
*/
has(key: string): boolean;
/**
* @function hasMany
* @param {string[]} keys - The keys to check
* @returns {boolean[]} - If true, the key exists. If false, the key does not exist.
*/
hasMany(keys: string[]): boolean[];
/**
* Take will get the key and delete the entry from cache
* @param {string} key - The key to take
* @returns {T | undefined} - The value of the key
*/
take<T>(key: string): T | undefined;
/**
* TakeMany will get the keys and delete the entries from cache
* @param {string[]} keys - The keys to take
* @returns {T[]} - The values of the keys
*/
takeMany<T>(keys: string[]): T[];
/**
* Delete the key
* @param {string} key - The key to delete
* @returns {void}
*/
delete(key: string): void;
/**
* Delete the keys
* @param {string[]} keys - The keys to delete
* @returns {void}
*/
deleteMany(keys: string[]): void;
/**
* Clear the cache
* @returns {void}
*/
clear(): void;
/**
* Get the store based on the key (internal use)
* @param {string} key - The key to get the store
* @returns {CacheableHashStore} - The store
*/
getStore(key: string): Map<string, CacheableStoreItem$1>;
/**
* Hash the key for which store to go to (internal use)
* @param {string} key - The key to hash
* Available algorithms are: SHA256, SHA1, MD5, and djb2Hash.
* @returns {number} - The hashed key as a number
*/
getKeyStoreHash(key: string): number;
/**
* Clone the value. This is for internal use
* @param {any} value - The value to clone
* @returns {any} - The cloned value
*/
clone(value: any): any;
/**
* Add to the front of the LRU cache. This is for internal use
* @param {string} key - The key to add to the front
* @returns {void}
*/
lruAddToFront(key: string): void;
/**
* Move to the front of the LRU cache. This is for internal use
* @param {string} key - The key to move to the front
* @returns {void}
*/
lruMoveToFront(key: string): void;
/**
* Remove a key from the LRU cache. This is for internal use
* @param {string} key - The key to remove
* @returns {void}
*/
lruRemove(key: string): void;
/**
* Resize the LRU cache. This is for internal use.
* @returns {void}
*/
lruResize(): void;
/**
* Check for expiration. This is for internal use
* @returns {void}
*/
checkExpiration(): void;
/**
* Start the interval check. This is for internal use
* @returns {void}
*/
startIntervalCheck(): void;
/**
* Stop the interval check. This is for internal use
* @returns {void}
*/
stopIntervalCheck(): void;
/**
* Wrap the function for caching
* @param {Function} function_ - The function to wrap
* @param {Object} [options] - The options to wrap
* @returns {Function} - The wrapped function
*/
wrap<T, Arguments extends any[]>(function_: (...arguments_: Arguments) => T, options?: WrapFunctionOptions): (...arguments_: Arguments) => T;
/**
* Gets the value of the key, or computes and stores it on a cache miss. This is the synchronous
* cache-aside helper: if the key is present its value is returned, otherwise `function_` is
* invoked, its result is stored, and that result is returned.
*
* The value is stored using `options.ttl`, falling back to the instance default `ttl`. Because
* the cache is synchronous there is no request coalescing — concurrent callers cannot stampede
* the setter the way they can with an async cache.
* @param {GetOrSetSyncKey} key - The key to get or set. Can also be a function that returns the key.
* @param {() => T} function_ - The function that computes the value on a cache miss.
* @param {GetOrSetFunctionOptions} [options] - Options such as `ttl`, `cacheErrors`, and `throwErrors`.
* @returns {T | undefined} - The cached or freshly computed value
*/
getOrSet<T>(key: GetOrSetSyncKey$1, function_: () => T, options?: GetOrSetFunctionOptions$1): T | undefined;
/**
* Records a single read against the statistics counters. Each read increments `gets` and either
* `hits` or `misses`. No-op when statistics are disabled. This is for internal use.
* @param {boolean} hit - Whether the read found a (non-expired) value
* @returns {void}
*/
private recordRead;
/**
* Decrements the size statistics (`count`, `ksize`, and `vsize`) for an entry that is being removed
* because it expired. Expirations are not counted as `deletes` since they are not user-initiated.
* No-op when statistics are disabled. This is for internal use.
* @param {CacheableStoreItem} item - The expired item being removed from the store
* @returns {void}
*/
private recordExpiration;
private isPrimitive;
private setTtl;
private setMaxTtl;
private hasExpired;
}
//#endregion
export { type CacheableItem, CacheableMemory, CacheableMemoryAfterGetItem, CacheableMemoryAfterGetManyItem, CacheableMemoryHookItem, CacheableMemoryHooks, CacheableMemoryOptions, type CacheableStoreItem, type GetOrSetFunctionOptions, type GetOrSetSyncKey, type GetOrSetSyncOptions, HashAlgorithm, KeyvCacheableMemory, type KeyvCacheableMemoryOptions, SetOptions, Stats, type StatsOptions, type StatsSnapshot, StoreHashAlgorithmFunction, createKeyv, defaultStoreHashSize, getOrSetSync, hash, hashToNumber, maximumMapSize };

841
node_modules/@cacheable/memory/dist/index.mjs generated vendored Normal file
View File

@@ -0,0 +1,841 @@
import { HashAlgorithm, HashAlgorithm as HashAlgorithm$1, Stats, Stats as Stats$1, getOrSetSync, getOrSetSync as getOrSetSync$1, hash, hashToNumber, hashToNumberSync, shorthandToTime, wrapSync } from "@cacheable/utils";
import { Hookified } from "hookified";
import { Keyv } from "keyv";
//#region src/memory-lru.ts
var ListNode = class {
value;
prev = void 0;
next = void 0;
constructor(value) {
this.value = value;
}
};
var DoublyLinkedList = class {
head = void 0;
tail = void 0;
nodesMap = /* @__PURE__ */ new Map();
addToFront(value) {
const newNode = new ListNode(value);
if (this.head) {
newNode.next = this.head;
this.head.prev = newNode;
this.head = newNode;
} else this.head = this.tail = newNode;
this.nodesMap.set(value, newNode);
}
moveToFront(value) {
const node = this.nodesMap.get(value);
if (!node || this.head === node) return;
/* v8 ignore next -- @preserve */
if (node.prev) node.prev.next = node.next;
/* v8 ignore next -- @preserve */
if (node.next) node.next.prev = node.prev;
/* v8 ignore next -- @preserve */
if (node === this.tail) this.tail = node.prev;
node.prev = void 0;
node.next = this.head;
/* v8 ignore next -- @preserve */
if (this.head) this.head.prev = node;
this.head = node;
this.tail ??= node;
}
getOldest() {
/* v8 ignore next -- @preserve */
return this.tail ? this.tail.value : void 0;
}
removeOldest() {
/* v8 ignore next -- @preserve */
if (!this.tail) return;
const oldValue = this.tail.value;
/* v8 ignore next -- @preserve */
if (this.tail.prev) {
this.tail = this.tail.prev;
this.tail.next = void 0;
} else
/* v8 ignore next -- @preserve */
this.head = this.tail = void 0;
this.nodesMap.delete(oldValue);
return oldValue;
}
remove(value) {
const node = this.nodesMap.get(value);
if (!node) return false;
if (node.prev) node.prev.next = node.next;
else {
this.head = node.next;
if (this.head) this.head.prev = void 0;
}
if (node.next) node.next.prev = node.prev;
else {
this.tail = node.prev;
if (this.tail) this.tail.next = void 0;
}
this.nodesMap.delete(value);
return true;
}
get size() {
return this.nodesMap.size;
}
};
//#endregion
//#region src/keyv-memory.ts
var KeyvCacheableMemory = class {
opts = {
ttl: 0,
useClone: true,
lruSize: 0,
checkInterval: 0
};
_defaultCache = new CacheableMemory();
_nCache = /* @__PURE__ */ new Map();
_namespace;
constructor(options) {
if (options) {
this.opts = options;
this._defaultCache = new CacheableMemory(options);
if (options.namespace) {
this._namespace = options.namespace;
this._nCache.set(this._namespace, new CacheableMemory(options));
}
}
}
get namespace() {
return this._namespace;
}
set namespace(value) {
this._namespace = value;
}
get store() {
return this.getStore(this._namespace);
}
async get(key) {
const result = this.getStore(this._namespace).get(key);
if (result) return result;
}
async getMany(keys) {
return this.getStore(this._namespace).getMany(keys);
}
async set(key, value, ttl) {
this.getStore(this._namespace).set(key, value, ttl);
}
async setMany(values) {
this.getStore(this._namespace).setMany(values);
}
async delete(key) {
this.getStore(this._namespace).delete(key);
return true;
}
async deleteMany(key) {
this.getStore(this._namespace).deleteMany(key);
return true;
}
async clear() {
this.getStore(this._namespace).clear();
}
async has(key) {
return this.getStore(this._namespace).has(key);
}
on(event, listener) {
this.getStore(this._namespace).on(event, listener);
return this;
}
getStore(namespace) {
if (!namespace) return this._defaultCache;
if (!this._nCache.has(namespace)) this._nCache.set(namespace, new CacheableMemory(this.opts));
return this._nCache.get(namespace);
}
};
/**
* Creates a new Keyv instance with a new KeyvCacheableMemory store. This also removes the serialize/deserialize methods from the Keyv instance for optimization.
* @param options
* @returns
*/
function createKeyv(options) {
const store = new KeyvCacheableMemory(options);
const namespace = options?.namespace;
let ttl;
/* v8 ignore next -- @preserve */
if (options?.ttl && Number.isInteger(options.ttl)) ttl = options?.ttl;
const keyv = new Keyv({
store,
namespace,
ttl
});
keyv.serialize = void 0;
keyv.deserialize = void 0;
return keyv;
}
//#endregion
//#region src/index.ts
/**
* Lifecycle hooks fired by {@link CacheableMemory}. Register handlers with the inherited
* `onHook(hook, handler)` method. Hooks are dispatched synchronously via `hookSync`, which skips
* `async` handler functions entirely — register only synchronous handlers.
*/
let CacheableMemoryHooks = /* @__PURE__ */ function(CacheableMemoryHooks) {
CacheableMemoryHooks["BEFORE_SET"] = "BEFORE_SET";
CacheableMemoryHooks["AFTER_SET"] = "AFTER_SET";
CacheableMemoryHooks["BEFORE_SET_MANY"] = "BEFORE_SET_MANY";
CacheableMemoryHooks["AFTER_SET_MANY"] = "AFTER_SET_MANY";
CacheableMemoryHooks["BEFORE_GET"] = "BEFORE_GET";
CacheableMemoryHooks["AFTER_GET"] = "AFTER_GET";
CacheableMemoryHooks["BEFORE_GET_MANY"] = "BEFORE_GET_MANY";
CacheableMemoryHooks["AFTER_GET_MANY"] = "AFTER_GET_MANY";
CacheableMemoryHooks["BEFORE_DELETE"] = "BEFORE_DELETE";
CacheableMemoryHooks["AFTER_DELETE"] = "AFTER_DELETE";
CacheableMemoryHooks["BEFORE_DELETE_MANY"] = "BEFORE_DELETE_MANY";
CacheableMemoryHooks["AFTER_DELETE_MANY"] = "AFTER_DELETE_MANY";
CacheableMemoryHooks["BEFORE_CLEAR"] = "BEFORE_CLEAR";
CacheableMemoryHooks["AFTER_CLEAR"] = "AFTER_CLEAR";
return CacheableMemoryHooks;
}({});
const defaultStoreHashSize = 16;
const maximumMapSize = 16777216;
var CacheableMemory = class extends Hookified {
_lru = new DoublyLinkedList();
_storeHashSize = 16;
_storeHashAlgorithm = HashAlgorithm$1.DJB2;
_store = Array.from({ length: this._storeHashSize }, () => /* @__PURE__ */ new Map());
_ttl;
_maxTtl;
_useClone = true;
_lruSize = 0;
_checkInterval = 0;
_interval = 0;
_stats = new Stats$1({ enabled: false });
/**
* @constructor
* @param {CacheableMemoryOptions} [options] - The options for the CacheableMemory
*/
constructor(options) {
super();
if (options?.ttl) this.setTtl(options.ttl);
if (options?.maxTtl !== void 0) this.setMaxTtl(options.maxTtl);
if (options?.useClone !== void 0) this._useClone = options.useClone;
if (options?.stats) this._stats.enabled = options.stats;
if (options?.storeHashSize && options.storeHashSize > 0) this._storeHashSize = options.storeHashSize;
if (options?.lruSize) if (options.lruSize > 16777216) this.emit("error", /* @__PURE__ */ new Error(`LRU size cannot be larger than ${maximumMapSize} due to Map limitations.`));
else this._lruSize = options.lruSize;
if (options?.checkInterval) this._checkInterval = options.checkInterval;
if (options?.storeHashAlgorithm) this._storeHashAlgorithm = options.storeHashAlgorithm;
this._store = Array.from({ length: this._storeHashSize }, () => /* @__PURE__ */ new Map());
this.startIntervalCheck();
}
/**
* Gets the time-to-live
* @returns {number|string|undefined} - The time-to-live in miliseconds or a human-readable format. If undefined, it will not have a time-to-live.
*/
get ttl() {
return this._ttl;
}
/**
* Sets the time-to-live
* @param {number|string|undefined} value - The time-to-live in miliseconds or a human-readable format (example '1s' = 1 second, '1h' = 1 hour). If undefined, it will not have a time-to-live.
*/
set ttl(value) {
this.setTtl(value);
}
/**
* Gets the maximum time-to-live. When set, any TTL that exceeds this value is capped to maxTtl.
* Entries with no TTL will also be capped to maxTtl. Default is `undefined` (no maximum).
* @returns {number|string|undefined} - The maximum TTL in milliseconds, human-readable format, or undefined.
*/
get maxTtl() {
return this._maxTtl;
}
/**
* Sets the maximum time-to-live. When set, any TTL that exceeds this value is capped to maxTtl.
* Entries with no TTL will also be capped to maxTtl.
* @param {number|string|undefined} value - The maximum TTL in milliseconds or human-readable format (e.g. '1s', '1h'). If undefined, no maximum is enforced.
*/
set maxTtl(value) {
this.setMaxTtl(value);
}
/**
* Gets whether to use clone
* @returns {boolean} - If true, it will clone the value before returning it. If false, it will return the value directly. Default is true.
*/
get useClone() {
return this._useClone;
}
/**
* Sets whether to use clone
* @param {boolean} value - If true, it will clone the value before returning it. If false, it will return the value directly. Default is true.
*/
set useClone(value) {
this._useClone = value;
}
/**
* Gets the size of the LRU cache
* @returns {number} - The size of the LRU cache. If set to 0, it will not use LRU cache. Default is 0. If you are using LRU then the limit is based on Map() size 17mm.
*/
get lruSize() {
return this._lruSize;
}
/**
* Sets the size of the LRU cache
* @param {number} value - The size of the LRU cache. If set to 0, it will not use LRU cache. Default is 0. If you are using LRU then the limit is based on Map() size 17mm.
*/
set lruSize(value) {
if (value > 16777216) {
this.emit("error", /* @__PURE__ */ new Error(`LRU size cannot be larger than ${maximumMapSize} due to Map limitations.`));
return;
}
this._lruSize = value;
if (this._lruSize === 0) {
this._lru = new DoublyLinkedList();
return;
}
this.lruResize();
}
/**
* Gets the check interval
* @returns {number} - The interval to check for expired items. If set to 0, it will not check for expired items. Default is 0.
*/
get checkInterval() {
return this._checkInterval;
}
/**
* Sets the check interval
* @param {number} value - The interval to check for expired items. If set to 0, it will not check for expired items. Default is 0.
*/
set checkInterval(value) {
this._checkInterval = value;
}
/**
* Gets the size of the cache
* @returns {number} - The size of the cache
*/
get size() {
let size = 0;
for (const store of this._store) size += store.size;
return size;
}
/**
* Gets the statistics of the cache. Statistics track aggregate counters such as `hits`, `misses`,
* `gets`, `sets`, `deletes`, `clears`, `count`, `ksize`, and `vsize`. They are disabled by default;
* enable them via the `stats` option or by setting `cache.stats.enabled = true`.
* @returns {Stats} - The statistics for this CacheableMemory instance
*/
get stats() {
return this._stats;
}
/**
* Gets the number of hash stores
* @returns {number} - The number of hash stores
*/
get storeHashSize() {
return this._storeHashSize;
}
/**
* Sets the number of hash stores. This will recreate the store and all data will be cleared
* @param {number} value - The number of hash stores
*/
set storeHashSize(value) {
if (value === this._storeHashSize) return;
this._storeHashSize = value;
this._store = Array.from({ length: this._storeHashSize }, () => /* @__PURE__ */ new Map());
if (this._stats.enabled) this._stats.resetStoreValues();
}
/**
* Gets the store hash algorithm
* @returns {HashAlgorithm | StoreHashAlgorithmFunction} - The store hash algorithm
*/
get storeHashAlgorithm() {
return this._storeHashAlgorithm;
}
/**
* Sets the store hash algorithm. This will recreate the store and all data will be cleared
* @param {HashAlgorithm | HashAlgorithmFunction} value - The store hash algorithm
*/
set storeHashAlgorithm(value) {
this._storeHashAlgorithm = value;
}
/**
* Gets the keys
* @returns {IterableIterator<string>} - The keys
*/
get keys() {
const keys = [];
for (const store of this._store) for (const key of store.keys()) {
const item = store.get(key);
if (item && this.hasExpired(item)) {
this.recordExpiration(item);
store.delete(key);
this.lruRemove(key);
continue;
}
keys.push(key);
}
return keys.values();
}
/**
* Gets the items
* @returns {IterableIterator<CacheableStoreItem>} - The items
*/
get items() {
const items = [];
for (const store of this._store) for (const item of store.values()) {
if (this.hasExpired(item)) {
this.recordExpiration(item);
store.delete(item.key);
this.lruRemove(item.key);
continue;
}
items.push(item);
}
return items.values();
}
/**
* Gets the store
* @returns {Array<Map<string, CacheableStoreItem>>} - The store
*/
get store() {
return this._store;
}
/**
* Gets the value of the key
* @param {string} key - The key to get the value
* @returns {T | undefined} - The value of the key
*/
get(key) {
this.hookSync("BEFORE_GET", key);
const store = this.getStore(key);
const item = store.get(key);
if (!item) {
this.recordRead(false);
this.hookSync("AFTER_GET", {
key,
result: void 0
});
return;
}
if (item.expires && Date.now() > item.expires) {
this.recordExpiration(item);
store.delete(key);
this.lruRemove(key);
this.recordRead(false);
this.hookSync("AFTER_GET", {
key,
result: void 0
});
return;
}
this.lruMoveToFront(key);
let result;
if (!this._useClone) result = item.value;
else result = this.clone(item.value);
this.recordRead(true);
this.hookSync("AFTER_GET", {
key,
result
});
return result;
}
/**
* Gets the values of the keys
* @param {string[]} keys - The keys to get the values
* @returns {T[]} - The values of the keys
*/
getMany(keys) {
this.hookSync("BEFORE_GET_MANY", keys);
const result = [];
for (const key of keys) result.push(this.get(key));
this.hookSync("AFTER_GET_MANY", {
keys,
result
});
return result;
}
/**
* Gets the raw value of the key
* @param {string} key - The key to get the value
* @returns {CacheableStoreItem | undefined} - The raw value of the key
*/
getRaw(key) {
const store = this.getStore(key);
const item = store.get(key);
if (!item) {
this.recordRead(false);
return;
}
if (item.expires && Date.now() > item.expires) {
this.recordExpiration(item);
store.delete(key);
this.lruRemove(key);
this.recordRead(false);
return;
}
this.lruMoveToFront(key);
this.recordRead(true);
return item;
}
/**
* Gets the raw values of the keys
* @param {string[]} keys - The keys to get the values
* @returns {CacheableStoreItem[]} - The raw values of the keys
*/
getManyRaw(keys) {
const result = [];
for (const key of keys) result.push(this.getRaw(key));
return result;
}
/**
* Sets the value of the key
* @param {string} key - The key to set the value
* @param {any} value - The value to set
* @param {number|string|SetOptions} [ttl] - Time to Live - If you set a number it is miliseconds, if you set a string it is a human-readable.
* If you want to set expire directly you can do that by setting the expire property in the SetOptions.
* If you set undefined, it will use the default time-to-live. If both are undefined then it will not have a time-to-live.
* @returns {void}
*/
set(key, value, ttl) {
const hookItem = {
key,
value,
ttl
};
this.hookSync("BEFORE_SET", hookItem);
const store = this.getStore(hookItem.key);
let expires;
const effectiveTtl = hookItem.ttl;
if (effectiveTtl !== void 0 || this._ttl !== void 0) if (typeof effectiveTtl === "object") {
if (effectiveTtl.expire) expires = typeof effectiveTtl.expire === "number" ? effectiveTtl.expire : effectiveTtl.expire.getTime();
if (effectiveTtl.ttl) {
const finalTtl = shorthandToTime(effectiveTtl.ttl);
/* v8 ignore next -- @preserve */
if (finalTtl !== void 0) expires = finalTtl;
}
} else {
const finalTtl = shorthandToTime(effectiveTtl ?? this._ttl);
/* v8 ignore next -- @preserve */
if (finalTtl !== void 0) expires = finalTtl;
}
if (this._maxTtl !== void 0) {
const maxExpires = shorthandToTime(this._maxTtl);
if (expires === void 0) expires = maxExpires;
else if (expires > maxExpires) expires = maxExpires;
}
if (this._lruSize > 0) if (store.has(hookItem.key)) this.lruMoveToFront(hookItem.key);
else {
this.lruAddToFront(hookItem.key);
if (this._lru.size > this._lruSize) {
const oldestKey = this._lru.getOldest();
/* v8 ignore next -- @preserve */
if (oldestKey) {
this._lru.removeOldest();
this.delete(oldestKey);
}
}
}
if (this._stats.enabled) {
const existing = store.get(hookItem.key);
if (existing) this._stats.decreaseVSize(existing.value);
else {
this._stats.incrementKSize(hookItem.key);
this._stats.incrementCount();
}
this._stats.incrementVSize(hookItem.value);
this._stats.incrementSets();
}
const item = {
key: hookItem.key,
value: hookItem.value,
expires
};
store.set(hookItem.key, item);
this.hookSync("AFTER_SET", hookItem);
}
/**
* Sets the values of the keys
* @param {CacheableItem[]} items - The items to set
* @returns {void}
*/
setMany(items) {
this.hookSync("BEFORE_SET_MANY", items);
for (const item of items) this.set(item.key, item.value, item.ttl);
this.hookSync("AFTER_SET_MANY", items);
}
/**
* Checks if the key exists
* @param {string} key - The key to check
* @returns {boolean} - If true, the key exists. If false, the key does not exist.
*/
has(key) {
const item = this.get(key);
return Boolean(item);
}
/**
* @function hasMany
* @param {string[]} keys - The keys to check
* @returns {boolean[]} - If true, the key exists. If false, the key does not exist.
*/
hasMany(keys) {
const result = [];
for (const key of keys) {
const item = this.get(key);
result.push(Boolean(item));
}
return result;
}
/**
* Take will get the key and delete the entry from cache
* @param {string} key - The key to take
* @returns {T | undefined} - The value of the key
*/
take(key) {
const item = this.get(key);
if (!item) return;
this.delete(key);
return item;
}
/**
* TakeMany will get the keys and delete the entries from cache
* @param {string[]} keys - The keys to take
* @returns {T[]} - The values of the keys
*/
takeMany(keys) {
const result = [];
for (const key of keys) result.push(this.take(key));
return result;
}
/**
* Delete the key
* @param {string} key - The key to delete
* @returns {void}
*/
delete(key) {
this.hookSync("BEFORE_DELETE", key);
const store = this.getStore(key);
if (this._stats.enabled) {
const item = store.get(key);
if (item) {
this._stats.decreaseKSize(key);
this._stats.decreaseVSize(item.value);
this._stats.decreaseCount();
this._stats.incrementDeletes();
}
}
store.delete(key);
this.lruRemove(key);
this.hookSync("AFTER_DELETE", key);
}
/**
* Delete the keys
* @param {string[]} keys - The keys to delete
* @returns {void}
*/
deleteMany(keys) {
this.hookSync("BEFORE_DELETE_MANY", keys);
for (const key of keys) this.delete(key);
this.hookSync("AFTER_DELETE_MANY", keys);
}
/**
* Clear the cache
* @returns {void}
*/
clear() {
this.hookSync("BEFORE_CLEAR");
this._store = Array.from({ length: this._storeHashSize }, () => /* @__PURE__ */ new Map());
this._lru = new DoublyLinkedList();
if (this._stats.enabled) {
this._stats.resetStoreValues();
this._stats.incrementClears();
}
this.hookSync("AFTER_CLEAR");
}
/**
* Get the store based on the key (internal use)
* @param {string} key - The key to get the store
* @returns {CacheableHashStore} - The store
*/
getStore(key) {
const hash = this.getKeyStoreHash(key);
this._store[hash] ||= /* @__PURE__ */ new Map();
return this._store[hash];
}
/**
* Hash the key for which store to go to (internal use)
* @param {string} key - The key to hash
* Available algorithms are: SHA256, SHA1, MD5, and djb2Hash.
* @returns {number} - The hashed key as a number
*/
getKeyStoreHash(key) {
if (this._store.length === 1) return 0;
if (typeof this._storeHashAlgorithm === "function") return this._storeHashAlgorithm(key, this._storeHashSize);
return hashToNumberSync(key, {
min: 0,
max: this._storeHashSize - 1,
algorithm: this._storeHashAlgorithm
});
}
/**
* Clone the value. This is for internal use
* @param {any} value - The value to clone
* @returns {any} - The cloned value
*/
clone(value) {
if (this.isPrimitive(value)) return value;
return structuredClone(value);
}
/**
* Add to the front of the LRU cache. This is for internal use
* @param {string} key - The key to add to the front
* @returns {void}
*/
lruAddToFront(key) {
if (this._lruSize === 0) return;
this._lru.addToFront(key);
}
/**
* Move to the front of the LRU cache. This is for internal use
* @param {string} key - The key to move to the front
* @returns {void}
*/
lruMoveToFront(key) {
if (this._lruSize === 0) return;
this._lru.moveToFront(key);
}
/**
* Remove a key from the LRU cache. This is for internal use
* @param {string} key - The key to remove
* @returns {void}
*/
lruRemove(key) {
if (this._lruSize === 0) return;
this._lru.remove(key);
}
/**
* Resize the LRU cache. This is for internal use.
* @returns {void}
*/
lruResize() {
while (this._lru.size > this._lruSize) {
const oldestKey = this._lru.getOldest();
/* v8 ignore next -- @preserve */
if (oldestKey) {
this._lru.removeOldest();
this.delete(oldestKey);
}
}
}
/**
* Check for expiration. This is for internal use
* @returns {void}
*/
checkExpiration() {
for (const store of this._store) for (const item of store.values()) if (item.expires && Date.now() > item.expires) {
this.recordExpiration(item);
store.delete(item.key);
this.lruRemove(item.key);
}
}
/**
* Start the interval check. This is for internal use
* @returns {void}
*/
startIntervalCheck() {
if (this._checkInterval > 0) {
/* v8 ignore next -- @preserve */
if (this._interval)
/* v8 ignore next -- @preserve */
clearInterval(this._interval);
this._interval = setInterval(() => {
this.checkExpiration();
}, this._checkInterval).unref();
}
}
/**
* Stop the interval check. This is for internal use
* @returns {void}
*/
stopIntervalCheck() {
/* v8 ignore next -- @preserve */
if (this._interval) clearInterval(this._interval);
this._interval = 0;
this._checkInterval = 0;
}
/**
* Wrap the function for caching
* @param {Function} function_ - The function to wrap
* @param {Object} [options] - The options to wrap
* @returns {Function} - The wrapped function
*/
wrap(function_, options) {
return wrapSync(function_, {
ttl: options?.ttl ?? this._ttl,
keyPrefix: options?.keyPrefix,
createKey: options?.createKey,
cache: this
});
}
/**
* Gets the value of the key, or computes and stores it on a cache miss. This is the synchronous
* cache-aside helper: if the key is present its value is returned, otherwise `function_` is
* invoked, its result is stored, and that result is returned.
*
* The value is stored using `options.ttl`, falling back to the instance default `ttl`. Because
* the cache is synchronous there is no request coalescing — concurrent callers cannot stampede
* the setter the way they can with an async cache.
* @param {GetOrSetSyncKey} key - The key to get or set. Can also be a function that returns the key.
* @param {() => T} function_ - The function that computes the value on a cache miss.
* @param {GetOrSetFunctionOptions} [options] - Options such as `ttl`, `cacheErrors`, and `throwErrors`.
* @returns {T | undefined} - The cached or freshly computed value
*/
getOrSet(key, function_, options) {
return getOrSetSync$1(key, function_, {
cache: this,
ttl: options?.ttl ?? this._ttl,
cacheErrors: options?.cacheErrors,
throwErrors: options?.throwErrors
});
}
/**
* Records a single read against the statistics counters. Each read increments `gets` and either
* `hits` or `misses`. No-op when statistics are disabled. This is for internal use.
* @param {boolean} hit - Whether the read found a (non-expired) value
* @returns {void}
*/
recordRead(hit) {
if (!this._stats.enabled) return;
if (hit) this._stats.incrementHits();
else this._stats.incrementMisses();
this._stats.incrementGets();
}
/**
* Decrements the size statistics (`count`, `ksize`, and `vsize`) for an entry that is being removed
* because it expired. Expirations are not counted as `deletes` since they are not user-initiated.
* No-op when statistics are disabled. This is for internal use.
* @param {CacheableStoreItem} item - The expired item being removed from the store
* @returns {void}
*/
recordExpiration(item) {
if (!this._stats.enabled) return;
this._stats.decreaseKSize(item.key);
this._stats.decreaseVSize(item.value);
this._stats.decreaseCount();
}
isPrimitive(value) {
const result = false;
/* v8 ignore next -- @preserve */
if (value === null || value === void 0) return true;
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return true;
return result;
}
setTtl(ttl) {
if (typeof ttl === "string" || ttl === void 0) this._ttl = ttl;
else if (ttl > 0) this._ttl = ttl;
else this._ttl = void 0;
}
setMaxTtl(maxTtl) {
if (typeof maxTtl === "string" || maxTtl === void 0) this._maxTtl = maxTtl;
else if (maxTtl > 0) this._maxTtl = maxTtl;
else this._maxTtl = void 0;
}
hasExpired(item) {
if (item.expires && Date.now() > item.expires) return true;
return false;
}
};
//#endregion
export { CacheableMemory, CacheableMemoryHooks, HashAlgorithm, KeyvCacheableMemory, Stats, createKeyv, defaultStoreHashSize, getOrSetSync, hash, hashToNumber, maximumMapSize };

65
node_modules/@cacheable/memory/package.json generated vendored Normal file
View File

@@ -0,0 +1,65 @@
{
"name": "@cacheable/memory",
"version": "2.2.0",
"description": "High Performance In-Memory Cache for Node.js",
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.mts",
"exports": {
".": {
"import": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
},
"require": {
"types": "./dist/index.d.cts",
"default": "./dist/index.cjs"
}
}
},
"repository": {
"type": "git",
"url": "git+https://github.com/jaredwray/cacheable.git",
"directory": "packages/cacheable"
},
"author": "Jared Wray <me@jaredwray.com>",
"license": "MIT",
"private": false,
"devDependencies": {
"tsdown": "^0.22.0",
"typescript": "^5.9.3"
},
"dependencies": {
"@keyv/bigmap": "^1.3.1",
"hookified": "^1.15.1",
"keyv": "^5.6.0",
"@cacheable/utils": "^2.5.0"
},
"keywords": [
"cacheable",
"high performance",
"distributed caching",
"Keyv storage engine",
"keyv",
"memory caching",
"LRU cache",
"memory",
"in-memory",
"scalable cache",
"in-memory cache",
"lruSize",
"lru"
],
"files": [
"dist",
"LICENSE"
],
"scripts": {
"build": "rimraf ./dist && tsdown src/index.ts --format cjs,esm --dts --clean",
"lint": "biome check --write --error-on-warnings",
"test": "pnpm lint && vitest run --coverage",
"test:ci": "biome check --error-on-warnings && vitest run --coverage",
"clean": "rimraf ./dist ./coverage ./node_modules"
}
}

19
node_modules/@cacheable/utils/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,19 @@
MIT License & © Jared Wray
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

854
node_modules/@cacheable/utils/README.md generated vendored Normal file
View File

@@ -0,0 +1,854 @@
[<img align="center" src="https://cacheable.org/logo.svg" alt="Cacheable" />](https://github.com/jaredwray/cacheable)
> Cacheble Utils
[![codecov](https://codecov.io/gh/jaredwray/cacheable/branch/main/graph/badge.svg?token=lWZ9OBQ7GM)](https://codecov.io/gh/jaredwray/cacheable)
[![tests](https://github.com/jaredwray/cacheable/actions/workflows/tests.yml/badge.svg)](https://github.com/jaredwray/cacheable/actions/workflows/tests.yml)
[![npm](https://img.shields.io/npm/dm/@cacheable/utils.svg)](https://www.npmjs.com/package/@cacheable/utils)
[![npm](https://img.shields.io/npm/v/@cacheable/utils)](https://www.npmjs.com/package/@cacheable/utils)
[![license](https://img.shields.io/github/license/jaredwray/cacheable)](https://github.com/jaredwray/cacheable/blob/main/LICENSE)
`@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:
* Data Types for Caching Items
* Hash Functions for Key Generation
* Coalesce Async for Handling Multiple Promises
* Statistics for Tracking Cache Metrics
* Sleep / Delay for Testing and Timing
* Memoization for wraping or get / set options
* Time to Live (TTL) Helpers
* Tag-Based Cache Invalidation
# Table of Contents
* [Getting Started](#getting-started)
* [Cacheable Types](#cacheable-types)
* [Coalesce Async](#coalesce-async)
* [Hash Functions](#hash-functions)
* [Shorthand Time Helpers](#shorthand-time-helpers)
* [Sleep Helper](#sleep-helper)
* [Statistics](#statistics)
* [Time to Live (TTL) Helpers](#time-to-live-ttl-helpers)
* [Run if Function Helper](#run-if-function-helper)
* [Less Than Helper](#less-than-helper)
* [Is Object Helper](#is-object-helper)
* [Wrap / Memoization for Sync and Async Functions](#wrap--memoization-for-sync-and-async-functions)
* [Get Or Set Memoization Function](#get-or-set-memoization-function)
* [Cache Tags](#cache-tags)
* [How to Contribute](#how-to-contribute)
* [License and Copyright](#license-and-copyright)
# Getting Started
```bash
npm install @cacheable/utils --save
```
# Cacheable Types
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.
```typescript
/**
* CacheableItem
* @typedef {Object} CacheableItem
* @property {string} key - The key of the cacheable item
* @property {any} value - The value of the cacheable item
* @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
* 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
* undefined then it will not have a time-to-live.
*/
export type CacheableItem = {
key: string;
value: any;
ttl?: number | string;
};
/**
* CacheableStoreItem
* @typedef {Object} CacheableStoreItem
* @property {string} key - The key of the cacheable store item
* @property {any} value - The value of the cacheable store item
* @property {number} [expires] - The expiration time in milliseconds since epoch. If not set, the item does not expire.
*/
export type CacheableStoreItem = {
key: string;
value: any;
expires?: number;
};
```
# Coalesce Async
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.
```typescript
import { coalesceAsync } from '@cacheable/utils';
const fetchData = async (key: string) => {
// Simulate an asynchronous operation
return new Promise((resolve) => setTimeout(() => resolve(`Data for ${key}`), 1000));
};
const result = await Promise.all([
coalesceAsync('my-key', fetchData),
coalesceAsync('my-key', fetchData),
coalesceAsync('my-key', fetchData),
]);
console.log(result); // Data for my-key only executed once
```
# Hash Functions
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.
The hashing API provides both **async** (for cryptographic algorithms) and **sync** (for non-cryptographic algorithms) methods.
## Async Hashing (Cryptographic Algorithms)
Use `hash()` and `hashToNumber()` for cryptographic algorithms like SHA-256, SHA-384, and SHA-512:
```typescript
import { hash, hashToNumber, HashAlgorithm } from '@cacheable/utils';
// Hash using SHA-256 (default)
const key = await hash('my-cache-key');
console.log(key); // Unique hash for 'my-cache-key'
// Hash with specific algorithm
const sha512Hash = await hash('my-data', { algorithm: HashAlgorithm.SHA512 });
// Convert hash to number within range
const min = 0;
const max = 10;
const result = await hashToNumber({foo: 'bar'}, { min, max, algorithm: HashAlgorithm.SHA256 });
console.log(result); // A number between 0 and 10 based on the hash value
```
## Sync Hashing (Non-Cryptographic Algorithms)
Use `hashSync()` and `hashToNumberSync()` for faster, non-cryptographic algorithms like DJB2, FNV1, MURMER, and CRC32:
```typescript
import { hashSync, hashToNumberSync, HashAlgorithm } from '@cacheable/utils';
// Hash using DJB2 (default for sync)
const key = hashSync('my-cache-key');
console.log(key); // Unique hash for 'my-cache-key'
// Hash with specific algorithm
const fnv1Hash = hashSync('my-data', { algorithm: HashAlgorithm.FNV1 });
// Convert hash to number within range
const min = 0;
const max = 10;
const result = hashToNumberSync({foo: 'bar'}, { min, max, algorithm: HashAlgorithm.DJB2 });
console.log(result); // A number between 0 and 10 based on the hash value
```
## Available Hash Algorithms
**Cryptographic (Async):**
- `HashAlgorithm.SHA256` - SHA-256 (default for async methods)
- `HashAlgorithm.SHA384` - SHA-384
- `HashAlgorithm.SHA512` - SHA-512
**Non-Cryptographic (Sync):**
- `HashAlgorithm.DJB2` - DJB2 (default for sync methods)
- `HashAlgorithm.FNV1` - FNV-1
- `HashAlgorithm.MURMER` - Murmur hash
- `HashAlgorithm.CRC32` - CRC32
# Shorthand Time Helpers
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.
You can also use the `shorthandToMilliseconds` function:
```typescript
import { shorthandToMilliseconds } from '@cacheable/utils';
const milliseconds = shorthandToMilliseconds('1h');
console.log(milliseconds); // 3600000
```
You can also use the `shorthandToTime` function to get the current date plus the shorthand time:
```typescript
import { shorthandToTime } from '@cacheable/utils';
const currentDate = new Date();
const timeInMs = shorthandToTime('1h', currentDate);
console.log(timeInMs); // Current date + 1 hour in milliseconds since epoch
```
# Sleep Helper
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.
```typescript
import { sleep } from '@cacheable/utils';
await sleep(1000); // Pause for 1 second
console.log('Execution resumed after 1 second');
```
# Statistics
The `Stats` class provides a unified, event-driven way to track caching metrics such as hits, misses, hit rate, item counts, and approximate memory usage. It can be driven two ways:
* **Imperatively** — call `increment` / `decrement` (or the named helpers) directly from your code.
* **Event-driven** — `subscribe` it to an event emitter (such as `@cacheable/node-cache` or a Node `EventEmitter`) and let matching events update the counters automatically.
Statistics are **opt-in**: a new `Stats` instance is disabled by default and ignores every update until enabled, so there is zero tracking overhead unless you ask for it.
```typescript
import { Stats } from '@cacheable/utils';
const stats = new Stats({ enabled: true });
stats.incrementHits();
stats.incrementMisses();
stats.incrementGets();
console.log(stats.hits); // 1
console.log(stats.misses); // 1
console.log(stats.hitRate); // 0.5
```
## Available Statistics
Every counter is exposed as a read-only property:
| Property | Type | Description |
| --- | --- | --- |
| `hits` | `number` | Number of cache hits. |
| `misses` | `number` | Number of cache misses. |
| `gets` | `number` | Number of get operations. |
| `sets` | `number` | Number of set operations. |
| `deletes` | `number` | Number of delete operations. |
| `clears` | `number` | Number of clear operations. |
| `count` | `number` | Number of items currently tracked. |
| `ksize` | `number` | Approximate size of all keys, in bytes. |
| `vsize` | `number` | Approximate size of all values, in bytes. |
### Computed Properties
| Property | Type | Description |
| --- | --- | --- |
| `hitRate` | `number` | `hits / (hits + misses)`, or `0` when there have been no lookups. |
| `missRate` | `number` | `misses / (hits + misses)`, or `0` when there have been no lookups. |
### Metadata
| Property | Type | Description |
| --- | --- | --- |
| `enabled` | `boolean` | Whether tracking is currently on. |
| `lastUpdated` | `number \| undefined` | Timestamp (ms since epoch) of the last update while enabled. |
| `lastReset` | `number \| undefined` | Timestamp (ms since epoch) of the last `reset()` / `clear()`. |
## Enabling, Disabling, and Clearing
```typescript
const stats = new Stats(); // disabled by default
stats.enable(); // start tracking (or: stats.enabled = true)
stats.incrementHits();
console.log(stats.hits); // 1
stats.disable(); // stop tracking (or: stats.enabled = false)
stats.incrementHits();
console.log(stats.hits); // still 1
stats.clear(); // reset every counter back to 0 (alias of reset())
console.log(stats.hits); // 0
```
* `reset()` / `clear()` — set every counter back to `0` and record `lastReset`.
* `resetStoreValues()` — reset only `count`, `ksize`, and `vsize`, leaving the hit/miss history intact.
## Incrementing and Decrementing
Use the unified `increment` / `decrement` methods with any counter field, or the named helpers. All updates are ignored while disabled.
```typescript
const stats = new Stats({ enabled: true });
// Unified API — optional amount (defaults to 1)
stats.increment('hits');
stats.increment('sets', 5);
stats.decrement('count', 2);
// Named helpers
stats.incrementHits();
stats.incrementMisses();
stats.incrementGets();
stats.incrementSets();
stats.incrementDeletes();
stats.incrementClears();
stats.incrementCount();
stats.decreaseCount();
// Approximate key/value sizes
stats.incrementKSize('my-key'); // adds the byte size of the key
stats.incrementVSize({ a: 1 }); // adds the byte size of the value
stats.decreaseKSize('my-key');
stats.decreaseVSize({ a: 1 });
stats.setCount(10); // set the item count directly
```
`StatField` is the union of countable fields: `'hits' | 'misses' | 'gets' | 'sets' | 'deletes' | 'clears' | 'count'`.
## Snapshot
`toJSON()` (aliased as `snapshot()`) returns a plain object of every counter, the computed rates, and the timestamps — handy for logging or sending to a metrics system.
```typescript
const stats = new Stats({ enabled: true });
stats.incrementHits(3);
stats.incrementMisses();
console.log(stats.toJSON());
// {
// enabled: true,
// hits: 3, misses: 1, gets: 0, sets: 0, deletes: 0, clears: 0,
// vsize: 0, ksize: 0, count: 0,
// hitRate: 0.75, missRate: 0.25,
// lastUpdated: 1749513600000, lastReset: undefined
// }
```
## Event-Driven Tracking
Instead of calling the increment methods yourself, you can `subscribe` a `Stats` instance to an emitter and have events update the counters automatically. The emitter is duck-typed — anything with `.on()` (plus `.off()` or `.removeListener()` to detach) works, including `Hookified`-based classes and Node's `EventEmitter`.
An **event map** describes how each event name updates the stats. A map value can be:
* a single field — `"sets"`
* an array of fields — `["hits", "gets"]`
* a custom handler — `(stats, ...args) => void`
```typescript
import { Stats, nodeCacheStatsEventMap } from '@cacheable/utils';
import { NodeCache } from '@cacheable/node-cache';
const cache = new NodeCache();
const stats = new Stats({ enabled: true });
// nodeCacheStatsEventMap maps set -> sets, del -> deletes, flush -> clears,
// and flush_stats -> reset.
stats.subscribe(cache, nodeCacheStatsEventMap);
cache.set('key', 'value');
console.log(stats.sets); // 1
stats.unsubscribe(); // detach all listeners (or pass an emitter to detach just one)
```
You can also provide your own map for any emitter:
```typescript
import { EventEmitter } from 'node:events';
import { Stats } from '@cacheable/utils';
const emitter = new EventEmitter();
const stats = new Stats({ enabled: true });
stats.subscribe(emitter, {
'cache:hit': ['hits', 'gets'],
'cache:miss': ['misses', 'gets'],
evicted: (s) => s.incrementDeletes(),
});
emitter.emit('cache:hit', { key: 'a' });
console.log(stats.hitRate); // 1
```
You can subscribe to multiple emitters from a single `Stats` instance, and pass an emitter to `unsubscribe(emitter)` to detach just that one. Counting is gated by `enabled`, so you can subscribe first and toggle tracking on later — handlers do not run at all while disabled.
## Per-Key Tracking (Most and Least Used Keys)
To find your hottest and coldest keys, enable per-key tracking with `trackKeys`. Each recorded key keeps its own breakdown of `hits`, `misses`, `gets`, `sets`, and `deletes`, plus a computed total `count` and per-key `hitRate`.
```typescript
import { Stats } from '@cacheable/utils';
const stats = new Stats({ enabled: true, trackKeys: true });
stats.recordKey('user:1', 'hits');
stats.recordKey('user:1', 'gets', 5);
stats.recordKey('user:2', 'misses');
// 100 most used keys by total operations (descending)
console.log(stats.mostUsedKeys(100));
// [
// { key: 'user:1', count: 6, hits: 1, misses: 0, gets: 5, sets: 0, deletes: 0, hitRate: 1 },
// { key: 'user:2', count: 1, hits: 0, misses: 1, gets: 0, sets: 0, deletes: 0, hitRate: 0 }
// ]
// 100 least used keys by total operations (ascending)
console.log(stats.leastUsedKeys(100));
// Rank by a single counter instead of the total
console.log(stats.mostUsedKeys(100, 'hits'));
// Inspect one key, or read the (read-only) tracked-keys map directly
console.log(stats.keyStats('user:1'));
console.log(stats.trackedKeys.size);
stats.clearKeys(); // clear per-key stats only (reset() clears these too)
```
Both `mostUsedKeys` and `leastUsedKeys` default to 100 entries, and `trackedKeys` is included in `toJSON()` snapshots.
Per-key tracking is fed two ways, just like the aggregate counters:
* **Imperatively** — call `recordKey(key, field, amount?)` wherever you already increment stats.
* **Event-driven** — `nodeCacheStatsEventMap` automatically records keys from `set`/`del` events when `trackKeys` is on, and custom event-map handlers can call `recordKey` with whatever the payload carries.
Memory is proportional to the number of unique keys tracked, so `trackKeys` is off by default. You can also set `maxTrackedKeys` as a safety cap — when exceeded, the lowest-count keys are pruned. Note that pruning keeps `mostUsedKeys` approximately accurate but makes `leastUsedKeys` unreliable (the pruned keys *are* the least used), so leave it unset if you need exact least-used-key rankings.
> **Note:** a built-in map is provided only where a library's events map cleanly to stats. `nodeCacheStatsEventMap` is included because `@cacheable/node-cache` emits each lifecycle event exactly once. Libraries that emit per-store probes or omit events on a miss (such as `cacheable` and `cache-manager`) should be wired with a custom map or driven imperatively so the counts stay accurate.
# Time to Live (TTL) Helpers
The `@cacheable/utils` package provides helpers for managing time-to-live (TTL) values for cached items.
You can use the `calculateTtlFromExpiration` function to calculate the TTL based on an expiration date:
```typescript
import { calculateTtlFromExpiration } from '@cacheable/utils';
const expirationDate = new Date(Date.now() + 1000 * 60 * 5); // 5 minutes from now
const ttl = calculateTtlFromExpiration(Date.now(), expirationDate);
console.log(ttl); // 300000
```
You can also use `getTtlFromExpires` to get the TTL from an expiration date:
```typescript
import { getTtlFromExpires } from '@cacheable/utils';
const expirationDate = new Date(Date.now() + 1000 * 60 * 5); // 5 minutes from now
const ttl = getTtlFromExpires(expirationDate);
console.log(ttl); // 300000
```
You can use `getCascadingTtl` to get the TTL for cascading cache operations:
```typescript
import { getCascadingTtl } from '@cacheable/utils';
const cacheableTtl = 1000 * 60 * 5; // 5 minutes
const primaryTtl = 1000 * 60 * 2; // 2 minutes
const secondaryTtl = 1000 * 60; // 1 minute
const ttl = getCascadingTtl(cacheableTtl, primaryTtl, secondaryTtl);
```
# Run if Function Helper
The `runIfFn` utility function provides a convenient way to conditionally execute functions or return values based on whether the input is a function or not. This pattern is commonly used in UI libraries and configuration systems where values can be either static or computed.
```typescript
import { runIfFn } from '@cacheable/utils';
// Static value - returns the value as-is
const staticValue = runIfFn('hello world');
console.log(staticValue); // 'hello world'
// Function with no arguments - executes the function
const dynamicValue = runIfFn(() => new Date().toISOString());
console.log(dynamicValue); // Current timestamp
// Function with arguments - executes with provided arguments
const sum = runIfFn((a: number, b: number) => a + b, 5, 10);
console.log(sum); // 15
// Complex example with conditional logic
const getConfig = (isDevelopment: boolean) => ({
apiUrl: isDevelopment ? 'http://localhost:3000' : 'https://api.example.com',
timeout: isDevelopment ? 5000 : 30000
});
const config = runIfFn(getConfig, true);
console.log(config); // { apiUrl: 'http://localhost:3000', timeout: 5000 }
```
# Less Than Helper
The `lessThan` utility function provides a safe way to compare two values and determine if the first value is less than the second. It only performs the comparison if both values are valid numbers, returning `false` for any non-number inputs.
```typescript
import { lessThan } from '@cacheable/utils';
// Basic number comparisons
console.log(lessThan(1, 2)); // true
console.log(lessThan(2, 1)); // false
console.log(lessThan(1, 1)); // false
// Works with negative numbers
console.log(lessThan(-1, 0)); // true
console.log(lessThan(-2, -1)); // true
// Works with decimal numbers
console.log(lessThan(1.5, 2.5)); // true
console.log(lessThan(2.7, 2.7)); // false
// Safe handling of non-number values
console.log(lessThan("1", 2)); // false
console.log(lessThan(1, "2")); // false
console.log(lessThan(null, 1)); // false
console.log(lessThan(undefined, 1)); // false
console.log(lessThan(NaN, 1)); // false
// Useful in filtering and sorting operations
const numbers = [5, 2, 8, 1, 9];
const lessThanFive = numbers.filter(n => lessThan(n, 5));
console.log(lessThanFive); // [2, 1]
// Safe comparison in conditional logic
function processValue(a?: number, b?: number) {
if (lessThan(a, b)) {
return `${a} is less than ${b}`;
}
return 'Invalid comparison or a >= b';
}
```
This utility is particularly useful when dealing with potentially undefined or invalid numeric values, ensuring type safety in comparison operations.
# Is Object Helper
The `isObject` utility function provides a type-safe way to determine if a value is a plain object. It returns `true` for objects but `false` for arrays, `null`, functions, and primitive types. This function also serves as a TypeScript type guard.
```typescript
import { isObject } from '@cacheable/utils';
// Basic object detection
console.log(isObject({})); // true
console.log(isObject({ name: 'John', age: 30 })); // true
console.log(isObject(Object.create(null))); // true
// Arrays are not considered objects
console.log(isObject([])); // false
console.log(isObject([1, 2, 3])); // false
// null is not considered an object (despite typeof null === 'object')
console.log(isObject(null)); // false
// Primitive types return false
console.log(isObject('string')); // false
console.log(isObject(123)); // false
console.log(isObject(true)); // false
console.log(isObject(undefined)); // false
// Functions return false
console.log(isObject(() => {})); // false
console.log(isObject(Date)); // false
// Built-in object types return true
console.log(isObject(new Date())); // true
console.log(isObject(/regex/)); // true
console.log(isObject(new Error('test'))); // true
console.log(isObject(new Map())); // true
// TypeScript type guard usage
function processValue(value: unknown) {
if (isObject<{ name: string; age: number }>(value)) {
// TypeScript now knows value is an object with name and age properties
console.log(`Name: ${value.name}, Age: ${value.age}`);
}
}
// Useful for configuration validation
function validateConfig(config: unknown) {
if (!isObject(config)) {
throw new Error('Configuration must be an object');
}
// Safe to access object properties
return config;
}
// Filtering arrays for objects only
const mixedArray = [1, 'string', {}, [], null, { valid: true }];
const objectsOnly = mixedArray.filter(isObject);
console.log(objectsOnly); // [{}', { valid: true }]
```
This utility is particularly useful for:
- **Type validation** - Ensuring values are objects before accessing properties
- **TypeScript type guarding** - Narrowing types in conditional blocks
- **Configuration parsing** - Validating that configuration values are objects
- **Data filtering** - Separating objects from other data types
# Wrap / Memoization for Sync and Async Functions
The `@cacheable/utils` package provides two main functions: `wrap` and `wrapSync`. These functions are used to memoize asynchronous and synchronous functions, respectively.
```javascript
import { Cacheable } from 'cacheable';
const asyncFunction = async (value: number) => {
return Math.random() * value;
};
const cache = new Cacheable();
const options = {
ttl: '1h', // 1 hour
keyPrefix: 'p1', // key prefix. This is used if you have multiple functions and need to set a unique prefix.
cache,
}
const wrappedFunction = wrap(asyncFunction, options);
console.log(await wrappedFunction(2)); // 4
console.log(await wrappedFunction(2)); // 4 from cache
```
With `wrap` we have also included stampede protection so that a `Promise` based call will only be called once if multiple requests of the same are executed at the same time. Here is an example of how to test for stampede protection:
```javascript
import { Cacheable } from 'cacheable';
const asyncFunction = async (value: number) => {
return value;
};
const cache = new Cacheable();
const options = {
ttl: '1h', // 1 hour
keyPrefix: 'p1', // key prefix. This is used if you have multiple functions and need to set a unique prefix.
cache,
}
const wrappedFunction = wrap(asyncFunction, options);
const promises = [];
for (let i = 0; i < 10; i++) {
promises.push(wrappedFunction(i));
}
const results = await Promise.all(promises); // all results should be the same
console.log(results); // [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
```
In this example we are wrapping an `async` function in a cache with a `ttl` of `1 hour`. This will cache the result of the function for `1 hour` and then expire the value. You can also wrap a `sync` function in a cache:
```javascript
import { CacheableMemory } from 'cacheable';
const syncFunction = (value: number) => {
return value * 2;
};
const cache = new CacheableMemory();
const wrappedFunction = wrap(syncFunction, { ttl: '1h', key: 'syncFunction', cache });
console.log(wrappedFunction(2)); // 4
console.log(wrappedFunction(2)); // 4 from cache
```
In this example we are wrapping a `sync` function in a cache with a `ttl` of `1 hour`. This will cache the result of the function for `1 hour` and then expire the value. You can also set the `key` property in the `wrap()` options to set a custom key for the cache.
When an error occurs in the function it will not cache the value and will return the error. This is useful if you want to cache the results of a function but not cache the error. If you want it to cache the error you can set the `cacheError` property to `true` in the `wrap()` options. This is disabled by default.
```javascript
import { CacheableMemory } from 'cacheable';
const syncFunction = (value: number) => {
throw new Error('error');
};
const cache = new CacheableMemory();
const wrappedFunction = wrap(syncFunction, { ttl: '1h', key: 'syncFunction', cacheError: true, cache });
console.log(wrappedFunction()); // error
console.log(wrappedFunction()); // error from cache
```
If you would like to generate your own key for the wrapped function you can set the `createKey` property in the `wrap()` options. This is useful if you want to generate a key based on the arguments of the function or any other criteria.
```javascript
const cache = new Cacheable();
const options: WrapOptions = {
cache,
keyPrefix: 'test',
createKey: (function_, arguments_, options: WrapOptions) => `customKey:${options?.keyPrefix}:${arguments_[0]}`,
};
const wrapped = wrap((argument: string) => `Result for ${argument}`, options);
const result1 = await wrapped('arg1');
const result2 = await wrapped('arg1'); // Should hit the cache
console.log(result1); // Result for arg1
console.log(result2); // Result for arg1 (from cache)
```
We will pass in the `function` that is being wrapped, the `arguments` passed to the function, and the `options` used to wrap the function. You can then use these to generate a custom key for the cache.
# Get Or Set Memoization Function
The `getOrSet` method provides a convenient way to implement the cache-aside pattern. It attempts to retrieve a value from cache, and if not found, calls the provided function to compute the value and store it in cache before returning it. Here are the options:
```typescript
export type GetOrSetFunctionOptions = {
ttl?: number | string;
cacheErrors?: boolean;
throwErrors?: boolean;
nonBlocking?: boolean;
};
```
The `nonBlocking` option allows you to override the instance-level `nonBlocking` setting for the `get` call within `getOrSet`. When set to `false`, the `get` will block and wait for a response from the secondary store before deciding whether to call the provided function. When set to `true`, the primary store returns immediately and syncs from secondary in the background.
Here is an example of how to use the `getOrSet` method:
```javascript
import { Cacheable } from 'cacheable';
const cache = new Cacheable();
// Use getOrSet to fetch user data
const function_ = async () => Math.random() * 100;
const value = await getOrSet('randomValue', function_, { ttl: '1h', cache });
console.log(value); // e.g. 42.123456789
```
You can also use a function to compute the key for the function:
```javascript
import { Cacheable, GetOrSetOptions } from 'cacheable';
const cache = new Cacheable();
// Function to generate a key based on options
const generateKey = (options?: GetOrSetOptions) => {
return `custom_key_:${options?.cacheId || 'default'}`;
};
const function_ = async () => Math.random() * 100;
const value = await getOrSet(generateKey(), function_, { ttl: '1h', cache });
```
# Cache Tags
The `CacheTags` service provides tag-based invalidation on top of any [Keyv](https://github.com/jaredwray/keyv) store. It is store-agnostic and does not require any adapter changes.
The service uses a lazy invalidation model. Instead of scanning and deleting keys, `invalidateTag` increments a per-tag version counter. Each cached key stores a snapshot of its tag versions at the time it was written, and `isKeyFresh` compares that snapshot to the current versions. If any tag version has been incremented since the snapshot was taken, the key is considered stale. Stale entries are not deleted explicitly and are expected to fall out of the cache via their TTL.
This approach keeps invalidation constant-time regardless of how many keys reference a tag. The trade-off is one additional `isKeyFresh` read per cache lookup.
```typescript
import { Keyv } from 'keyv';
import { CacheTags } from '@cacheable/utils';
const store = new Keyv();
const cacheTags = new CacheTags({ store, namespace: 'app' });
await cacheTags.setKeyTags('user:42', ['users', 'org:7'], { ttl: 3600000 });
console.log(await cacheTags.isKeyFresh('user:42')); // true
await cacheTags.invalidateTag('users');
console.log(await cacheTags.isKeyFresh('user:42')); // false
```
The recommended pattern is to call `isKeyFresh` before trusting a value returned from your cache, and to refresh the tag snapshot whenever you write a new value:
```typescript
import { Cacheable } from 'cacheable';
import { Keyv } from 'keyv';
import { CacheTags } from '@cacheable/utils';
const cache = new Cacheable();
const cacheTags = new CacheTags({ store: new Keyv() });
const getUser = async (id: string) => {
const key = `user:${id}`;
if (await cacheTags.isKeyFresh(key)) {
const cached = await cache.get(key);
if (cached !== undefined) {
return cached;
}
}
const fresh = await loadUser(id);
await cache.set(key, fresh, '1h');
await cacheTags.setKeyTags(key, ['users', `org:${fresh.orgId}`], { ttl: 3600000 });
return fresh;
};
```
You can invalidate one or many tags at a time. Both methods return the names of the tags that were bumped:
```typescript
const bumped = await cacheTags.invalidateTags(['users', 'org:7']);
console.log(bumped); // ['users', 'org:7']
```
When integrating with a cache where most keys are untagged, use `isKeyStale` instead of `isKeyFresh`. It only reports `true` when a snapshot exists for the key and one of its tags has been invalidated, so keys that were never tagged are not treated as stale:
```typescript
console.log(await cacheTags.isKeyStale('never-tagged')); // false
await cacheTags.setKeyTags('user:42', ['users']);
console.log(await cacheTags.isKeyStale('user:42')); // false
await cacheTags.invalidateTag('users');
console.log(await cacheTags.isKeyStale('user:42')); // true
```
The `getStaleKeys` method checks many keys at once using two batched store reads regardless of how many keys are passed — one for the snapshots and one for the union of their tag versions:
```typescript
await cacheTags.setKeyTags('a', ['x']);
await cacheTags.setKeyTags('b', ['y']);
await cacheTags.invalidateTag('x');
console.log(await cacheTags.getStaleKeys(['a', 'b', 'untagged'])); // ['a']
```
The `getTags` method returns the tags currently associated with a key, or `undefined` if the key has no snapshot:
```typescript
await cacheTags.setKeyTags('user:42', ['users', 'org:7']);
console.log(await cacheTags.getTags('user:42')); // ['users', 'org:7']
console.log(await cacheTags.getTags('missing')); // undefined
```
The `removeKey` and `removeKeys` methods delete tag snapshots when the cached values themselves are deleted. `removeKeys` performs a single batched delete:
```typescript
await cacheTags.removeKeys(['user:1', 'user:2']);
```
The service can be disabled via the `enabled` option or property so integrations pay no extra store reads for untagged workloads. While disabled, every method is a no-op: read methods return their neutral value (`isKeyFresh` returns `true`, `isKeyStale` returns `false`, `getStaleKeys` returns `[]`, and so on) and writes are skipped. The service never enables itself — you have to turn it on explicitly, which keeps behavior consistent across distributed instances sharing a store:
```typescript
const cacheTags = new CacheTags({ store, enabled: false });
console.log(await cacheTags.isKeyStale('anything')); // false, no store read
await cacheTags.setKeyTags('user:42', ['users']); // no-op while disabled
cacheTags.enabled = true; // turn it on to use tags
```
`setKeyTags`, `removeKey`, and `removeKeys` accept a `nonBlocking` option to fire-and-forget the store write. Failures from non-blocking operations are reported to the `onError` constructor option since they cannot be thrown to the caller:
```typescript
const cacheTags = new CacheTags({ store, onError: (error) => console.error(error) });
await cacheTags.setKeyTags('user:42', ['users'], { ttl: 3600000, nonBlocking: true });
```
The `getKeysByTag` method returns the keys currently referencing a given tag. It iterates the Keyv namespace and is therefore an `O(N)` operation. It is intended for debugging and tests rather than hot paths.
```typescript
await cacheTags.setKeyTags('user:1', ['users']);
await cacheTags.setKeyTags('user:2', ['users']);
const keys = await cacheTags.getKeysByTag('users');
console.log(keys); // ['user:1', 'user:2']
```
The service stores its metadata under a reserved prefix so that it cannot collide with user keys:
```
--cacheable--tags--:<namespace>:tag:<tagName> → integer version counter
--cacheable--tags--:<namespace>:key:<keyName> → { tags: { [tag]: versionAtSetTime } }
```
Tag version counters are stored without a TTL because they must outlive any key that references them. Key entries respect the `ttl` passed to `setKeyTags`, which should be set to match the TTL of the cached value it tracks.
The namespace defaults to `default` and can be set via the constructor. Two services configured with different namespaces can share the same store without seeing each other's tags or keys.
The read-version then write-snapshot sequence in `setKeyTags` is not atomic across processes. A concurrent `invalidateTag` that runs between the read and the write can leave a freshly written key referencing a stale version. An atomic Redis fast path using `MULTI` or Lua is a planned future enhancement.
# How to Contribute
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`.
# License and Copyright
[MIT © Jared Wray](./LICENSE)

1380
node_modules/@cacheable/utils/dist/index.cjs generated vendored Normal file

File diff suppressed because it is too large Load Diff

903
node_modules/@cacheable/utils/dist/index.d.cts generated vendored Normal file
View File

@@ -0,0 +1,903 @@
import { Keyv } from "keyv";
//#region src/shorthand-time.d.ts
/**
* Converts a shorthand time string or number into milliseconds.
* The shorthand can be a string like '1s', '2m', '3h', '4d', or a number representing milliseconds.
* If the input is undefined, it returns undefined.
* If the input is a string that does not match the expected format, it throws an error.
* @param shorthand - A shorthand time string or number representing milliseconds.
* @returns The equivalent time in milliseconds or undefined.
*/
declare const shorthandToMilliseconds: (shorthand?: string | number) => number | undefined;
/**
* Converts a shorthand time string or number into a timestamp.
* If the shorthand is undefined, it returns the current date's timestamp.
* If the shorthand is a valid time format, it adds that duration to the current date's timestamp.
* @param shorthand - A shorthand time string or number representing milliseconds.
* @param fromDate - An optional Date object to calculate from. Defaults to the current date if not provided.
* @returns The timestamp in milliseconds since epoch.
*/
declare const shorthandToTime: (shorthand?: string | number, fromDate?: Date) => number;
//#endregion
//#region src/cache-tags.d.ts
/**
* Options for constructing a {@link CacheTags}.
* @typedef {Object} CacheTagsOptions
* @property {Keyv} store - The Keyv store used to persist tag versions and key snapshots.
* @property {string} [namespace] - An optional namespace that isolates this service's tags
* and keys from others sharing the same store. Defaults to `"default"`.
* @property {boolean} [enabled] - Whether the service is enabled. While disabled, every method
* is a no-op: read methods return their neutral value ({@link CacheTags.isKeyFresh} returns
* `true`, {@link CacheTags.isKeyStale} returns `false`, etc.) and writes are skipped. The
* service must be explicitly enabled to use tags. Defaults to `true`.
* @property {(error: unknown) => void} [onError] - Invoked with errors from non-blocking
* (fire-and-forget) operations, which cannot be thrown to the caller. Defaults to ignoring them.
*/
type CacheTagsOptions = {
store: Keyv;
namespace?: string;
enabled?: boolean;
onError?: (error: unknown) => void;
};
/**
* Options for {@link CacheTags.setKeyTags}.
* @typedef {Object} SetKeyTagsOptions
* @property {number} [ttl] - Time-to-live in milliseconds for the key's tag snapshot. Should
* match the TTL of the cached value it tracks so the snapshot expires alongside it. If omitted,
* the snapshot does not expire.
* @property {boolean} [nonBlocking] - When `true`, the snapshot write is fire-and-forget:
* the call resolves immediately and failures are reported via the `onError` option.
*/
type SetKeyTagsOptions = {
ttl?: number;
nonBlocking?: boolean;
};
/**
* Options for {@link CacheTags.removeKey} and {@link CacheTags.removeKeys}.
* @typedef {Object} RemoveKeysOptions
* @property {boolean} [nonBlocking] - When `true`, the removal is fire-and-forget:
* the call resolves immediately and failures are reported via the `onError` option.
*/
type RemoveKeysOptions = {
nonBlocking?: boolean;
};
/**
* The metadata stored for a tagged key. It records the version of each tag at the moment the key
* was written, allowing {@link CacheTags.isKeyFresh} to detect later invalidations.
* @typedef {Object} KeyTagEntry
* @property {Record<string, number>} tags - A snapshot mapping each tag name to its version at set time.
*/
type KeyTagEntry = {
tags: Record<string, number>;
};
/**
* Provides tag-based cache invalidation on top of any {@link Keyv} store. It is store-agnostic and
* requires no adapter changes.
*
* The service uses a lazy invalidation model rather than scanning and deleting keys. Each tag has a
* monotonically increasing version counter; {@link CacheTags.invalidateTag} simply increments
* it. When a key is tagged via {@link CacheTags.setKeyTags}, a snapshot of its tags' current
* versions is stored alongside it. {@link CacheTags.isKeyFresh} compares that snapshot against
* the live versions — if any tag has been incremented since, the key is considered stale. Stale
* entries are not deleted explicitly; they are expected to fall out of the cache via their TTL.
*
* This keeps invalidation constant-time regardless of how many keys reference a tag, at the cost of
* one additional `isKeyFresh` read per cache lookup.
*
* The service can be disabled via the `enabled` option or property so integrations pay no cost for
* untagged workloads: while disabled, every method is a no-op — reads return their neutral value
* and writes are skipped. The service must be explicitly enabled to use tags; it never enables
* itself, which keeps behavior consistent across distributed instances sharing a store.
*
* All metadata is written under a reserved prefix so it cannot collide with user keys:
* - `--cacheable--tags--:<namespace>:tag:<tag>` → integer version counter (stored without TTL).
* - `--cacheable--tags--:<namespace>:key:<key>` → the {@link KeyTagEntry} snapshot.
*
* Note: the read-version-then-write-snapshot sequence in `setKeyTags` is not atomic across
* processes. A concurrent `invalidateTag` running between the read and the write can leave a freshly
* written key referencing a stale version.
*
* @example
* ```typescript
* const cacheTags = new CacheTags({ store: new Keyv(), namespace: 'app' });
* await cacheTags.setKeyTags('user:42', ['users', 'org:7'], { ttl: 3600000 });
* await cacheTags.isKeyFresh('user:42'); // true
* await cacheTags.invalidateTag('users');
* await cacheTags.isKeyFresh('user:42'); // false
* ```
*/
declare class CacheTags {
private readonly _store;
private readonly _namespace;
private _enabled;
private readonly _onError?;
/**
* Creates a new tag service.
* @param {CacheTagsOptions} options - The store, optional namespace, enabled state, and
* non-blocking error handler to use.
*/
constructor(options: CacheTagsOptions);
/**
* The Keyv store backing this service.
* @returns {Keyv} The store provided to the constructor.
*/
get store(): Keyv;
/**
* The namespace isolating this service's tags and keys within the store.
* @returns {string} The configured namespace, or `"default"` if none was provided.
*/
get namespace(): string;
/**
* Whether the service is enabled. While disabled, every method is a no-op — read methods
* return their neutral value and writes are skipped — so integrations pay no extra store
* reads for untagged workloads. The service must be explicitly enabled to use tags; it never
* enables itself.
* @returns {boolean} Whether the service is enabled.
*/
get enabled(): boolean;
/**
* Sets whether the service is enabled.
* @param {boolean} enabled Whether the service is enabled.
*/
set enabled(enabled: boolean);
/**
* Builds the reserved store key under which a tag's version counter is stored.
* @param tag - The tag name.
* @returns {string} The namespaced store key for the tag's version.
*/
private tagKey;
/**
* Builds the reserved store key under which a cache key's tag snapshot is stored.
* @param key - The cache key being tagged.
* @returns {string} The namespaced store key for the key's snapshot.
*/
private keyEntryKey;
/**
* Builds the common prefix shared by every key-snapshot entry in this namespace. Used to filter
* key entries when iterating the store.
* @returns {string} The namespaced key-entry prefix.
*/
private keyPrefix;
/**
* Reads the current version of a single tag.
* @param tag - The tag name.
* @returns {Promise<number>} The tag's version, or `0` if it has never been invalidated.
*/
private getTagVersion;
/**
* Reads the current versions of multiple tags in a single batched store read.
* @param tags - The tag names to look up.
* @returns {Promise<number[]>} The versions in the same order as `tags`; entries that have never
* been invalidated resolve to `0`. Returns an empty array when `tags` is empty.
*/
private getTagVersions;
/**
* Reports a fire-and-forget failure to the `onError` handler, if one was provided.
* @param error - The error raised by the non-blocking operation.
*/
private handleNonBlockingError;
/**
* Reads the version snapshot of each tag and writes the key's tag snapshot to the store.
* @param key - The cache key to tag.
* @param tags - The tags to associate with the key.
* @param ttl - Time-to-live in milliseconds for the snapshot.
* @returns {Promise<void>} Resolves once the snapshot has been written.
*/
private writeKeyTags;
/**
* Associates a cache key with a set of tags by recording a snapshot of each tag's current
* version. Call this whenever you write a fresh value to the cache. Duplicate tags are ignored.
* No-op while the service is disabled.
* @param key - The cache key to tag.
* @param tags - The tags to associate with the key.
* @param {SetKeyTagsOptions} [options] - Optional settings, such as a `ttl` for the snapshot or
* `nonBlocking` to fire-and-forget the write.
* @returns {Promise<void>} Resolves once the snapshot has been written, or immediately when
* `nonBlocking` is set.
*/
setKeyTags(key: string, tags: string[], options?: SetKeyTagsOptions): Promise<void>;
/**
* Removes a key's tag snapshot. After this, {@link CacheTags.isKeyFresh} returns `false`
* for the key. Use when the cached value itself is deleted. No-op while the service is
* disabled.
* @param key - The cache key whose snapshot should be removed.
* @param {RemoveKeysOptions} [options] - Optional settings, such as `nonBlocking` to
* fire-and-forget the removal.
* @returns {Promise<void>} Resolves once the snapshot has been deleted, or immediately when
* `nonBlocking` is set.
*/
removeKey(key: string, options?: RemoveKeysOptions): Promise<void>;
/**
* Removes multiple keys' tag snapshots in a single batched store delete. After this,
* {@link CacheTags.isKeyFresh} returns `false` for each key. An empty list is a no-op, as is
* the entire call while the service is disabled.
* @param keys - The cache keys whose snapshots should be removed.
* @param {RemoveKeysOptions} [options] - Optional settings, such as `nonBlocking` to
* fire-and-forget the removal.
* @returns {Promise<void>} Resolves once the snapshots have been deleted, or immediately when
* `nonBlocking` is set.
*/
removeKeys(keys: string[], options?: RemoveKeysOptions): Promise<void>;
/**
* Determines whether a key's cached value can still be trusted. A key is fresh only when a
* snapshot exists for it and every tag in that snapshot still has the version it had at set time.
* A key with no tags is trivially fresh. Call this before returning a value from your cache.
* Always returns `true` while the service is disabled.
* @param key - The cache key to check.
* @returns {Promise<boolean>} `true` if the key is still fresh; `false` if it is unknown or any of
* its tags has been invalidated since the snapshot was taken.
*/
isKeyFresh(key: string): Promise<boolean>;
/**
* Determines whether a key's cached value is known to be stale due to tag invalidation. This is
* the complement of {@link CacheTags.isKeyFresh} for tagged keys, but treats keys without a
* snapshot as not stale — making it safe to call for every cache lookup, including keys that were
* never tagged. Always returns `false` while the service is disabled.
* @param key - The cache key to check.
* @returns {Promise<boolean>} `true` only when a snapshot exists for the key and at least one of
* its tags has been invalidated since the snapshot was taken; `false` otherwise (including when
* the key has no snapshot).
*/
isKeyStale(key: string): Promise<boolean>;
/**
* Determines which of the given keys are known to be stale due to tag invalidation, using two
* batched store reads regardless of how many keys are checked: one for the snapshots and one for
* the union of their tag versions. Keys without a snapshot are not considered stale. Returns an
* empty array while the service is disabled.
* @param keys - The cache keys to check.
* @returns {Promise<string[]>} The subset of `keys` whose snapshot references at least one tag
* that has been invalidated since the snapshot was taken.
*/
getStaleKeys(keys: string[]): Promise<string[]>;
/**
* Returns the tags currently associated with a key. Returns `undefined` while the service is
* disabled.
* @param key - The cache key to look up.
* @returns {Promise<string[] | undefined>} The tag names from the key's snapshot, or `undefined`
* if the key has no snapshot.
*/
getTags(key: string): Promise<string[] | undefined>;
/**
* Returns all cache keys whose snapshot references the given tag. This scans every key entry in
* the namespace via the Keyv iterator, making it an `O(N)` operation intended for debugging and
* tests rather than hot paths. Returns an empty array if the underlying store exposes no iterator
* or while the service is disabled.
* @param tag - The tag to search for.
* @returns {Promise<string[]>} The cache keys (with the reserved prefix stripped) referencing the tag.
*/
getKeysByTag(tag: string): Promise<string[]>;
/**
* Invalidates a single tag by incrementing its version counter. Every key whose snapshot
* references this tag becomes stale immediately. Runs in constant time regardless of how many
* keys reference the tag. No-op while the service is disabled.
* @param tag - The tag to invalidate.
* @returns {Promise<string[]>} A single-element array containing the invalidated tag, or an
* empty array while the service is disabled.
*/
invalidateTag(tag: string): Promise<string[]>;
/**
* Invalidates multiple tags by incrementing each of their version counters in a single batched
* store write. Duplicate tags are bumped once. An empty list is a no-op, as is the entire call
* while the service is disabled.
* @param tags - The tags to invalidate.
* @returns {Promise<string[]>} The `tags` argument as provided (including any duplicates), or
* an empty array while the service is disabled.
*/
invalidateTags(tags: string[]): Promise<string[]>;
}
//#endregion
//#region src/cacheable-item-types.d.ts
/**
* CacheableItem
* @typedef {Object} CacheableItem
* @property {string} key - The key of the cacheable item
* @property {any} value - The value of the cacheable item
* @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
* 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
* undefined then it will not have a time-to-live.
*/
type CacheableItem = {
key: string;
value: any;
ttl?: number | string;
};
/**
* CacheableStoreItem
* @typedef {Object} CacheableStoreItem
* @property {string} key - The key of the cacheable store item
* @property {any} value - The value of the cacheable store item
* @property {number} [expires] - The expiration time in milliseconds since epoch. If not set, the item does not expire.
*/
type CacheableStoreItem = {
key: string;
value: any;
expires?: number;
};
//#endregion
//#region src/coalesce-async.d.ts
/**
* Enqueue a promise for the group identified by `key`.
*
* All requests received for the same key while a request for that key
* is already being executed will wait. Once the running request settles
* then all the waiting requests in the group will settle, too.
* This minimizes how many times the function itself runs at the same time.
* This function resolves or rejects according to the given function argument.
*
* @url https://github.com/douglascayers/promise-coalesce
*/
declare function coalesceAsync<T>(
/**
* Any identifier to group requests together.
*/
key: string,
/**
* The function to run.
*/
fnc: () => T | PromiseLike<T>): Promise<T>;
//#endregion
//#region src/hash.d.ts
declare enum HashAlgorithm {
SHA256 = "SHA-256",
SHA384 = "SHA-384",
SHA512 = "SHA-512",
DJB2 = "djb2",
FNV1 = "fnv1",
MURMER = "murmer",
CRC32 = "crc32"
}
type HashOptions = {
algorithm?: HashAlgorithm;
serialize?: (object: any) => string;
};
type HashToNumberOptions = HashOptions & {
min?: number;
max?: number;
hashLength?: number;
};
/**
* Hashes an object asynchronously using the specified cryptographic algorithm.
* This method should be used for cryptographic algorithms (SHA-256, SHA-384, SHA-512).
* For non-cryptographic algorithms, use hashSync() for better performance.
* @param object The object to hash
* @param options The hash options to use
* @returns {Promise<string>} The hash of the object
*/
declare function hash(object: any, options?: HashOptions): Promise<string>;
/**
* Hashes an object synchronously using the specified non-cryptographic algorithm.
* This method should be used for non-cryptographic algorithms (DJB2, FNV1, MURMER, CRC32).
* For cryptographic algorithms, use hash() instead.
* @param object The object to hash
* @param options The hash options to use
* @returns {string} The hash of the object
*/
declare function hashSync(object: any, options?: HashOptions): string;
/**
* Hashes an object asynchronously and converts it to a number within a specified range.
* This method should be used for cryptographic algorithms (SHA-256, SHA-384, SHA-512).
* For non-cryptographic algorithms, use hashToNumberSync() for better performance.
* @param object The object to hash
* @param options The hash options to use including min/max range
* @returns {Promise<number>} A number within the specified range
*/
declare function hashToNumber(object: any, options?: HashToNumberOptions): Promise<number>;
/**
* Hashes an object synchronously and converts it to a number within a specified range.
* This method should be used for non-cryptographic algorithms (DJB2, FNV1, MURMER, CRC32).
* For cryptographic algorithms, use hashToNumber() instead.
* @param object The object to hash
* @param options The hash options to use including min/max range
* @returns {number} A number within the specified range
*/
declare function hashToNumberSync(object: any, options?: HashToNumberOptions): number;
//#endregion
//#region src/is-keyv-instance.d.ts
declare function isKeyvInstance(keyv: any): boolean;
//#endregion
//#region src/is-object.d.ts
declare function isObject<T = Record<string, unknown>>(value: unknown): value is T;
//#endregion
//#region src/less-than.d.ts
declare function lessThan(number1?: number, number2?: number): boolean;
//#endregion
//#region src/ttl.d.ts
/**
* A per-store time-to-live override. Each field is a normal TTL (a number in milliseconds or a
* human-readable shorthand such as `1s`, `1m`, `1h`, `1d`) applied to that specific store. Fields
* left undefined fall back to that store's own default TTL resolution.
*/
type PerStoreTtl = {
/**
* The time-to-live to use for the primary store.
*/
primary?: number | string;
/**
* The time-to-live to use for the secondary store.
*/
secondary?: number | string;
};
/**
* Normalizes a TTL input into per-store milliseconds. When given an object it resolves the
* `primary` and `secondary` fields independently; when given a number or shorthand string it
* applies the same value to both stores. Undefined fields (or undefined input) resolve to
* `undefined` so the caller can fall back to its own default TTL.
* @param ttl - The TTL input: a number (ms), a shorthand string, or a {@link PerStoreTtl} object.
* @returns {{ primary?: number; secondary?: number }} The resolved per-store TTLs in milliseconds.
*/
declare function resolvePerStoreTtl(ttl?: number | string | PerStoreTtl): {
primary?: number;
secondary?: number;
};
/**
* Converts a exspires value to a TTL value.
* @param expires - The expires value to convert.
* @returns {number | undefined} The TTL value in milliseconds, or undefined if the expires value is not valid.
*/
declare function getTtlFromExpires(expires: number | undefined): number | undefined;
/**
* Get the TTL value from the cacheableTtl, primaryTtl, and secondaryTtl values.
* @param cacheableTtl - The cacheableTtl value to use.
* @param primaryTtl - The primaryTtl value to use.
* @param secondaryTtl - The secondaryTtl value to use.
* @returns {number | undefined} The TTL value in milliseconds, or undefined if all values are undefined.
*/
declare function getCascadingTtl(cacheableTtl?: number | string, primaryTtl?: number, secondaryTtl?: number): number | undefined;
/**
* Calculate the TTL value from the expires value. If the ttl is undefined, it will be set to the expires value. If the
* expires value is undefined, it will be set to the ttl value. If both values are defined, the smaller of the two will be used.
* @param ttl
* @param expires
* @returns
*/
declare function calculateTtlFromExpiration(ttl: number | undefined, expires: number | undefined): number | undefined;
//#endregion
//#region src/memoize.d.ts
type CacheInstance = {
get: (key: string) => Promise<any | undefined>;
has: (key: string) => Promise<boolean>;
set: (key: string, value: any, ttl?: number | string | PerStoreTtl) => Promise<void>;
on: (event: string, listener: (...args: any[]) => void) => void;
emit: (event: string, ...args: any[]) => boolean;
};
type CacheSyncInstance = {
get: (key: string) => any | undefined;
has: (key: string) => boolean;
set: (key: string, value: any, ttl?: number | string) => void;
on: (event: string, listener: (...args: any[]) => void) => void;
emit: (event: string, ...args: any[]) => boolean;
};
type GetOrSetKey = string | ((options?: GetOrSetOptions) => string);
type GetOrSetThrowErrorsContext = "function" | "store";
type GetOrSetFunctionOptions = {
ttl?: number | string;
cacheErrors?: boolean;
/** Whether or not to throw errors:
* - `false` (default) - do not throw any errors
* - `true` - throw any error
* - `"function"` - only throw errors that occur in the provided function / setter
* - `"store"` - only throw errors that occur when getting/setting the cache
*/
throwErrors?: boolean | GetOrSetThrowErrorsContext;
/**
* If set, this will bypass the instances nonBlocking setting for the get call.
* @type {boolean}
*/
nonBlocking?: boolean;
};
type GetOrSetOptions = Omit<GetOrSetFunctionOptions, "ttl"> & {
ttl?: number | string | PerStoreTtl;
cacheId?: string;
cache: CacheInstance;
};
/**
* Options for {@link getOrSetSync}, the synchronous counterpart to {@link GetOrSetOptions}. It
* targets a {@link CacheSyncInstance} and its `ttl` is always a single value (a number in
* milliseconds or a shorthand string), never a per-store object. The inherited `nonBlocking`
* option has no effect on a single, synchronous store.
*/
type GetOrSetSyncOptions = GetOrSetFunctionOptions & {
cache: CacheSyncInstance;
};
/**
* A cache key for {@link getOrSetSync}: either a string or a function that derives the key from the
* resolved {@link GetOrSetSyncOptions}.
*/
type GetOrSetSyncKey = string | ((options?: GetOrSetSyncOptions) => string);
type CreateWrapKey = (function_: AnyFunction, arguments_: any[], options?: WrapFunctionOptions) => string;
type WrapFunctionOptions = {
ttl?: number | string;
keyPrefix?: string;
createKey?: CreateWrapKey;
cacheErrors?: boolean;
cacheId?: string;
serialize?: (object: any) => string;
};
type WrapOptions = Omit<WrapFunctionOptions, "ttl"> & {
ttl?: number | string | PerStoreTtl;
cache: CacheInstance;
serialize?: (object: any) => string;
};
type WrapSyncOptions = WrapFunctionOptions & {
cache: CacheSyncInstance;
serialize?: (object: any) => string;
};
type AnyFunction = (...arguments_: any[]) => any;
declare function wrapSync<T>(function_: AnyFunction, options: WrapSyncOptions): AnyFunction;
declare function getOrSet<T>(key: GetOrSetKey, function_: () => Promise<T>, options: GetOrSetOptions): Promise<T | undefined>;
/**
* Synchronous counterpart to {@link getOrSet}. Reads `key` from the cache and, on a miss, computes
* the value with `function_`, stores it, and returns it.
*
* Unlike {@link getOrSet} there is no request coalescing: synchronous code runs to completion
* without interleaving, so concurrent callers cannot stampede the setter the way they can with an
* async cache.
*
* Error handling mirrors {@link getOrSet}: errors are emitted on the cache's `error` event, can be
* cached when `cacheErrors` is set, and can be rethrown selectively via `throwErrors` (`true` for
* any error, `"function"` for setter errors, `"store"` for cache read/write errors).
*
* @param key - The cache key, or a function that derives it from the resolved options.
* @param function_ - The setter invoked on a cache miss to compute the value.
* @param options - The {@link GetOrSetSyncOptions} including the target synchronous cache.
* @returns The cached or freshly computed value, or `undefined`.
*/
declare function getOrSetSync<T>(key: GetOrSetSyncKey, function_: () => T, options: GetOrSetSyncOptions): T | undefined;
declare function wrap<T>(function_: AnyFunction, options: WrapOptions): AnyFunction;
type CreateWrapKeyOptions = {
keyPrefix?: string;
serialize?: (object: any) => string;
};
declare function createWrapKey(function_: AnyFunction, arguments_: any[], options?: CreateWrapKeyOptions): string;
//#endregion
//#region src/run-if-fn.d.ts
type Function_<P, T> = (...arguments_: P[]) => T;
declare function runIfFn<T, P>(valueOrFunction: T | Function_<P, T>, ...arguments_: P[]): T;
//#endregion
//#region src/sleep.d.ts
declare const sleep: (ms: number) => Promise<unknown>;
//#endregion
//#region src/stats.d.ts
/**
* A counter field that can be incremented or decremented via the unified
* {@link Stats.increment} / {@link Stats.decrement} API or an event map.
*/
type StatField = "hits" | "misses" | "gets" | "sets" | "deletes" | "clears" | "count";
/**
* A duck-typed event emitter. This intentionally matches both `Hookified`
* (used by `cacheable`, `node-cache`, `memory`, `flat-cache`) and Node's
* built-in `EventEmitter` (used by `cache-manager`, `cacheable-request`)
* without adding a hard dependency on either.
*/
type StatsEmitter = {
on(event: string, listener: (...args: any[]) => void): unknown;
off?(event: string, listener: (...args: any[]) => void): unknown;
removeListener?(event: string, listener: (...args: any[]) => void): unknown;
};
/**
* A custom handler invoked when a subscribed event fires. It receives the
* {@link Stats} instance and the raw event arguments (which may be positional,
* e.g. node-cache emits `(key, value)`).
*/
type StatsEventHandler = (stats: Stats, ...args: any[]) => void;
/**
* Maps an event name to the stat update it should perform: a single field to
* increment, an array of fields to increment, or a custom handler.
*/
type StatsEventMap = Record<string, StatField | StatField[] | StatsEventHandler>;
/**
* A counter field that can be recorded per key via {@link Stats.recordKey}.
* This is the subset of {@link StatField} that makes sense for a single key
* (`clears` and `count` are cache-wide).
*/
type KeyStatField = "hits" | "misses" | "gets" | "sets" | "deletes";
/**
* Per-key statistics returned by {@link Stats.mostUsedKeys},
* {@link Stats.leastUsedKeys}, and {@link Stats.keyStats}.
*/
type StatsKeyEntry = {
key: string; /** Total recorded operations for this key (sum of all fields). */
count: number;
hits: number;
misses: number;
gets: number;
sets: number;
deletes: number; /** `hits / (hits + misses)` for this key, or `0` when there have been no lookups. */
hitRate: number;
};
/**
* A plain-object snapshot of a {@link Stats} instance, suitable for logging,
* metrics, or serialization. Returned by {@link Stats.toJSON}.
*/
type StatsSnapshot = {
enabled: boolean;
hits: number;
misses: number;
gets: number;
sets: number;
deletes: number;
clears: number;
vsize: number;
ksize: number;
count: number;
hitRate: number;
missRate: number; /** Number of unique keys currently tracked (0 when key tracking is off). */
trackedKeys: number;
lastUpdated?: number;
lastReset?: number;
};
type StatsOptions = {
/** Whether the stats are enabled. Defaults to `false`. */enabled?: boolean; /** Optionally subscribe to an emitter immediately on construction. */
emitter?: StatsEmitter; /** The event map to use. Required when `emitter` is provided. */
eventMap?: StatsEventMap; /** Track per-key statistics via {@link Stats.recordKey}. Defaults to `false`. */
trackKeys?: boolean;
/**
* Safety cap on the number of unique keys tracked. When exceeded, the
* lowest-count keys are pruned, which keeps {@link Stats.mostUsedKeys}
* approximately accurate but makes {@link Stats.leastUsedKeys} unreliable.
* Unbounded when unset.
*/
maxTrackedKeys?: number;
};
/**
* Event map for `@cacheable/node-cache` instances. node-cache emits with
* positional arguments (e.g. `set(key, value)`), and emits each lifecycle
* event exactly once, so the counts map cleanly. `flush` clears the cache data
* and `flush_stats` resets the stats counters, mirroring node-cache's
* `flushAll()` / `flushStats()` lifecycle.
*
* Presets for `cacheable` and `cache-manager` are intentionally not provided:
* their event streams emit per-store probes (and, for cache-manager, do not
* emit an event on a normal miss), so a simple map cannot faithfully reproduce
* their imperative stats. Wire those up with a custom map or imperative calls.
*/
declare const nodeCacheStatsEventMap: StatsEventMap;
/**
* Raw per-key counters stored in {@link Stats.trackedKeys}: the
* `hits`/`misses`/`gets`/`sets`/`deletes` totals for a single cache key.
*/
type KeyCounters = Record<KeyStatField, number>;
declare class Stats {
private _counters;
private _vsize;
private _ksize;
private _enabled;
private _lastUpdated;
private _lastReset;
private _subscriptions;
/** Backing store for the public {@link trackedKeys} read-only view. */
private _trackedKeys;
private _trackKeys;
private _maxTrackedKeys;
constructor(options?: StatsOptions);
/**
* @returns {boolean} - Whether the stats are enabled
*/
get enabled(): boolean;
/**
* @param {boolean} enabled - Whether to enable the stats
*/
set enabled(enabled: boolean);
/**
* @returns {boolean} - Whether per-key statistics are tracked
*/
get trackKeys(): boolean;
/**
* @param {boolean} trackKeys - Whether to track per-key statistics
*/
set trackKeys(trackKeys: boolean);
/**
* @returns {number | undefined} - The cap on unique keys tracked, or
* `undefined` when unbounded
*/
get maxTrackedKeys(): number | undefined;
/**
* @param {number | undefined} maxTrackedKeys - The cap on unique keys
* tracked. Set `undefined` for unbounded.
*/
set maxTrackedKeys(maxTrackedKeys: number | undefined);
/**
* Per-key statistics, keyed by cache key, holding each key's raw
* `hits`/`misses`/`gets`/`sets`/`deletes` counters. Populated by
* {@link recordKey} when {@link trackKeys} is enabled; read `trackedKeys.size`
* for the number of unique keys currently tracked. The returned map is a
* read-only view — mutate per-key stats via {@link recordKey} /
* {@link clearKeys} / {@link reset}.
* @returns {ReadonlyMap<string, Readonly<KeyCounters>>}
* @readonly
*/
get trackedKeys(): ReadonlyMap<string, Readonly<KeyCounters>>;
/**
* @returns {number} - The number of hits
* @readonly
*/
get hits(): number;
/**
* @returns {number} - The number of misses
* @readonly
*/
get misses(): number;
/**
* @returns {number} - The number of gets
* @readonly
*/
get gets(): number;
/**
* @returns {number} - The number of sets
* @readonly
*/
get sets(): number;
/**
* @returns {number} - The number of deletes
* @readonly
*/
get deletes(): number;
/**
* @returns {number} - The number of clears
* @readonly
*/
get clears(): number;
/**
* @returns {number} - The vsize (value size) of the cache instance
* @readonly
*/
get vsize(): number;
/**
* @returns {number} - The ksize (key size) of the cache instance
* @readonly
*/
get ksize(): number;
/**
* @returns {number} - The count of the cache instance
* @readonly
*/
get count(): number;
/**
* The ratio of hits to total lookups (hits + misses). Returns `0` when there
* have been no lookups.
* @returns {number} - A value between 0 and 1
* @readonly
*/
get hitRate(): number;
/**
* The ratio of misses to total lookups (hits + misses). Returns `0` when
* there have been no lookups.
* @returns {number} - A value between 0 and 1
* @readonly
*/
get missRate(): number;
/**
* The timestamp (ms since epoch) of the last mutation while enabled, or
* `undefined` if there have been none since the last reset.
* @returns {number | undefined}
* @readonly
*/
get lastUpdated(): number | undefined;
/**
* The timestamp (ms since epoch) of the last {@link reset}/{@link clear}, or
* `undefined` if it has never been reset.
* @returns {number | undefined}
* @readonly
*/
get lastReset(): number | undefined;
/**
* Increment a counter field by `amount` (default `1`). No-op when disabled.
* @param {StatField} field - The counter to increment
* @param {number} amount - The amount to add (default 1)
*/
increment(field: StatField, amount?: number): void;
/**
* Decrement a counter field by `amount` (default `1`). No-op when disabled.
* @param {StatField} field - The counter to decrement
* @param {number} amount - The amount to subtract (default 1)
*/
decrement(field: StatField, amount?: number): void;
incrementHits(amount?: number): void;
incrementMisses(amount?: number): void;
incrementGets(amount?: number): void;
incrementSets(amount?: number): void;
incrementDeletes(amount?: number): void;
incrementClears(amount?: number): void;
incrementVSize(value: any): void;
decreaseVSize(value: any): void;
incrementKSize(key: string): void;
decreaseKSize(key: string): void;
incrementCount(amount?: number): void;
decreaseCount(amount?: number): void;
setCount(count: number): void;
roughSizeOfString(value: string): number;
roughSizeOfObject(object: any): number;
/**
* Enable stat tracking. Equivalent to setting {@link enabled} to `true`.
*/
enable(): void;
/**
* Disable stat tracking. Equivalent to setting {@link enabled} to `false`.
*/
disable(): void;
/**
* Reset all counters to zero and record the reset timestamp. Alias of
* {@link reset}.
*/
clear(): void;
reset(): void;
resetStoreValues(): void;
/**
* @returns {StatsSnapshot} - A plain-object snapshot of the current stats,
* including computed `hitRate`/`missRate` and timestamps.
*/
toJSON(): StatsSnapshot;
/**
* @returns {StatsSnapshot} - A plain-object snapshot of the current stats.
* Alias of {@link toJSON}.
*/
snapshot(): StatsSnapshot;
/**
* Record an operation against a specific key for per-key statistics. No-op
* unless both {@link enabled} and {@link trackKeys} are `true`.
* @param {string} key - The cache key the operation touched
* @param {KeyStatField} field - The per-key counter to increment
* @param {number} amount - The amount to add (default 1)
*/
recordKey(key: string, field: KeyStatField, amount?: number): void;
/**
* The most-used keys, sorted descending. Sorts by total recorded operations,
* or by a single field when `field` is provided. Ties order by key.
* @param {number} limit - Maximum entries to return (default 100)
* @param {KeyStatField} [field] - Optionally rank by one counter (e.g. "hits")
* @returns {StatsKeyEntry[]}
*/
mostUsedKeys(limit?: number, field?: KeyStatField): StatsKeyEntry[];
/**
* The least-used keys, sorted ascending. Sorts by total recorded operations,
* or by a single field when `field` is provided. Ties order by key. Note:
* only keys that have been recorded at least once can be ranked, and when
* {@link maxTrackedKeys} pruning has occurred the true least-used keys may
* have been evicted.
* @param {number} limit - Maximum entries to return (default 100)
* @param {KeyStatField} [field] - Optionally rank by one counter (e.g. "gets")
* @returns {StatsKeyEntry[]}
*/
leastUsedKeys(limit?: number, field?: KeyStatField): StatsKeyEntry[];
/**
* @param {string} key - The key to look up
* @returns {StatsKeyEntry | undefined} - The per-key statistics, or
* `undefined` if the key has not been recorded
*/
keyStats(key: string): StatsKeyEntry | undefined;
/**
* Clear all per-key statistics without touching the aggregate counters.
*/
clearKeys(): void;
private totalOf;
private toKeyEntry;
private sortedKeyEntries;
/**
* When over {@link maxTrackedKeys}, prune the lowest-count keys down to 90%
* of the cap (batched so the sort cost amortizes across inserts). The key
* that was just recorded is never pruned.
*/
private pruneTrackedKeys;
/**
* Subscribe to an emitter so that matching events automatically update the
* stats. Counting is gated by {@link enabled}, so you may subscribe first and
* toggle enablement later. Call {@link unsubscribe} to detach.
* @param {StatsEmitter} emitter - The emitter to listen on
* @param {StatsEventMap} eventMap - The event-to-stat mapping (e.g.
* {@link nodeCacheStatsEventMap} or a custom map)
*/
subscribe(emitter: StatsEmitter, eventMap: StatsEventMap): void;
/**
* Detach listeners previously attached via {@link subscribe}. When `emitter`
* is provided, only that emitter's listeners are removed; otherwise all are.
* @param {StatsEmitter} [emitter] - The emitter to detach from
*/
unsubscribe(emitter?: StatsEmitter): void;
private applyEvent;
private touch;
}
//#endregion
export { type AnyFunction, type CacheInstance, type CacheSyncInstance, CacheTags, type CacheTagsOptions, type CacheableItem, type CacheableStoreItem, type CreateWrapKey, type CreateWrapKeyOptions, type GetOrSetFunctionOptions, type GetOrSetKey, type GetOrSetOptions, type GetOrSetSyncKey, type GetOrSetSyncOptions, HashAlgorithm, type HashOptions, type HashToNumberOptions, type KeyCounters, type KeyStatField, type KeyTagEntry, type PerStoreTtl, type RemoveKeysOptions, type SetKeyTagsOptions, type StatField, Stats, type StatsEmitter, type StatsEventHandler, type StatsEventMap, type StatsKeyEntry, type StatsOptions, type StatsSnapshot, type WrapFunctionOptions, type WrapOptions, type WrapSyncOptions, calculateTtlFromExpiration, coalesceAsync, createWrapKey, getCascadingTtl, getOrSet, getOrSetSync, getTtlFromExpires, hash, hashSync, hashToNumber, hashToNumberSync, isKeyvInstance, isObject, lessThan, nodeCacheStatsEventMap, resolvePerStoreTtl, runIfFn, shorthandToMilliseconds, shorthandToTime, sleep, wrap, wrapSync };

903
node_modules/@cacheable/utils/dist/index.d.mts generated vendored Normal file
View File

@@ -0,0 +1,903 @@
import { Keyv } from "keyv";
//#region src/shorthand-time.d.ts
/**
* Converts a shorthand time string or number into milliseconds.
* The shorthand can be a string like '1s', '2m', '3h', '4d', or a number representing milliseconds.
* If the input is undefined, it returns undefined.
* If the input is a string that does not match the expected format, it throws an error.
* @param shorthand - A shorthand time string or number representing milliseconds.
* @returns The equivalent time in milliseconds or undefined.
*/
declare const shorthandToMilliseconds: (shorthand?: string | number) => number | undefined;
/**
* Converts a shorthand time string or number into a timestamp.
* If the shorthand is undefined, it returns the current date's timestamp.
* If the shorthand is a valid time format, it adds that duration to the current date's timestamp.
* @param shorthand - A shorthand time string or number representing milliseconds.
* @param fromDate - An optional Date object to calculate from. Defaults to the current date if not provided.
* @returns The timestamp in milliseconds since epoch.
*/
declare const shorthandToTime: (shorthand?: string | number, fromDate?: Date) => number;
//#endregion
//#region src/cache-tags.d.ts
/**
* Options for constructing a {@link CacheTags}.
* @typedef {Object} CacheTagsOptions
* @property {Keyv} store - The Keyv store used to persist tag versions and key snapshots.
* @property {string} [namespace] - An optional namespace that isolates this service's tags
* and keys from others sharing the same store. Defaults to `"default"`.
* @property {boolean} [enabled] - Whether the service is enabled. While disabled, every method
* is a no-op: read methods return their neutral value ({@link CacheTags.isKeyFresh} returns
* `true`, {@link CacheTags.isKeyStale} returns `false`, etc.) and writes are skipped. The
* service must be explicitly enabled to use tags. Defaults to `true`.
* @property {(error: unknown) => void} [onError] - Invoked with errors from non-blocking
* (fire-and-forget) operations, which cannot be thrown to the caller. Defaults to ignoring them.
*/
type CacheTagsOptions = {
store: Keyv;
namespace?: string;
enabled?: boolean;
onError?: (error: unknown) => void;
};
/**
* Options for {@link CacheTags.setKeyTags}.
* @typedef {Object} SetKeyTagsOptions
* @property {number} [ttl] - Time-to-live in milliseconds for the key's tag snapshot. Should
* match the TTL of the cached value it tracks so the snapshot expires alongside it. If omitted,
* the snapshot does not expire.
* @property {boolean} [nonBlocking] - When `true`, the snapshot write is fire-and-forget:
* the call resolves immediately and failures are reported via the `onError` option.
*/
type SetKeyTagsOptions = {
ttl?: number;
nonBlocking?: boolean;
};
/**
* Options for {@link CacheTags.removeKey} and {@link CacheTags.removeKeys}.
* @typedef {Object} RemoveKeysOptions
* @property {boolean} [nonBlocking] - When `true`, the removal is fire-and-forget:
* the call resolves immediately and failures are reported via the `onError` option.
*/
type RemoveKeysOptions = {
nonBlocking?: boolean;
};
/**
* The metadata stored for a tagged key. It records the version of each tag at the moment the key
* was written, allowing {@link CacheTags.isKeyFresh} to detect later invalidations.
* @typedef {Object} KeyTagEntry
* @property {Record<string, number>} tags - A snapshot mapping each tag name to its version at set time.
*/
type KeyTagEntry = {
tags: Record<string, number>;
};
/**
* Provides tag-based cache invalidation on top of any {@link Keyv} store. It is store-agnostic and
* requires no adapter changes.
*
* The service uses a lazy invalidation model rather than scanning and deleting keys. Each tag has a
* monotonically increasing version counter; {@link CacheTags.invalidateTag} simply increments
* it. When a key is tagged via {@link CacheTags.setKeyTags}, a snapshot of its tags' current
* versions is stored alongside it. {@link CacheTags.isKeyFresh} compares that snapshot against
* the live versions — if any tag has been incremented since, the key is considered stale. Stale
* entries are not deleted explicitly; they are expected to fall out of the cache via their TTL.
*
* This keeps invalidation constant-time regardless of how many keys reference a tag, at the cost of
* one additional `isKeyFresh` read per cache lookup.
*
* The service can be disabled via the `enabled` option or property so integrations pay no cost for
* untagged workloads: while disabled, every method is a no-op — reads return their neutral value
* and writes are skipped. The service must be explicitly enabled to use tags; it never enables
* itself, which keeps behavior consistent across distributed instances sharing a store.
*
* All metadata is written under a reserved prefix so it cannot collide with user keys:
* - `--cacheable--tags--:<namespace>:tag:<tag>` → integer version counter (stored without TTL).
* - `--cacheable--tags--:<namespace>:key:<key>` → the {@link KeyTagEntry} snapshot.
*
* Note: the read-version-then-write-snapshot sequence in `setKeyTags` is not atomic across
* processes. A concurrent `invalidateTag` running between the read and the write can leave a freshly
* written key referencing a stale version.
*
* @example
* ```typescript
* const cacheTags = new CacheTags({ store: new Keyv(), namespace: 'app' });
* await cacheTags.setKeyTags('user:42', ['users', 'org:7'], { ttl: 3600000 });
* await cacheTags.isKeyFresh('user:42'); // true
* await cacheTags.invalidateTag('users');
* await cacheTags.isKeyFresh('user:42'); // false
* ```
*/
declare class CacheTags {
private readonly _store;
private readonly _namespace;
private _enabled;
private readonly _onError?;
/**
* Creates a new tag service.
* @param {CacheTagsOptions} options - The store, optional namespace, enabled state, and
* non-blocking error handler to use.
*/
constructor(options: CacheTagsOptions);
/**
* The Keyv store backing this service.
* @returns {Keyv} The store provided to the constructor.
*/
get store(): Keyv;
/**
* The namespace isolating this service's tags and keys within the store.
* @returns {string} The configured namespace, or `"default"` if none was provided.
*/
get namespace(): string;
/**
* Whether the service is enabled. While disabled, every method is a no-op — read methods
* return their neutral value and writes are skipped — so integrations pay no extra store
* reads for untagged workloads. The service must be explicitly enabled to use tags; it never
* enables itself.
* @returns {boolean} Whether the service is enabled.
*/
get enabled(): boolean;
/**
* Sets whether the service is enabled.
* @param {boolean} enabled Whether the service is enabled.
*/
set enabled(enabled: boolean);
/**
* Builds the reserved store key under which a tag's version counter is stored.
* @param tag - The tag name.
* @returns {string} The namespaced store key for the tag's version.
*/
private tagKey;
/**
* Builds the reserved store key under which a cache key's tag snapshot is stored.
* @param key - The cache key being tagged.
* @returns {string} The namespaced store key for the key's snapshot.
*/
private keyEntryKey;
/**
* Builds the common prefix shared by every key-snapshot entry in this namespace. Used to filter
* key entries when iterating the store.
* @returns {string} The namespaced key-entry prefix.
*/
private keyPrefix;
/**
* Reads the current version of a single tag.
* @param tag - The tag name.
* @returns {Promise<number>} The tag's version, or `0` if it has never been invalidated.
*/
private getTagVersion;
/**
* Reads the current versions of multiple tags in a single batched store read.
* @param tags - The tag names to look up.
* @returns {Promise<number[]>} The versions in the same order as `tags`; entries that have never
* been invalidated resolve to `0`. Returns an empty array when `tags` is empty.
*/
private getTagVersions;
/**
* Reports a fire-and-forget failure to the `onError` handler, if one was provided.
* @param error - The error raised by the non-blocking operation.
*/
private handleNonBlockingError;
/**
* Reads the version snapshot of each tag and writes the key's tag snapshot to the store.
* @param key - The cache key to tag.
* @param tags - The tags to associate with the key.
* @param ttl - Time-to-live in milliseconds for the snapshot.
* @returns {Promise<void>} Resolves once the snapshot has been written.
*/
private writeKeyTags;
/**
* Associates a cache key with a set of tags by recording a snapshot of each tag's current
* version. Call this whenever you write a fresh value to the cache. Duplicate tags are ignored.
* No-op while the service is disabled.
* @param key - The cache key to tag.
* @param tags - The tags to associate with the key.
* @param {SetKeyTagsOptions} [options] - Optional settings, such as a `ttl` for the snapshot or
* `nonBlocking` to fire-and-forget the write.
* @returns {Promise<void>} Resolves once the snapshot has been written, or immediately when
* `nonBlocking` is set.
*/
setKeyTags(key: string, tags: string[], options?: SetKeyTagsOptions): Promise<void>;
/**
* Removes a key's tag snapshot. After this, {@link CacheTags.isKeyFresh} returns `false`
* for the key. Use when the cached value itself is deleted. No-op while the service is
* disabled.
* @param key - The cache key whose snapshot should be removed.
* @param {RemoveKeysOptions} [options] - Optional settings, such as `nonBlocking` to
* fire-and-forget the removal.
* @returns {Promise<void>} Resolves once the snapshot has been deleted, or immediately when
* `nonBlocking` is set.
*/
removeKey(key: string, options?: RemoveKeysOptions): Promise<void>;
/**
* Removes multiple keys' tag snapshots in a single batched store delete. After this,
* {@link CacheTags.isKeyFresh} returns `false` for each key. An empty list is a no-op, as is
* the entire call while the service is disabled.
* @param keys - The cache keys whose snapshots should be removed.
* @param {RemoveKeysOptions} [options] - Optional settings, such as `nonBlocking` to
* fire-and-forget the removal.
* @returns {Promise<void>} Resolves once the snapshots have been deleted, or immediately when
* `nonBlocking` is set.
*/
removeKeys(keys: string[], options?: RemoveKeysOptions): Promise<void>;
/**
* Determines whether a key's cached value can still be trusted. A key is fresh only when a
* snapshot exists for it and every tag in that snapshot still has the version it had at set time.
* A key with no tags is trivially fresh. Call this before returning a value from your cache.
* Always returns `true` while the service is disabled.
* @param key - The cache key to check.
* @returns {Promise<boolean>} `true` if the key is still fresh; `false` if it is unknown or any of
* its tags has been invalidated since the snapshot was taken.
*/
isKeyFresh(key: string): Promise<boolean>;
/**
* Determines whether a key's cached value is known to be stale due to tag invalidation. This is
* the complement of {@link CacheTags.isKeyFresh} for tagged keys, but treats keys without a
* snapshot as not stale — making it safe to call for every cache lookup, including keys that were
* never tagged. Always returns `false` while the service is disabled.
* @param key - The cache key to check.
* @returns {Promise<boolean>} `true` only when a snapshot exists for the key and at least one of
* its tags has been invalidated since the snapshot was taken; `false` otherwise (including when
* the key has no snapshot).
*/
isKeyStale(key: string): Promise<boolean>;
/**
* Determines which of the given keys are known to be stale due to tag invalidation, using two
* batched store reads regardless of how many keys are checked: one for the snapshots and one for
* the union of their tag versions. Keys without a snapshot are not considered stale. Returns an
* empty array while the service is disabled.
* @param keys - The cache keys to check.
* @returns {Promise<string[]>} The subset of `keys` whose snapshot references at least one tag
* that has been invalidated since the snapshot was taken.
*/
getStaleKeys(keys: string[]): Promise<string[]>;
/**
* Returns the tags currently associated with a key. Returns `undefined` while the service is
* disabled.
* @param key - The cache key to look up.
* @returns {Promise<string[] | undefined>} The tag names from the key's snapshot, or `undefined`
* if the key has no snapshot.
*/
getTags(key: string): Promise<string[] | undefined>;
/**
* Returns all cache keys whose snapshot references the given tag. This scans every key entry in
* the namespace via the Keyv iterator, making it an `O(N)` operation intended for debugging and
* tests rather than hot paths. Returns an empty array if the underlying store exposes no iterator
* or while the service is disabled.
* @param tag - The tag to search for.
* @returns {Promise<string[]>} The cache keys (with the reserved prefix stripped) referencing the tag.
*/
getKeysByTag(tag: string): Promise<string[]>;
/**
* Invalidates a single tag by incrementing its version counter. Every key whose snapshot
* references this tag becomes stale immediately. Runs in constant time regardless of how many
* keys reference the tag. No-op while the service is disabled.
* @param tag - The tag to invalidate.
* @returns {Promise<string[]>} A single-element array containing the invalidated tag, or an
* empty array while the service is disabled.
*/
invalidateTag(tag: string): Promise<string[]>;
/**
* Invalidates multiple tags by incrementing each of their version counters in a single batched
* store write. Duplicate tags are bumped once. An empty list is a no-op, as is the entire call
* while the service is disabled.
* @param tags - The tags to invalidate.
* @returns {Promise<string[]>} The `tags` argument as provided (including any duplicates), or
* an empty array while the service is disabled.
*/
invalidateTags(tags: string[]): Promise<string[]>;
}
//#endregion
//#region src/cacheable-item-types.d.ts
/**
* CacheableItem
* @typedef {Object} CacheableItem
* @property {string} key - The key of the cacheable item
* @property {any} value - The value of the cacheable item
* @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
* 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
* undefined then it will not have a time-to-live.
*/
type CacheableItem = {
key: string;
value: any;
ttl?: number | string;
};
/**
* CacheableStoreItem
* @typedef {Object} CacheableStoreItem
* @property {string} key - The key of the cacheable store item
* @property {any} value - The value of the cacheable store item
* @property {number} [expires] - The expiration time in milliseconds since epoch. If not set, the item does not expire.
*/
type CacheableStoreItem = {
key: string;
value: any;
expires?: number;
};
//#endregion
//#region src/coalesce-async.d.ts
/**
* Enqueue a promise for the group identified by `key`.
*
* All requests received for the same key while a request for that key
* is already being executed will wait. Once the running request settles
* then all the waiting requests in the group will settle, too.
* This minimizes how many times the function itself runs at the same time.
* This function resolves or rejects according to the given function argument.
*
* @url https://github.com/douglascayers/promise-coalesce
*/
declare function coalesceAsync<T>(
/**
* Any identifier to group requests together.
*/
key: string,
/**
* The function to run.
*/
fnc: () => T | PromiseLike<T>): Promise<T>;
//#endregion
//#region src/hash.d.ts
declare enum HashAlgorithm {
SHA256 = "SHA-256",
SHA384 = "SHA-384",
SHA512 = "SHA-512",
DJB2 = "djb2",
FNV1 = "fnv1",
MURMER = "murmer",
CRC32 = "crc32"
}
type HashOptions = {
algorithm?: HashAlgorithm;
serialize?: (object: any) => string;
};
type HashToNumberOptions = HashOptions & {
min?: number;
max?: number;
hashLength?: number;
};
/**
* Hashes an object asynchronously using the specified cryptographic algorithm.
* This method should be used for cryptographic algorithms (SHA-256, SHA-384, SHA-512).
* For non-cryptographic algorithms, use hashSync() for better performance.
* @param object The object to hash
* @param options The hash options to use
* @returns {Promise<string>} The hash of the object
*/
declare function hash(object: any, options?: HashOptions): Promise<string>;
/**
* Hashes an object synchronously using the specified non-cryptographic algorithm.
* This method should be used for non-cryptographic algorithms (DJB2, FNV1, MURMER, CRC32).
* For cryptographic algorithms, use hash() instead.
* @param object The object to hash
* @param options The hash options to use
* @returns {string} The hash of the object
*/
declare function hashSync(object: any, options?: HashOptions): string;
/**
* Hashes an object asynchronously and converts it to a number within a specified range.
* This method should be used for cryptographic algorithms (SHA-256, SHA-384, SHA-512).
* For non-cryptographic algorithms, use hashToNumberSync() for better performance.
* @param object The object to hash
* @param options The hash options to use including min/max range
* @returns {Promise<number>} A number within the specified range
*/
declare function hashToNumber(object: any, options?: HashToNumberOptions): Promise<number>;
/**
* Hashes an object synchronously and converts it to a number within a specified range.
* This method should be used for non-cryptographic algorithms (DJB2, FNV1, MURMER, CRC32).
* For cryptographic algorithms, use hashToNumber() instead.
* @param object The object to hash
* @param options The hash options to use including min/max range
* @returns {number} A number within the specified range
*/
declare function hashToNumberSync(object: any, options?: HashToNumberOptions): number;
//#endregion
//#region src/is-keyv-instance.d.ts
declare function isKeyvInstance(keyv: any): boolean;
//#endregion
//#region src/is-object.d.ts
declare function isObject<T = Record<string, unknown>>(value: unknown): value is T;
//#endregion
//#region src/less-than.d.ts
declare function lessThan(number1?: number, number2?: number): boolean;
//#endregion
//#region src/ttl.d.ts
/**
* A per-store time-to-live override. Each field is a normal TTL (a number in milliseconds or a
* human-readable shorthand such as `1s`, `1m`, `1h`, `1d`) applied to that specific store. Fields
* left undefined fall back to that store's own default TTL resolution.
*/
type PerStoreTtl = {
/**
* The time-to-live to use for the primary store.
*/
primary?: number | string;
/**
* The time-to-live to use for the secondary store.
*/
secondary?: number | string;
};
/**
* Normalizes a TTL input into per-store milliseconds. When given an object it resolves the
* `primary` and `secondary` fields independently; when given a number or shorthand string it
* applies the same value to both stores. Undefined fields (or undefined input) resolve to
* `undefined` so the caller can fall back to its own default TTL.
* @param ttl - The TTL input: a number (ms), a shorthand string, or a {@link PerStoreTtl} object.
* @returns {{ primary?: number; secondary?: number }} The resolved per-store TTLs in milliseconds.
*/
declare function resolvePerStoreTtl(ttl?: number | string | PerStoreTtl): {
primary?: number;
secondary?: number;
};
/**
* Converts a exspires value to a TTL value.
* @param expires - The expires value to convert.
* @returns {number | undefined} The TTL value in milliseconds, or undefined if the expires value is not valid.
*/
declare function getTtlFromExpires(expires: number | undefined): number | undefined;
/**
* Get the TTL value from the cacheableTtl, primaryTtl, and secondaryTtl values.
* @param cacheableTtl - The cacheableTtl value to use.
* @param primaryTtl - The primaryTtl value to use.
* @param secondaryTtl - The secondaryTtl value to use.
* @returns {number | undefined} The TTL value in milliseconds, or undefined if all values are undefined.
*/
declare function getCascadingTtl(cacheableTtl?: number | string, primaryTtl?: number, secondaryTtl?: number): number | undefined;
/**
* Calculate the TTL value from the expires value. If the ttl is undefined, it will be set to the expires value. If the
* expires value is undefined, it will be set to the ttl value. If both values are defined, the smaller of the two will be used.
* @param ttl
* @param expires
* @returns
*/
declare function calculateTtlFromExpiration(ttl: number | undefined, expires: number | undefined): number | undefined;
//#endregion
//#region src/memoize.d.ts
type CacheInstance = {
get: (key: string) => Promise<any | undefined>;
has: (key: string) => Promise<boolean>;
set: (key: string, value: any, ttl?: number | string | PerStoreTtl) => Promise<void>;
on: (event: string, listener: (...args: any[]) => void) => void;
emit: (event: string, ...args: any[]) => boolean;
};
type CacheSyncInstance = {
get: (key: string) => any | undefined;
has: (key: string) => boolean;
set: (key: string, value: any, ttl?: number | string) => void;
on: (event: string, listener: (...args: any[]) => void) => void;
emit: (event: string, ...args: any[]) => boolean;
};
type GetOrSetKey = string | ((options?: GetOrSetOptions) => string);
type GetOrSetThrowErrorsContext = "function" | "store";
type GetOrSetFunctionOptions = {
ttl?: number | string;
cacheErrors?: boolean;
/** Whether or not to throw errors:
* - `false` (default) - do not throw any errors
* - `true` - throw any error
* - `"function"` - only throw errors that occur in the provided function / setter
* - `"store"` - only throw errors that occur when getting/setting the cache
*/
throwErrors?: boolean | GetOrSetThrowErrorsContext;
/**
* If set, this will bypass the instances nonBlocking setting for the get call.
* @type {boolean}
*/
nonBlocking?: boolean;
};
type GetOrSetOptions = Omit<GetOrSetFunctionOptions, "ttl"> & {
ttl?: number | string | PerStoreTtl;
cacheId?: string;
cache: CacheInstance;
};
/**
* Options for {@link getOrSetSync}, the synchronous counterpart to {@link GetOrSetOptions}. It
* targets a {@link CacheSyncInstance} and its `ttl` is always a single value (a number in
* milliseconds or a shorthand string), never a per-store object. The inherited `nonBlocking`
* option has no effect on a single, synchronous store.
*/
type GetOrSetSyncOptions = GetOrSetFunctionOptions & {
cache: CacheSyncInstance;
};
/**
* A cache key for {@link getOrSetSync}: either a string or a function that derives the key from the
* resolved {@link GetOrSetSyncOptions}.
*/
type GetOrSetSyncKey = string | ((options?: GetOrSetSyncOptions) => string);
type CreateWrapKey = (function_: AnyFunction, arguments_: any[], options?: WrapFunctionOptions) => string;
type WrapFunctionOptions = {
ttl?: number | string;
keyPrefix?: string;
createKey?: CreateWrapKey;
cacheErrors?: boolean;
cacheId?: string;
serialize?: (object: any) => string;
};
type WrapOptions = Omit<WrapFunctionOptions, "ttl"> & {
ttl?: number | string | PerStoreTtl;
cache: CacheInstance;
serialize?: (object: any) => string;
};
type WrapSyncOptions = WrapFunctionOptions & {
cache: CacheSyncInstance;
serialize?: (object: any) => string;
};
type AnyFunction = (...arguments_: any[]) => any;
declare function wrapSync<T>(function_: AnyFunction, options: WrapSyncOptions): AnyFunction;
declare function getOrSet<T>(key: GetOrSetKey, function_: () => Promise<T>, options: GetOrSetOptions): Promise<T | undefined>;
/**
* Synchronous counterpart to {@link getOrSet}. Reads `key` from the cache and, on a miss, computes
* the value with `function_`, stores it, and returns it.
*
* Unlike {@link getOrSet} there is no request coalescing: synchronous code runs to completion
* without interleaving, so concurrent callers cannot stampede the setter the way they can with an
* async cache.
*
* Error handling mirrors {@link getOrSet}: errors are emitted on the cache's `error` event, can be
* cached when `cacheErrors` is set, and can be rethrown selectively via `throwErrors` (`true` for
* any error, `"function"` for setter errors, `"store"` for cache read/write errors).
*
* @param key - The cache key, or a function that derives it from the resolved options.
* @param function_ - The setter invoked on a cache miss to compute the value.
* @param options - The {@link GetOrSetSyncOptions} including the target synchronous cache.
* @returns The cached or freshly computed value, or `undefined`.
*/
declare function getOrSetSync<T>(key: GetOrSetSyncKey, function_: () => T, options: GetOrSetSyncOptions): T | undefined;
declare function wrap<T>(function_: AnyFunction, options: WrapOptions): AnyFunction;
type CreateWrapKeyOptions = {
keyPrefix?: string;
serialize?: (object: any) => string;
};
declare function createWrapKey(function_: AnyFunction, arguments_: any[], options?: CreateWrapKeyOptions): string;
//#endregion
//#region src/run-if-fn.d.ts
type Function_<P, T> = (...arguments_: P[]) => T;
declare function runIfFn<T, P>(valueOrFunction: T | Function_<P, T>, ...arguments_: P[]): T;
//#endregion
//#region src/sleep.d.ts
declare const sleep: (ms: number) => Promise<unknown>;
//#endregion
//#region src/stats.d.ts
/**
* A counter field that can be incremented or decremented via the unified
* {@link Stats.increment} / {@link Stats.decrement} API or an event map.
*/
type StatField = "hits" | "misses" | "gets" | "sets" | "deletes" | "clears" | "count";
/**
* A duck-typed event emitter. This intentionally matches both `Hookified`
* (used by `cacheable`, `node-cache`, `memory`, `flat-cache`) and Node's
* built-in `EventEmitter` (used by `cache-manager`, `cacheable-request`)
* without adding a hard dependency on either.
*/
type StatsEmitter = {
on(event: string, listener: (...args: any[]) => void): unknown;
off?(event: string, listener: (...args: any[]) => void): unknown;
removeListener?(event: string, listener: (...args: any[]) => void): unknown;
};
/**
* A custom handler invoked when a subscribed event fires. It receives the
* {@link Stats} instance and the raw event arguments (which may be positional,
* e.g. node-cache emits `(key, value)`).
*/
type StatsEventHandler = (stats: Stats, ...args: any[]) => void;
/**
* Maps an event name to the stat update it should perform: a single field to
* increment, an array of fields to increment, or a custom handler.
*/
type StatsEventMap = Record<string, StatField | StatField[] | StatsEventHandler>;
/**
* A counter field that can be recorded per key via {@link Stats.recordKey}.
* This is the subset of {@link StatField} that makes sense for a single key
* (`clears` and `count` are cache-wide).
*/
type KeyStatField = "hits" | "misses" | "gets" | "sets" | "deletes";
/**
* Per-key statistics returned by {@link Stats.mostUsedKeys},
* {@link Stats.leastUsedKeys}, and {@link Stats.keyStats}.
*/
type StatsKeyEntry = {
key: string; /** Total recorded operations for this key (sum of all fields). */
count: number;
hits: number;
misses: number;
gets: number;
sets: number;
deletes: number; /** `hits / (hits + misses)` for this key, or `0` when there have been no lookups. */
hitRate: number;
};
/**
* A plain-object snapshot of a {@link Stats} instance, suitable for logging,
* metrics, or serialization. Returned by {@link Stats.toJSON}.
*/
type StatsSnapshot = {
enabled: boolean;
hits: number;
misses: number;
gets: number;
sets: number;
deletes: number;
clears: number;
vsize: number;
ksize: number;
count: number;
hitRate: number;
missRate: number; /** Number of unique keys currently tracked (0 when key tracking is off). */
trackedKeys: number;
lastUpdated?: number;
lastReset?: number;
};
type StatsOptions = {
/** Whether the stats are enabled. Defaults to `false`. */enabled?: boolean; /** Optionally subscribe to an emitter immediately on construction. */
emitter?: StatsEmitter; /** The event map to use. Required when `emitter` is provided. */
eventMap?: StatsEventMap; /** Track per-key statistics via {@link Stats.recordKey}. Defaults to `false`. */
trackKeys?: boolean;
/**
* Safety cap on the number of unique keys tracked. When exceeded, the
* lowest-count keys are pruned, which keeps {@link Stats.mostUsedKeys}
* approximately accurate but makes {@link Stats.leastUsedKeys} unreliable.
* Unbounded when unset.
*/
maxTrackedKeys?: number;
};
/**
* Event map for `@cacheable/node-cache` instances. node-cache emits with
* positional arguments (e.g. `set(key, value)`), and emits each lifecycle
* event exactly once, so the counts map cleanly. `flush` clears the cache data
* and `flush_stats` resets the stats counters, mirroring node-cache's
* `flushAll()` / `flushStats()` lifecycle.
*
* Presets for `cacheable` and `cache-manager` are intentionally not provided:
* their event streams emit per-store probes (and, for cache-manager, do not
* emit an event on a normal miss), so a simple map cannot faithfully reproduce
* their imperative stats. Wire those up with a custom map or imperative calls.
*/
declare const nodeCacheStatsEventMap: StatsEventMap;
/**
* Raw per-key counters stored in {@link Stats.trackedKeys}: the
* `hits`/`misses`/`gets`/`sets`/`deletes` totals for a single cache key.
*/
type KeyCounters = Record<KeyStatField, number>;
declare class Stats {
private _counters;
private _vsize;
private _ksize;
private _enabled;
private _lastUpdated;
private _lastReset;
private _subscriptions;
/** Backing store for the public {@link trackedKeys} read-only view. */
private _trackedKeys;
private _trackKeys;
private _maxTrackedKeys;
constructor(options?: StatsOptions);
/**
* @returns {boolean} - Whether the stats are enabled
*/
get enabled(): boolean;
/**
* @param {boolean} enabled - Whether to enable the stats
*/
set enabled(enabled: boolean);
/**
* @returns {boolean} - Whether per-key statistics are tracked
*/
get trackKeys(): boolean;
/**
* @param {boolean} trackKeys - Whether to track per-key statistics
*/
set trackKeys(trackKeys: boolean);
/**
* @returns {number | undefined} - The cap on unique keys tracked, or
* `undefined` when unbounded
*/
get maxTrackedKeys(): number | undefined;
/**
* @param {number | undefined} maxTrackedKeys - The cap on unique keys
* tracked. Set `undefined` for unbounded.
*/
set maxTrackedKeys(maxTrackedKeys: number | undefined);
/**
* Per-key statistics, keyed by cache key, holding each key's raw
* `hits`/`misses`/`gets`/`sets`/`deletes` counters. Populated by
* {@link recordKey} when {@link trackKeys} is enabled; read `trackedKeys.size`
* for the number of unique keys currently tracked. The returned map is a
* read-only view — mutate per-key stats via {@link recordKey} /
* {@link clearKeys} / {@link reset}.
* @returns {ReadonlyMap<string, Readonly<KeyCounters>>}
* @readonly
*/
get trackedKeys(): ReadonlyMap<string, Readonly<KeyCounters>>;
/**
* @returns {number} - The number of hits
* @readonly
*/
get hits(): number;
/**
* @returns {number} - The number of misses
* @readonly
*/
get misses(): number;
/**
* @returns {number} - The number of gets
* @readonly
*/
get gets(): number;
/**
* @returns {number} - The number of sets
* @readonly
*/
get sets(): number;
/**
* @returns {number} - The number of deletes
* @readonly
*/
get deletes(): number;
/**
* @returns {number} - The number of clears
* @readonly
*/
get clears(): number;
/**
* @returns {number} - The vsize (value size) of the cache instance
* @readonly
*/
get vsize(): number;
/**
* @returns {number} - The ksize (key size) of the cache instance
* @readonly
*/
get ksize(): number;
/**
* @returns {number} - The count of the cache instance
* @readonly
*/
get count(): number;
/**
* The ratio of hits to total lookups (hits + misses). Returns `0` when there
* have been no lookups.
* @returns {number} - A value between 0 and 1
* @readonly
*/
get hitRate(): number;
/**
* The ratio of misses to total lookups (hits + misses). Returns `0` when
* there have been no lookups.
* @returns {number} - A value between 0 and 1
* @readonly
*/
get missRate(): number;
/**
* The timestamp (ms since epoch) of the last mutation while enabled, or
* `undefined` if there have been none since the last reset.
* @returns {number | undefined}
* @readonly
*/
get lastUpdated(): number | undefined;
/**
* The timestamp (ms since epoch) of the last {@link reset}/{@link clear}, or
* `undefined` if it has never been reset.
* @returns {number | undefined}
* @readonly
*/
get lastReset(): number | undefined;
/**
* Increment a counter field by `amount` (default `1`). No-op when disabled.
* @param {StatField} field - The counter to increment
* @param {number} amount - The amount to add (default 1)
*/
increment(field: StatField, amount?: number): void;
/**
* Decrement a counter field by `amount` (default `1`). No-op when disabled.
* @param {StatField} field - The counter to decrement
* @param {number} amount - The amount to subtract (default 1)
*/
decrement(field: StatField, amount?: number): void;
incrementHits(amount?: number): void;
incrementMisses(amount?: number): void;
incrementGets(amount?: number): void;
incrementSets(amount?: number): void;
incrementDeletes(amount?: number): void;
incrementClears(amount?: number): void;
incrementVSize(value: any): void;
decreaseVSize(value: any): void;
incrementKSize(key: string): void;
decreaseKSize(key: string): void;
incrementCount(amount?: number): void;
decreaseCount(amount?: number): void;
setCount(count: number): void;
roughSizeOfString(value: string): number;
roughSizeOfObject(object: any): number;
/**
* Enable stat tracking. Equivalent to setting {@link enabled} to `true`.
*/
enable(): void;
/**
* Disable stat tracking. Equivalent to setting {@link enabled} to `false`.
*/
disable(): void;
/**
* Reset all counters to zero and record the reset timestamp. Alias of
* {@link reset}.
*/
clear(): void;
reset(): void;
resetStoreValues(): void;
/**
* @returns {StatsSnapshot} - A plain-object snapshot of the current stats,
* including computed `hitRate`/`missRate` and timestamps.
*/
toJSON(): StatsSnapshot;
/**
* @returns {StatsSnapshot} - A plain-object snapshot of the current stats.
* Alias of {@link toJSON}.
*/
snapshot(): StatsSnapshot;
/**
* Record an operation against a specific key for per-key statistics. No-op
* unless both {@link enabled} and {@link trackKeys} are `true`.
* @param {string} key - The cache key the operation touched
* @param {KeyStatField} field - The per-key counter to increment
* @param {number} amount - The amount to add (default 1)
*/
recordKey(key: string, field: KeyStatField, amount?: number): void;
/**
* The most-used keys, sorted descending. Sorts by total recorded operations,
* or by a single field when `field` is provided. Ties order by key.
* @param {number} limit - Maximum entries to return (default 100)
* @param {KeyStatField} [field] - Optionally rank by one counter (e.g. "hits")
* @returns {StatsKeyEntry[]}
*/
mostUsedKeys(limit?: number, field?: KeyStatField): StatsKeyEntry[];
/**
* The least-used keys, sorted ascending. Sorts by total recorded operations,
* or by a single field when `field` is provided. Ties order by key. Note:
* only keys that have been recorded at least once can be ranked, and when
* {@link maxTrackedKeys} pruning has occurred the true least-used keys may
* have been evicted.
* @param {number} limit - Maximum entries to return (default 100)
* @param {KeyStatField} [field] - Optionally rank by one counter (e.g. "gets")
* @returns {StatsKeyEntry[]}
*/
leastUsedKeys(limit?: number, field?: KeyStatField): StatsKeyEntry[];
/**
* @param {string} key - The key to look up
* @returns {StatsKeyEntry | undefined} - The per-key statistics, or
* `undefined` if the key has not been recorded
*/
keyStats(key: string): StatsKeyEntry | undefined;
/**
* Clear all per-key statistics without touching the aggregate counters.
*/
clearKeys(): void;
private totalOf;
private toKeyEntry;
private sortedKeyEntries;
/**
* When over {@link maxTrackedKeys}, prune the lowest-count keys down to 90%
* of the cap (batched so the sort cost amortizes across inserts). The key
* that was just recorded is never pruned.
*/
private pruneTrackedKeys;
/**
* Subscribe to an emitter so that matching events automatically update the
* stats. Counting is gated by {@link enabled}, so you may subscribe first and
* toggle enablement later. Call {@link unsubscribe} to detach.
* @param {StatsEmitter} emitter - The emitter to listen on
* @param {StatsEventMap} eventMap - The event-to-stat mapping (e.g.
* {@link nodeCacheStatsEventMap} or a custom map)
*/
subscribe(emitter: StatsEmitter, eventMap: StatsEventMap): void;
/**
* Detach listeners previously attached via {@link subscribe}. When `emitter`
* is provided, only that emitter's listeners are removed; otherwise all are.
* @param {StatsEmitter} [emitter] - The emitter to detach from
*/
unsubscribe(emitter?: StatsEmitter): void;
private applyEvent;
private touch;
}
//#endregion
export { type AnyFunction, type CacheInstance, type CacheSyncInstance, CacheTags, type CacheTagsOptions, type CacheableItem, type CacheableStoreItem, type CreateWrapKey, type CreateWrapKeyOptions, type GetOrSetFunctionOptions, type GetOrSetKey, type GetOrSetOptions, type GetOrSetSyncKey, type GetOrSetSyncOptions, HashAlgorithm, type HashOptions, type HashToNumberOptions, type KeyCounters, type KeyStatField, type KeyTagEntry, type PerStoreTtl, type RemoveKeysOptions, type SetKeyTagsOptions, type StatField, Stats, type StatsEmitter, type StatsEventHandler, type StatsEventMap, type StatsKeyEntry, type StatsOptions, type StatsSnapshot, type WrapFunctionOptions, type WrapOptions, type WrapSyncOptions, calculateTtlFromExpiration, coalesceAsync, createWrapKey, getCascadingTtl, getOrSet, getOrSetSync, getTtlFromExpires, hash, hashSync, hashToNumber, hashToNumberSync, isKeyvInstance, isObject, lessThan, nodeCacheStatsEventMap, resolvePerStoreTtl, runIfFn, shorthandToMilliseconds, shorthandToTime, sleep, wrap, wrapSync };

1355
node_modules/@cacheable/utils/dist/index.mjs generated vendored Normal file

File diff suppressed because it is too large Load Diff

56
node_modules/@cacheable/utils/package.json generated vendored Normal file
View File

@@ -0,0 +1,56 @@
{
"name": "@cacheable/utils",
"version": "2.5.0",
"description": "Cacheable Utilities for Caching Libraries",
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.mts",
"exports": {
".": {
"import": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
},
"require": {
"types": "./dist/index.d.cts",
"default": "./dist/index.cjs"
}
}
},
"repository": {
"type": "git",
"url": "git+https://github.com/jaredwray/cacheable.git",
"directory": "packages/utils"
},
"author": "Jared Wray <me@jaredwray.com>",
"license": "MIT",
"private": false,
"dependencies": {
"hashery": "^1.5.1",
"keyv": "^5.6.0"
},
"devDependencies": {
"tsdown": "^0.22.0",
"typescript": "^5.9.3"
},
"keywords": [
"cacheable",
"caching",
"utilities",
"hashing",
"keyv",
"cache utils"
],
"files": [
"dist",
"LICENSE"
],
"scripts": {
"build": "rimraf ./dist && tsdown src/index.ts --format cjs,esm --dts --clean",
"lint": "biome check --write --error-on-warnings",
"test": "pnpm lint && vitest run --coverage",
"test:ci": "biome check --error-on-warnings && vitest run --coverage",
"clean": "rimraf ./dist ./coverage ./node_modules"
}
}