intial
This commit is contained in:
19
node_modules/@cacheable/utils/LICENSE
generated
vendored
Normal file
19
node_modules/@cacheable/utils/LICENSE
generated
vendored
Normal 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
854
node_modules/@cacheable/utils/README.md
generated
vendored
Normal file
@@ -0,0 +1,854 @@
|
||||
[<img align="center" src="https://cacheable.org/logo.svg" alt="Cacheable" />](https://github.com/jaredwray/cacheable)
|
||||
|
||||
> Cacheble Utils
|
||||
|
||||
[](https://codecov.io/gh/jaredwray/cacheable)
|
||||
[](https://github.com/jaredwray/cacheable/actions/workflows/tests.yml)
|
||||
[](https://www.npmjs.com/package/@cacheable/utils)
|
||||
[](https://www.npmjs.com/package/@cacheable/utils)
|
||||
[](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
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
903
node_modules/@cacheable/utils/dist/index.d.cts
generated
vendored
Normal 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
903
node_modules/@cacheable/utils/dist/index.d.mts
generated
vendored
Normal 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
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
56
node_modules/@cacheable/utils/package.json
generated
vendored
Normal 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"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user