import { DurationObj } from "./time.mjs"; //#region src/cache.d.ts /** * Creates a cached getter that only calls the provided function once. The first * access computes and caches the value; subsequent accesses return the cached * result. This is useful for lazy initialization of expensive computations. * * @example * const expensive = cachedGetter(() => { * console.log('Computing...'); * return heavyComputation(); * }); * * console.log(expensive.value); // Logs "Computing..." and returns result * console.log(expensive.value); // Returns cached result without logging * console.log(expensive.value); // Returns cached result without logging * * @param getter - Function that computes the value to cache * @returns Object with a `value` property that caches the result */ declare function cachedGetter(getter: () => T): { value: T; }; type Options = { /** * The maximum number of items in the cache. * * @default 1000 */ maxCacheSize?: number; /** The maximum age of items in the cache. */ maxItemAge?: DurationObj; /** * The throttle for checking expired items in milliseconds. * * @default * 10_000 */ expirationThrottle?: number; }; /** * Wrapper class that prevents a value from being cached. When returned from a * cache computation function, the value will be returned to the caller but not * stored in the cache. * * @example * const cache = createCache(); * const result = cache.getOrInsert('dynamic', ({ skipCaching }) => { * const data = generateData(); * if (data.isTemporary) { * return skipCaching(data); // Won't be cached * } * return data; // Will be cached * }); */ declare class SkipCaching { value: T; constructor(value: T); } /** * Wrapper class that sets a custom expiration time for a cached value. Allows * individual cache entries to have different expiration times than the default * cache expiration. * * @example * const cache = createCache({ maxItemAge: { hours: 1 } }); // Default 1 hour * * const result = cache.getOrInsert('short-lived', ({ withExpiration }) => { * return withExpiration('temporary data', { minutes: 5 }); // Expires in 5 minutes * }); * * const longLived = cache.getOrInsert( * 'long-lived', * ({ withExpiration }) => { * return withExpiration('persistent data', { days: 1 }); // Expires in 1 day * }, * ); */ declare class WithExpiration { value: T; expiration: number; /** * @param value - The value to store in the cache. * @param expiration - The expiration time of the value in seconds or a * duration object. */ constructor(value: T, expiration: DurationObj); } type Utils = { skipCaching: (value: T) => SkipCaching; /** * Create a new WithExpiration object with the given value and expiration * time. * * @param value - The value to store in the cache. * @param expiration - The expiration time of the value in seconds or a * duration object. */ withExpiration: (value: T, expiration: DurationObj) => WithExpiration; }; type GetOptions = { /** * A function that determines whether a value should be rejected from being * cached. If the function returns true, the value will be returned but not * cached. * * @param value The value to check * @returns True if the value should be rejected, false otherwise */ skipCachingWhen?: (value: T) => boolean; }; type Cache = { getOrInsert: (cacheKey: string, val: (utils: Utils) => T | SkipCaching, options?: GetOptions) => T; getOrInsertAsync: (cacheKey: string, val: (utils: Utils) => Promise>, options?: GetOptions) => Promise; clear: () => void; delete: (...cacheKeys: string[]) => void; has: (cacheKey: string) => boolean; size: number; get: (cacheKey: string) => T | undefined; set: (cacheKey: string, value: T | WithExpiration) => void; cleanExpiredItems: () => void; getAsync: (cacheKey: string) => Promise; setAsync: (cacheKey: string, value: (utils: Utils) => Promise>) => Promise; clone: () => Cache; [' cache']: { map: Map; timestamp: number; }>; }; }; /** * Creates a full-featured cache with time-based expiration, async support, and * advanced features. This is a more powerful alternative to `fastCache` when * you need expiration, async operations, or advanced caching strategies. * * @example * // Basic usage with expiration * const cache = createCache({ * maxCacheSize: 100, * maxItemAge: { minutes: 5 }, * }); * * // Simple caching * const result = cache.getOrInsert('user:123', () => { * return fetchUserFromDatabase('123'); * }); * * // Async caching with promise deduplication * const asyncResult = await cache.getOrInsertAsync( * 'api:data', * async () => { * return await fetchFromApi('/data'); * }, * ); * * // Skip caching for certain values * const value = cache.getOrInsert('dynamic', ({ skipCaching }) => { * const data = generateDynamicData(); * if (data.shouldNotCache) { * return skipCaching(data); // Won't be cached * } * return data; * }); * * // Custom expiration per item * const shortLivedValue = cache.getOrInsert( * 'temp', * ({ withExpiration }) => { * return withExpiration('temporary data', { seconds: 30 }); * }, * ); * * // Conditional caching based on the computed value * const result = cache.getOrInsert( * 'conditional', * () => { * return computeValue(); * }, * { * skipCachingWhen: (value) => value === null || value.error, * }, * ); * * @param cacheOptions - Configuration options for the cache * @param cacheOptions.maxCacheSize - Maximum number of items to store. When * exceeded, oldest items are removed first. Defaults to 1000. * @param cacheOptions.maxItemAge - Default expiration time for all cached items. * Items older than this will be automatically removed. * @param cacheOptions.expirationThrottle - Minimum time in milliseconds between * expiration cleanup runs. Prevents excessive cleanup operations. Defaults to * 10,000ms. * @returns A cache instance with various methods for storing and retrieving * values */ declare function createCache(cacheOptions?: Options): Cache; type FastCacheOptions = { maxCacheSize?: number; }; /** * Creates a simple, fast cache with FIFO (First In, First Out) eviction policy. * This is a lightweight alternative to `createCache` for basic caching needs * without expiration, async support, or advanced features. * * @example * const cache = fastCache({ maxCacheSize: 100 }); * * // Cache expensive computation * const result = cache.getOrInsert('user:123', () => { * return fetchUserFromDatabase('123'); * }); * * // Subsequent calls return cached value without re-computation * const cachedResult = cache.getOrInsert('user:123', () => { * return fetchUserFromDatabase('123'); // Won't be called * }); * * // Clear all cached values * cache.clear(); * * @param fastCacheOptions - Configuration options for the cache * @param fastCacheOptions.maxCacheSize - Maximum number of items to store in the cache. * When exceeded, oldest items are removed first. Defaults to 1000. * @returns An object with cache methods */ declare function fastCache(fastCacheOptions?: FastCacheOptions): { getOrInsert: (cacheKey: string, val: () => T) => T; /** Clears all cached values */ clear: () => void; /** * Removes one or more items from the cache. * * @param cacheKeys - Keys of the items to remove */ delete: (...cacheKeys: string[]) => void; /** * Checks whether an item exists for the given key. * * @param cacheKey - Key to check * @returns True if the entry exists */ has: (cacheKey: string) => boolean; /** * Gets a value from the cache without computing it if missing. * * @param cacheKey - Key to look up in the cache * @returns The cached value or undefined if not found */ get: (cacheKey: string) => T | undefined; /** The number of items currently in the cache. */ readonly size: number; /** Creates an independent copy of this cache with the same options. */ clone(): { getOrInsert: (cacheKey: string, val: () => T) => T; /** Clears all cached values */ clear: () => void; /** * Removes one or more items from the cache. * * @param cacheKeys - Keys of the items to remove */ delete: (...cacheKeys: string[]) => void; /** * Checks whether an item exists for the given key. * * @param cacheKey - Key to check * @returns True if the entry exists */ has: (cacheKey: string) => boolean; /** * Gets a value from the cache without computing it if missing. * * @param cacheKey - Key to look up in the cache * @returns The cached value or undefined if not found */ get: (cacheKey: string) => T | undefined; /** The number of items currently in the cache. */ readonly size: number; clone(): /*elided*/any; /** @internal */ " cache": Map; }; /** @internal */ " cache": Map; }; //#endregion export { Cache, SkipCaching, WithExpiration, cachedGetter, createCache, fastCache };