### Initialize and Use BunCache Source: https://github.com/nds-stack/bun-cache/blob/main/README.md Demonstrates basic usage of BunCache, including initialization with options, setting, getting, checking existence, and deleting cache entries. Ensure the package is installed before use. ```typescript import { BunCache } from "@nds-stack/bun-cache"; const cache = new BunCache({ maxKeys: 1000, defaultTTL: 60_000 }); cache.set("session", { user: "alice" }); const session = cache.get("session"); // → { user: "alice" } cache.has("session"); // → true cache.delete("session"); // → true ``` -------------------------------- ### Install @nds-stack/bun-cache Source: https://github.com/nds-stack/bun-cache/blob/main/README.md Command to add the @nds-stack/bun-cache package to your project using Bun. ```bash bun add @nds-stack/bun-cache ``` -------------------------------- ### BunCache Methods Source: https://github.com/nds-stack/bun-cache/blob/main/README.md Provides a comprehensive set of methods for interacting with the cache, including setting, getting, deleting, and inspecting entries. ```APIDOC ## Methods ### `set(key, value, ttl?)` - **Description**: Set a value in the cache. An optional per-key TTL can override the default TTL. - **Returns**: `void` ### `get(key)` - **Description**: Retrieve a value from the cache. Returns `undefined` if the key is missing or has expired. - **Returns**: `T | undefined` ### `has(key)` - **Description**: Check if a key exists in the cache and has not expired. - **Returns**: `boolean` ### `delete(key)` - **Description**: Remove a key-value pair from the cache. Returns `true` if the key existed. - **Returns**: `boolean` ### `clear()` - **Description**: Remove all entries from the cache and reset statistics. - **Returns**: `void` ### `remainingTTL(key)` - **Description**: Get the remaining time-to-live in milliseconds for a key. Returns `-1` if the key has no TTL, has expired, or is missing. - **Returns**: `number` ### `keys()` - **Description**: Get an array of all keys currently in the cache. - **Returns**: `string[]` ### `values()` - **Description**: Get an array of all values currently in the cache. - **Returns**: `T[]` ### `entries()` - **Description**: Get an array of all key-value pairs currently in the cache. - **Returns**: `{ key: string, value: T }[]` ### `size` (getter) - **Description**: Get the current number of entries in the cache. - **Returns**: `number` ### `stats` (getter) - **Description**: Get cache statistics, including hit, miss, and eviction counters. - **Returns**: `CacheStats` ``` -------------------------------- ### BunCacheError and Custom Subclass Example Source: https://context7.com/nds-stack/bun-cache/llms.txt Demonstrates how to use the custom BunCacheError for error handling and how to extend it to create more specific error types like RateLimitCacheError. ```typescript import { BunCacheError } from "@nds-stack/bun-cache"; function safeCacheOperation(fn: () => void): void { try { fn(); } catch (err) { if (err instanceof BunCacheError) { console.error("Cache operation failed:", err.message); } else { throw err; } } } // Custom subclass example class RateLimitCacheError extends BunCacheError { constructor(key: string) { super(`Rate limit exceeded for key: ${key}`); this.name = "RateLimitCacheError"; } } const error = new RateLimitCacheError("user:42"); console.log(error instanceof BunCacheError); // true console.log(error.name); // "RateLimitCacheError" console.log(error.message); // "Rate limit exceeded for key: user:42" ``` -------------------------------- ### get(key) Source: https://context7.com/nds-stack/bun-cache/llms.txt Retrieves the value for a key. Returns `undefined` if the key is not found or has expired. Lazy TTL check removes expired entries. ```APIDOC ## `get(key)` Retrieves the value for `key`. Returns `undefined` if the key does not exist or has expired. On expiry detection, the entry is removed and the `onExpire` event handler is called. Uses a generic type parameter for typed retrieval. ```typescript import { BunCache } from "@nds-stack/bun-cache"; interface User { name: string; role: string } const cache = new BunCache(); cache.set("user:1", { name: "Alice", role: "admin" }); cache.set("temp", { name: "Bob", role: "guest" }, 5); // expires in 5 ms const user = cache.get("user:1"); console.log(user?.name); // "Alice" console.log(user?.role); // "admin" const missing = cache.get("user:99"); console.log(missing); // undefined await Bun.sleep(10); const expired = cache.get("temp"); console.log(expired); // undefined (expired, entry removed) ``` ``` -------------------------------- ### Get remaining TTL for a cache entry Source: https://context7.com/nds-stack/bun-cache/llms.txt The `remainingTTL(key)` method returns the time-to-live in milliseconds. It returns -1 if the key is missing, expired, or has no TTL. Expired entries are not removed and statistics are not affected. ```typescript import { BunCache } from "@nds-stack/bun-cache"; const cache = new BunCache(); cache.set("short", "value", 500); // 500 ms TTL cache.set("forever", "value"); // no TTL const remaining = cache.remainingTTL("short"); console.log(remaining > 0); // true console.log(remaining <= 500); // true console.log(cache.remainingTTL("forever")); // -1 (no TTL) console.log(cache.remainingTTL("ghost")); // -1 (missing) await Bun.sleep(510); console.log(cache.remainingTTL("short")); // -1 (expired) ``` -------------------------------- ### Get current cache size Source: https://context7.com/nds-stack/bun-cache/llms.txt The read-only `size` property returns the number of entries currently in the cache. This count includes entries that may have expired but have not yet been removed. ```typescript import { BunCache } from "@nds-stack/bun-cache"; const cache = new BunCache({ maxKeys: 5 }); console.log(cache.size); // 0 for (let i = 0; i < 5; i++) cache.set(`k${i}`, i); console.log(cache.size); // 5 cache.set("k5", 5); // triggers LRU eviction of oldest key console.log(cache.size); // 5 (still 5: one evicted, one added) cache.delete("k5"); console.log(cache.size); // 4 ``` -------------------------------- ### onExpire event handler Source: https://context7.com/nds-stack/bun-cache/llms.txt Allows registration of a callback function that is invoked when an entry is detected as expired during a `get` or `has` operation. The handler receives the expired key and its value. Errors within the handler are caught to maintain cache stability. Setting this to `null` removes the handler. ```APIDOC ## `onExpire` event handler Setter that registers a callback invoked whenever an entry is detected as expired during a `get` or `has` call. The handler receives the expired `key` and its `value`. Errors thrown inside the handler are silently caught to keep cache state consistent. Set to `null` to remove the handler. ```typescript import { BunCache } from "@nds-stack/bun-cache"; const cache = new BunCache(); const log: string[] = []; cache.onExpire = (key, value) => { log.push(`EXPIRED ${key}=${JSON.stringify(value)}`); }; cache.set("session:1", { userId: 42 }, 10); cache.set("session:2", { userId: 99 }, 10); await Bun.sleep(15); cache.get("session:1"); // triggers onExpire cache.has("session:2"); // triggers onExpire console.log(log); // ["EXPIRED session:1={\"userId\":42}", "EXPIRED session:2={\"userId\":99}"] // Remove the handler cache.onExpire = null; ``` ``` -------------------------------- ### Get Typed Cache Value Source: https://context7.com/nds-stack/bun-cache/llms.txt Retrieve a value by key, with optional generic typing for type safety. Returns undefined for non-existent or expired keys, triggering lazy expiration cleanup. ```typescript import { BunCache } from "@nds-stack/bun-cache"; interface User { name: string; role: string } const cache = new BunCache(); cache.set("user:1", { name: "Alice", role: "admin" }); cache.set("temp", { name: "Bob", role: "guest" }, 5); // expires in 5 ms const user = cache.get("user:1"); console.log(user?.name); // "Alice" console.log(user?.role); // "admin" const missing = cache.get("user:99"); console.log(missing); // undefined await Bun.sleep(10); const expired = cache.get("temp"); console.log(expired); // undefined (expired, entry removed) ``` -------------------------------- ### Register an onExpire event handler Source: https://context7.com/nds-stack/bun-cache/llms.txt The `onExpire` setter registers a callback that is invoked when an entry is found to be expired during a `get` or `has` operation. The handler receives the expired key and its value. Errors within the handler are caught silently. Set to `null` to remove the handler. ```typescript import { BunCache } from "@nds-stack/bun-cache"; const cache = new BunCache(); const log: string[] = []; cache.onExpire = (key, value) => { log.push(`EXPIRED ${key}=${JSON.stringify(value)}`); }; cache.set("session:1", { userId: 42 }, 10); cache.set("session:2", { userId: 99 }, 10); await Bun.sleep(15); cache.get("session:1"); // triggers onExpire cache.has("session:2"); // triggers onExpire console.log(log); // ["EXPIRED session:1={\"userId\":42}", "EXPIRED session:2={\"userId\":99}"] // Remove the handler cache.onExpire = null; ``` -------------------------------- ### Constructor: new BunCache(options?) Source: https://context7.com/nds-stack/bun-cache/llms.txt Creates a new cache instance. Options include `maxKeys` for LRU eviction limit and `defaultTTL` for entry expiration in milliseconds. ```APIDOC ## Constructor: `new BunCache(options?)` Creates a new cache instance. `maxKeys` sets the maximum number of entries before LRU eviction kicks in (`0` disables the limit). `defaultTTL` sets the default time-to-live in milliseconds for all keys that do not specify their own TTL (`0` means no expiry). ```typescript import { BunCache } from "@nds-stack/bun-cache"; // Default: 1000 max keys, no TTL const cache = new BunCache(); // Custom limits: 500 entries, 5-minute default TTL const sessionCache = new BunCache({ maxKeys: 500, defaultTTL: 5 * 60 * 1000 }); // Unlimited entries, no default TTL const unlimitedCache = new BunCache({ maxKeys: 0 }); console.log(cache.size); // 0 console.log(sessionCache.size); // 0 ``` ``` -------------------------------- ### BunCache with TTL and LRU Source: https://github.com/nds-stack/bun-cache/blob/main/README.md Demonstrates setting up a BunCache with both maximum key count (LRU) and default time-to-live (TTL). It shows how expiration and eviction events are handled. ```typescript import { BunCache } from "@nds-stack/bun-cache"; const cache = new BunCache({ maxKeys: 3, defaultTTL: 5000 }); cache.onExpire = (key, value) => console.log(`expired: ${key}=${value}`); cache.onEvict = (key, value, reason) => console.log(`evicted: ${key}=${value} (${reason})`); cache.set("a", 1); // TTL: 5s cache.set("b", 2); // TTL: 5s cache.set("c", 3); // TTL: 5s cache.set("d", 4); // maxKeys=3 exceeded → onEvict("a", 1, "lru") // After 5 seconds... cache.get("b"); // → undefined, onExpire("b", 2) fires cache.has("c"); // → false, onExpire("c", 3) fires // Stats after all operations: console.log(cache.stats); // { size: 1, hits: 0, misses: 2, evictions: 1, expirations: 2 } ``` -------------------------------- ### BunCache Constructor Source: https://github.com/nds-stack/bun-cache/blob/main/README.md Initializes a new BunCache instance with optional configuration for maximum keys and default time-to-live (TTL). ```APIDOC ## Constructor ```typescript new BunCache(options?: BunCacheOptions) ``` ### Description Initializes a new BunCache instance. ### Parameters #### Options - **maxKeys** (`number`) - Optional - Maximum entries before LRU eviction. `0` means unlimited. - **defaultTTL** (`number`) - Optional - Default TTL in milliseconds (`0` means no expiry). ``` -------------------------------- ### Local Cache + SQLite (via bunql) Source: https://github.com/nds-stack/bun-cache/blob/main/README.md Utilizes BunCache locally with bunql (SQLite) as a shared persistence layer. This provides cross-instance durability for process-local caching. ```typescript import { BunCache } from "@nds-stack/bun-cache"; // import { db } from "@nds-stack/bunql"; const local = new BunCache({ maxKeys: 1000, defaultTTL: 30_000 }); async function getSettings(key: string): Promise { const cached = local.get(`settings:${key}`); if (cached) return cached; const row = db.query( "SELECT value FROM settings WHERE key = ?", [key] ); if (row.rows.length > 0) { local.set(`settings:${key}`, row.rows[0], 30_000); return row.rows[0]; } return null; } ``` -------------------------------- ### Create BunCache Instance Source: https://context7.com/nds-stack/bun-cache/llms.txt Instantiate BunCache with default or custom options for max keys and default TTL. Max keys of 0 disables LRU eviction. ```typescript import { BunCache } from "@nds-stack/bun-cache"; // Default: 1000 max keys, no TTL const cache = new BunCache(); // Custom limits: 500 entries, 5-minute default TTL const sessionCache = new BunCache({ maxKeys: 500, defaultTTL: 5 * 60 * 1000 }); // Unlimited entries, no default TTL const unlimitedCache = new BunCache({ maxKeys: 0 }); console.log(cache.size); // 0 console.log(sessionCache.size); // 0 ``` -------------------------------- ### keys(), values(), entries() Source: https://context7.com/nds-stack/bun-cache/llms.txt Provides methods to inspect the cache contents. `keys()` returns all keys, `values()` returns all values cast to type `T`, and `entries()` returns an array of `{ key, value }` objects. These methods return snapshots and do not interact with TTL or statistics. ```APIDOC ## `keys()`, `values()`, `entries()` Inspection methods that return snapshots of current cache contents. `keys()` returns all string keys. `values()` returns all stored values cast to `T`. `entries()` returns an array of `{ key, value }` objects. None of these methods check TTL or affect statistics — expired entries that haven't been accessed yet will still appear. ```typescript import { BunCache } from "@nds-stack/bun-cache"; interface Product { name: string; price: number } const cache = new BunCache(); cache.set("prod:1", { name: "Widget", price: 9.99 }); cache.set("prod:2", { name: "Gadget", price: 24.99 }); cache.set("prod:3", { name: "Doohickey", price: 4.49 }); console.log(cache.keys()); // ["prod:1", "prod:2", "prod:3"] const prices = cache.values().map((p) => p.price); console.log(prices); // [9.99, 24.99, 4.49] const entries = cache.entries(); entries.forEach(({ key, value }) => { console.log(`${key}: ${value.name} @ $${value.price}`); }); // prod:1: Widget @ $9.99 // prod:2: Gadget @ $24.99 // prod:3: Doohickey @ $4.49 ``` ``` -------------------------------- ### set(key, value, ttl?) Source: https://context7.com/nds-stack/bun-cache/llms.txt Stores a value under a key with an optional TTL. If the cache is at capacity, LRU eviction occurs. Setting an existing key updates its value and resets its TTL. ```APIDOC ## `set(key, value, ttl?)` Stores a value under `key`. The optional `ttl` argument (milliseconds) overrides `defaultTTL` for this specific entry. If the cache is at capacity and the key is new, the least-recently-used entry is evicted first. Setting an existing key updates its value and resets its TTL without counting as a new entry for LRU purposes. ```typescript import { BunCache } from "@nds-stack/bun-cache"; const cache = new BunCache({ maxKeys: 3, defaultTTL: 60_000 }); // Store with default TTL (60 s from constructor) cache.set("user:1", { name: "Alice", role: "admin" }); // Store with per-key TTL override (10 s) cache.set("session:abc", { userId: 1, token: "xyz" }, 10_000); // Store with no expiry (TTL = 0 overrides defaultTTL) cache.set("config:theme", "dark", 0); // Overwrite an existing key cache.set("user:1", { name: "Alice", role: "superadmin" }); console.log(cache.size); // 3 ``` ``` -------------------------------- ### Inspect cache contents with keys(), values(), and entries() Source: https://context7.com/nds-stack/bun-cache/llms.txt These methods provide snapshots of the cache. `keys()` returns keys, `values()` returns values cast to type T, and `entries()` returns an array of { key, value } objects. Expired entries may still be included if not yet accessed. ```typescript import { BunCache } from "@nds-stack/bun-cache"; interface Product { name: string; price: number } const cache = new BunCache(); cache.set("prod:1", { name: "Widget", price: 9.99 }); cache.set("prod:2", { name: "Gadget", price: 24.99 }); cache.set("prod:3", { name: "Doohickey", price: 4.49 }); console.log(cache.keys()); // ["prod:1", "prod:2", "prod:3"] const prices = cache.values().map((p) => p.price); console.log(prices); // [9.99, 24.99, 4.49] const entries = cache.entries(); entries.forEach(({ key, value }) => { console.log(`${key}: ${value.name} @ $${value.price}`); }); // prod:1: Widget @ $9.99 // prod:2: Gadget @ $24.99 // prod:3: Doohickey @ $4.49 ``` -------------------------------- ### Local Cache + Shared Database (Read-Through) Source: https://github.com/nds-stack/bun-cache/blob/main/README.md Implements a read-through caching strategy using BunCache locally in front of a shared database. This reduces database load by caching frequently accessed data. ```typescript import { BunCache } from "@nds-stack/bun-cache"; // import { db } from "./db"; // bun:sqlite, Postgres, etc. const local = new BunCache({ maxKeys: 1000, defaultTTL: 60_000 }); async function getUser(id: string): Promise { // 1. Check local cache (fast, ~4.5M ops/s) const cached = local.get(`user:${id}`); if (cached) return cached; // 2. Miss — read from shared database const user = await db.query("SELECT * FROM users WHERE id = ?", [id]); // 3. Populate local cache for next read if (user) local.set(`user:${id}`, user, 60_000); return user; } async function updateUser(id: string, data: Partial): Promise { // 1. Write to shared database (source of truth) await db.run("UPDATE users SET ... WHERE id = ?", [id, ...data]); // 2. Invalidate local cache entry local.delete(`user:${id}`); } ``` -------------------------------- ### Local Cache + Redis (Cache-Aside with Invalidation) Source: https://github.com/nds-stack/bun-cache/blob/main/README.md Combines a local BunCache with Redis as a shared cache. This approach uses Redis pub/sub for invalidation signals to keep local caches synchronized across instances. ```typescript import { BunCache } from "@nds-stack/bun-cache"; // import { redis } from "./redis"; // ioredis or bun-redis const local = new BunCache({ maxKeys: 5000, defaultTTL: 120_000 }); async function getCached(key: string): Promise { // 1. Check local cache first const hit = local.get(key); if (hit !== undefined) return hit; // 2. Miss — check Redis const value = await redis.get(key); if (value !== null) { local.set(key, value, 120_000); // populate local } return value; } async function setCached(key: string, value: string): Promise { // 1. Write to Redis (shared) await redis.set(key, value, "EX", 3600); // 2. Update local cache local.set(key, value, 120_000); // 3. Publish invalidation to other instances await redis.publish("cache:invalidate", key); } // Subscribe to invalidation from other instances // redis.subscribe("cache:invalidate", (key) => local.delete(key)); ``` -------------------------------- ### Check Cache Entry Existence Source: https://context7.com/nds-stack/bun-cache/llms.txt Verify if a key exists and is not expired. This method also performs lazy TTL checks and removes expired entries without affecting statistics. ```typescript import { BunCache } from "@nds-stack/bun-cache"; const cache = new BunCache(); cache.set("active", true, 50); cache.set("permanent", true); console.log(cache.has("active")); // true console.log(cache.has("permanent")); // true console.log(cache.has("missing")); // false await Bun.sleep(60); console.log(cache.has("active")); // false (expired) console.log(cache.has("permanent")); // true (no TTL) ``` -------------------------------- ### BunCache Events Source: https://github.com/nds-stack/bun-cache/blob/main/README.md Defines events that are emitted by the cache for key expiration, eviction, and clearing operations. ```APIDOC ## Events ### `onExpire` - **Signature**: `(key: string, value: T) => void` - **Description**: Called when a key expires. This is detected lazily during `get()` or `has()` operations. ### `onEvict` - **Signature**: `(key: string, value: T, reason: "lru" | "manual") => void` - **Description**: Called when a key is evicted due to LRU policy or manually deleted. Increments the `stats.evictions` counter. ### `onClear` - **Signature**: `() => void` - **Description**: Called after the cache has been completely cleared using the `clear()` method. ``` -------------------------------- ### size (property) Source: https://context7.com/nds-stack/bun-cache/llms.txt A read-only getter that returns the current number of entries in the cache. This count includes entries that may have expired but have not yet been lazily removed. ```APIDOC ## `size` (property) Read-only getter that returns the current number of entries in the cache. Includes entries that may have logically expired but haven't been lazily removed yet. ```typescript import { BunCache } from "@nds-stack/bun-cache"; const cache = new BunCache({ maxKeys: 5 }); console.log(cache.size); // 0 for (let i = 0; i < 5; i++) cache.set(`k${i}`, i); console.log(cache.size); // 5 cache.set("k5", 5); // triggers LRU eviction of oldest key console.log(cache.size); // 5 (still 5: one evicted, one added) cache.delete("k5"); console.log(cache.size); // 4 ``` ``` -------------------------------- ### delete(key) Source: https://context7.com/nds-stack/bun-cache/llms.txt Removes an entry by key. Returns `true` if the key was found and removed, `false` otherwise. Triggers the `onEvict` event. ```APIDOC ## `delete(key)` Removes a single entry by key. Returns `true` if the key existed and was removed, `false` if the key was not found. Triggers the `onEvict` event handler with reason `"manual"`. ```typescript import { BunCache } from "@nds-stack/bun-cache"; const cache = new BunCache(); cache.set("token:user1", "jwt.abc.xyz"); cache.set("token:user2", "jwt.def.uvw"); const removed = cache.delete("token:user1"); console.log(removed); // true console.log(cache.get("token:user1")); // undefined console.log(cache.delete("token:user1")); // false (already gone) console.log(cache.size); // 1 ``` ``` -------------------------------- ### clear() Source: https://context7.com/nds-stack/bun-cache/llms.txt Removes all entries from the cache and resets all statistics counters to zero. This operation also triggers the `onClear` event handler. ```APIDOC ## `clear()` Removes all entries and resets all statistics counters (`hits`, `misses`, `evictions`, `expirations`) to zero. Triggers the `onClear` event handler after clearing. ```typescript import { BunCache } from "@nds-stack/bun-cache"; const cache = new BunCache(); cache.set("a", 1); cache.set("b", 2); cache.get("a"); // hit cache.get("z"); // miss console.log(cache.stats.hits); // 1 console.log(cache.stats.misses); // 1 console.log(cache.size); // 2 cache.clear(); console.log(cache.size); // 0 console.log(cache.stats.hits); // 0 (reset) console.log(cache.stats.misses); // 0 (reset) ``` ``` -------------------------------- ### Register onClear Handler for BunCache Source: https://context7.com/nds-stack/bun-cache/llms.txt Register a callback to be invoked after the clear() method removes all entries. The handler is called even if the cache is already empty. To remove the handler, set it to null. ```typescript import { BunCache } from "@nds-stack/bun-cache"; const cache = new BunCache(); let clearCount = 0; cache.onClear = () => { clearCount++; }; cache.set("a", 1); cache.set("b", 2); cache.clear(); cache.clear(); // called even on already-empty cache console.log(clearCount); // 2 cache.onClear = null; // remove handler cache.clear(); console.log(clearCount); // still 2 ``` -------------------------------- ### stats (property) Source: https://context7.com/nds-stack/bun-cache/llms.txt A read-only getter that provides a snapshot of cache statistics, including hit and miss counts, hit rate, eviction count, and expiration count. These statistics are reset to zero when the `clear()` method is called. ```APIDOC ## `stats` (property) Read-only getter that returns a `CacheStats` snapshot with hit/miss counts, hit rate, eviction count, and expiration count. Stats are reset to zero by `clear()`. ```typescript import { BunCache } from "@nds-stack/bun-cache"; const cache = new BunCache({ maxKeys: 2 }); cache.set("a", 1); cache.set("b", 2); cache.set("c", 3); // evicts "a" (LRU) cache.get("b"); // hit cache.get("c"); // hit cache.get("a"); // miss (was evicted) cache.get("x"); // miss (never existed) const stats = cache.stats; console.log(stats.hits); // 2 console.log(stats.misses); // 2 console.log(stats.hitRate); // 0.5 console.log(stats.evictions); // 1 console.log(stats.size); // 2 ``` ``` -------------------------------- ### Clear BunCache entries and reset statistics Source: https://context7.com/nds-stack/bun-cache/llms.txt Use `clear()` to remove all entries and reset hit, miss, eviction, and expiration counters. This method also triggers the `onClear` event handler. ```typescript import { BunCache } from "@nds-stack/bun-cache"; const cache = new BunCache(); cache.set("a", 1); cache.set("b", 2); cache.get("a"); // hit cache.get("z"); // miss console.log(cache.stats.hits); // 1 console.log(cache.stats.misses); // 1 console.log(cache.size); // 2 cache.clear(); console.log(cache.size); // 0 console.log(cache.stats.hits); // 0 (reset) console.log(cache.stats.misses); // 0 (reset) ``` -------------------------------- ### Register onEvict Handler for BunCache Source: https://context7.com/nds-stack/bun-cache/llms.txt Register a callback to be invoked when an entry is removed from the cache due to LRU eviction or manual deletion. Errors within the handler are silently caught. ```typescript import { BunCache } from "@nds-stack/bun-cache"; const evictions: Array<{ key: string; reason: "lru" | "manual" }> = []; const cache = new BunCache({ maxKeys: 2 }); cache.onEvict = (key, _value, reason) => { evictions.push({ key, reason }); }; cache.set("x", 1); cache.set("y", 2); cache.set("z", 3); // LRU evicts "x" cache.delete("y"); // manual eviction console.log(evictions); // [{ key: "x", reason: "lru" }, { key: "y", reason: "manual" }] ``` -------------------------------- ### has(key) Source: https://context7.com/nds-stack/bun-cache/llms.txt Checks if a key exists and has not expired. Performs a lazy TTL check and removes expired entries without affecting statistics. ```APIDOC ## `has(key)` Checks whether `key` exists and has not expired. Like `get`, it performs a lazy TTL check and removes the entry if expired. Does not affect hit/miss statistics. ```typescript import { BunCache } from "@nds-stack/bun-cache"; const cache = new BunCache(); cache.set("active", true, 50); cache.set("permanent", true); console.log(cache.has("active")); // true console.log(cache.has("permanent")); // true console.log(cache.has("missing")); // false await Bun.sleep(60); console.log(cache.has("active")); // false (expired) console.log(cache.has("permanent")); // true (no TTL) ``` ``` -------------------------------- ### Set Cache Entry with TTL Source: https://context7.com/nds-stack/bun-cache/llms.txt Store values with a default TTL or override it per key. Existing keys are updated without affecting LRU order. Setting TTL to 0 disables expiry for that entry. ```typescript import { BunCache } from "@nds-stack/bun-cache"; const cache = new BunCache({ maxKeys: 3, defaultTTL: 60_000 }); // Store with default TTL (60 s from constructor) cache.set("user:1", { name: "Alice", role: "admin" }); // Store with per-key TTL override (10 s) cache.set("session:abc", { userId: 1, token: "xyz" }, 10_000); // Store with no expiry (TTL = 0 overrides defaultTTL) cache.set("config:theme", "dark", 0); // Overwrite an existing key cache.set("user:1", { name: "Alice", role: "superadmin" }); console.log(cache.size); // 3 ``` -------------------------------- ### remainingTTL(key) Source: https://context7.com/nds-stack/bun-cache/llms.txt Retrieves the remaining time-to-live (TTL) for a given cache key in milliseconds. Returns -1 if the key is not found, has expired, or was set without a TTL. This method does not affect cache statistics. ```APIDOC ## `remainingTTL(key)` Returns the remaining time-to-live of an entry in milliseconds. Returns `-1` if the key does not exist, has already expired, or was set without a TTL. Does not remove expired entries or affect statistics. ```typescript import { BunCache } from "@nds-stack/bun-cache"; const cache = new BunCache(); cache.set("short", "value", 500); // 500 ms TTL cache.set("forever", "value"); // no TTL const remaining = cache.remainingTTL("short"); console.log(remaining > 0); // true console.log(remaining <= 500); // true console.log(cache.remainingTTL("forever")); // -1 (no TTL) console.log(cache.remainingTTL("ghost")); // -1 (missing) await Bun.sleep(510); console.log(cache.remainingTTL("short")); // -1 (expired) ``` ``` -------------------------------- ### Access cache statistics Source: https://context7.com/nds-stack/bun-cache/llms.txt The read-only `stats` property provides a snapshot of cache performance metrics, including hits, misses, hit rate, evictions, and expiration counts. These statistics are reset to zero when `clear()` is called. ```typescript import { BunCache } from "@nds-stack/bun-cache"; const cache = new BunCache({ maxKeys: 2 }); cache.set("a", 1); cache.set("b", 2); cache.set("c", 3); // evicts "a" (LRU) cache.get("b"); // hit cache.get("c"); // hit cache.get("a"); // miss (was evicted) cache.get("x"); // miss (never existed) const stats = cache.stats; console.log(stats.hits); // 2 console.log(stats.misses); // 2 console.log(stats.hitRate); // 0.5 console.log(stats.evictions); // 1 console.log(stats.size); // 2 ``` -------------------------------- ### Delete Cache Entry Source: https://context7.com/nds-stack/bun-cache/llms.txt Remove a specific entry by key. Returns true if the entry was found and removed, false otherwise. This action triggers the 'onEvict' event with a 'manual' reason. ```typescript import { BunCache } from "@nds-stack/bun-cache"; const cache = new BunCache(); cache.set("token:user1", "jwt.abc.xyz"); cache.set("token:user2", "jwt.def.uvw"); const removed = cache.delete("token:user1"); console.log(removed); // true console.log(cache.get("token:user1")); // undefined console.log(cache.delete("token:user1")); // false (already gone) console.log(cache.size); // 1 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.