import { DotPath, DotPathValue } from "@arkstack/common"; //#region src/Contracts/Store.d.ts /** * The low level contract every cache store driver must satisfy. * * Stores are intentionally thin: they only deal in raw key/value persistence * and expiration. The higher level convenience API (`remember`, `add`, `pull`, * default value resolution, etc.) lives in {@link Repository}, which wraps a * store. This keeps drivers simple and behaviour consistent across backends. */ declare abstract class Store { /** * Retrieve the value for the given key, or `null` when the key is missing * or has expired. * * @param key */ abstract get(key: string): Promise; /** * Store a value for the given key. * * @param key The cache key. * @param value The value to store (will be serialized by the driver). * @param seconds Lifetime in seconds, or `null` to store forever. * @returns Whether the value was stored. */ abstract put(key: string, value: unknown, seconds?: number | null): Promise; /** * Store a value that never expires. * * @param key * @param value */ abstract forever(key: string, value: unknown): Promise; /** * Increment a numeric value, creating it (starting at 0) when absent. * * @returns The new value, or `false` when the existing value is not numeric. * * @param key * @param value */ abstract increment(key: string, value?: number): Promise; /** * Decrement a numeric value, creating it (starting at 0) when absent. * * @returns The new value, or `false` when the existing value is not numeric. * * @param key * @param value */ abstract decrement(key: string, value?: number): Promise; /** * Remove a single key from the store. * * @param key * @param value */ abstract forget(key: string): Promise; /** * Remove every entry owned by this store. */ abstract flush(): Promise; /** * The key prefix applied to every entry by this store. */ abstract getPrefix(): string; } //#endregion //#region src/types.d.ts /** * A value, or a function (sync or async) that resolves to a value. * * Used for cache defaults and the `remember` callbacks. */ type Resolvable = T | (() => T | Promise); /** * Time to live for a cache entry. * * - `number` number of seconds the entry should live. * - `Date` an absolute expiry time. * - `null` store forever (no expiration). */ type CacheTtl = number | Date | null; /** * Built in cache store driver names. */ type CacheDriverName = 'memory' | 'array' | 'file' | 'redis' | 'database'; interface FilePayload { value: unknown; /** Absolute expiry in epoch milliseconds, or `null` for forever. */ expiresAt: number | null; } interface MemoryStoreConfig { driver: 'memory' | 'array'; } interface FileStoreConfig { driver: 'file'; /** Absolute path to the directory cache files are written to. */ path: string; } interface RedisStoreConfig { driver: 'redis'; /** A pre built ioredis connection string, e.g. `redis://localhost:6379`. */ url?: string; host?: string; port?: number; password?: string; db?: number; /** Optional per store key prefix applied on top of the global prefix. */ prefix?: string; } interface DatabaseStoreConfig { driver: 'database'; /** The table the cache entries are stored in. */ table: string; /** Optional named database connection. */ connection?: string; } /** * Apps may augment this registry to register custom store driver configs. */ interface CustomCacheStoreRegistry {} type CacheStoreConfig = MemoryStoreConfig | FileStoreConfig | RedisStoreConfig | DatabaseStoreConfig | ({ driver: string; } & Record); interface CacheConfig { /** * The default cache store used when no store is explicitly requested. */ default: string; /** * A string prepended to every cache key to avoid collisions between * applications sharing the same backing store. */ prefix: string; /** * The configured cache stores. Each entry is keyed by the name used with * `Cache.store('')`. */ stores: Record & CustomCacheStoreRegistry; } /** * Signature for a custom store factory registered via `Cache.extend`. */ type CacheStoreFactory = (config: CacheStoreConfig) => Store; interface MemoryEntry { value: unknown; /** Absolute expiry in epoch milliseconds, or `null` for forever. */ expiresAt: number | null; } interface CacheRow { key: string; value: string; /** Absolute expiry in epoch seconds, or `null` for forever. */ expiration: number | null; } /** * Structural type for the `DB` class exported by `@arkstack/database`, declared * locally so the cache package does not depend on it at build time (it is an * optional peer dependency). */ interface DatabaseFacade { table(table: string): { where(where: Record): { first(): Promise; delete(): Promise; }; updateOrInsert(attributes: Record, values: Record): Promise; delete(): Promise; }; } /** * Minimal structural type for the slice of the ioredis client we use. Declared * locally so the package does not need ioredis types at build time (it is an * optional peer dependency). */ interface RedisClient { get(key: string): Promise; set(key: string, value: string): Promise; set(key: string, value: string, mode: 'EX', seconds: number): Promise; del(...keys: string[]): Promise; incrby(key: string, value: number): Promise; decrby(key: string, value: number): Promise; scan(cursor: string, match: 'MATCH', pattern: string, count: 'COUNT', n: number): Promise<[string, string[]]>; quit(): Promise; } //#endregion //#region src/Repository.d.ts /** * Normalize a {@link CacheTtl} into a whole number of seconds, or `null` for a * forever entry. A non positive duration is treated as already expired and * returns `0`, signalling the caller to skip writing. */ declare const ttlToSeconds: (ttl: CacheTtl) => number | null; /** * A high level wrapper around a {@link Store} that provides the developer facing * cache API. A repository is what `Cache.store()` returns. */ declare class Repository { protected readonly store: Store; constructor(store: Store); /** * Get the underlying store driver. */ getStore(): Store; /** * Determine whether an item exists in the cache and has not expired. * * @param key * @returns */ has(key: string): Promise; /** * Determine whether an item is missing from the cache. * * @param key * @returns */ missing(key: string): Promise; /** * Retrieve an item from the cache, falling back to `defaultValue` (which may * be a callback) when the item is absent. * * @param key * @returns */ get(key: string, defaultValue?: Resolvable): Promise; /** * Retrieve an item and delete it from the cache in a single call. * * @param key * @param defaultValue * @returns */ pull(key: string, defaultValue?: Resolvable): Promise; /** * Store an item in the cache. A `null`/omitted ttl stores the item forever; * a non positive ttl is a no-op that also forgets any existing entry. * * @param key * @param defaultValue * @returns */ put(key: string, value: unknown, ttl?: CacheTtl): Promise; /** * Alias for {@link put}. * * @param key * @param defaultValue * @returns */ set(key: string, value: unknown, ttl?: CacheTtl): Promise; /** * Store an item only if it is not already present. Returns `false` when the * key already exists. * * @param key * @param defaultValue * @returns */ add(key: string, value: unknown, ttl?: CacheTtl): Promise; /** * Store an item that never expires. * * @param key * @param defaultValue * @returns */ forever(key: string, value: unknown): Promise; /** * Increment a stored numeric value. * * @param key * @param defaultValue * @returns */ increment(key: string, value?: number): Promise; /** * Decrement a stored numeric value. * * @param key * @param defaultValue * @returns */ decrement(key: string, value?: number): Promise; /** * Get an item from the cache, or execute the callback, store its result for * the given ttl, and return it. * * @param key * @param defaultValue * @returns */ remember(key: string, ttl: CacheTtl, callback: () => T | Promise): Promise; /** * Get an item from the cache, or execute the callback and store its result * forever. * * @param key * @param defaultValue * @returns */ rememberForever(key: string, callback: () => T | Promise): Promise; /** * Alias for {@link rememberForever}. * * @param key * @param callback * @returns */ sear(key: string, callback: () => T | Promise): Promise; /** * Remove an item from the cache. * * @param key * @param callback * @returns */ forget(key: string): Promise; /** * Alias for {@link forget}. * * @param key * @param callback * @returns */ delete(key: string): Promise; /** * Remove every item from the cache store. * * @param key * @param callback * @returns */ flush(): Promise; /** * Alias for {@link flush}. * * @param key * @param callback * @returns */ clear(): Promise; } //#endregion //#region src/CacheManager.d.ts /** * The cache manager and primary entry point of `@arkstack/cache`. * * Resolves named cache stores from configuration, memoizes the resulting * repositories, and exposes static convenience methods that proxy the default * store, e.g.: * * ```ts * await Cache.put('user:1', user, 60) * await Cache.store('redis').remember('stats', 300, computeStats) * ``` */ declare class Cache { private static repositories; private static customDrivers; /** * Resolve a cache repository for the given store name (or the default store * when omitted). Repositories are memoized per name. */ static store(name?: string): Repository; /** * Alias for {@link store}. */ static driver(name?: string): Repository; /** * Register a custom store driver factory, used when a store's `driver` does * not match a built in one. */ static extend(driver: string, factory: CacheStoreFactory): typeof Cache; /** * Clear the memoized repositories. Mainly useful between tests or after the * configuration changes at runtime. */ static clearResolved(): void; /** * Build a repository for a configured store from scratch. */ private static resolve; /** * Instantiate the concrete {@link Store} for a store config. */ private static createStore; static has(key: string): Promise; static missing(key: string): Promise; static get(key: string, defaultValue?: Resolvable): Promise; static pull(key: string, defaultValue?: Resolvable): Promise; static put(key: string, value: unknown, ttl?: CacheTtl): Promise; static set(key: string, value: unknown, ttl?: CacheTtl): Promise; static add(key: string, value: unknown, ttl?: CacheTtl): Promise; static forever(key: string, value: unknown): Promise; static increment(key: string, value?: number): Promise; static decrement(key: string, value?: number): Promise; static remember(key: string, ttl: CacheTtl, callback: () => T | Promise): Promise; static rememberForever(key: string, callback: () => T | Promise): Promise; static forget(key: string): Promise; static delete(key: string): Promise; static flush(): Promise; static clear(): Promise; } //#endregion //#region src/config.d.ts /** * Read a value from the `cache` configuration namespace with a fallback. * * Mirrors the framework `config()` helper but is scoped to the cache config and * never throws when the config file is missing, returning the default instead. * * @param key Dot path within the cache config. * @param defaultValue Value returned when the key is not set. */ declare const configure: >(key: T, defaultValue: unknown) => DotPathValue; //#endregion //#region src/drivers/MemoryStore.d.ts /** * An in-process cache store backed by a `Map`. * * The backing map is shared across every `MemoryStore` instance that uses the * same prefix, so resolving the store twice within a process sees the same data * (matching how the other backends behave). Great for development and tests; it * is not shared across processes. */ declare class MemoryStore extends Store { private readonly prefix; private static stores; private readonly entries; constructor(prefix?: string); getPrefix(): string; get(key: string): Promise; put(key: string, value: unknown, seconds?: number | null): Promise; forever(key: string, value: unknown): Promise; increment(key: string, value?: number): Promise; decrement(key: string, value?: number): Promise; forget(key: string): Promise; flush(): Promise; } //#endregion //#region src/drivers/FileStore.d.ts /** * A cache store that persists each entry as a JSON file on disk. * * Keys are hashed to produce safe, fixed length file names. Expired files are * removed lazily on read and ignored otherwise. */ declare class FileStore extends Store { private readonly directory; private readonly prefix; constructor(directory: string, prefix?: string); getPrefix(): string; private pathFor; private ensureDirectory; get(key: string): Promise; put(key: string, value: unknown, seconds?: number | null): Promise; forever(key: string, value: unknown): Promise; increment(key: string, value?: number): Promise; decrement(key: string, value?: number): Promise; forget(key: string): Promise; flush(): Promise; } //#endregion //#region src/drivers/RedisStore.d.ts /** * A Redis backed cache store using an ioredis compatible client. * * Values are JSON serialized. Numeric helpers use native `INCRBY`/`DECRBY` so * counters stay atomic across processes. `ioredis` is an optional peer * dependency; it is imported lazily so applications that never use the redis * store don't need it installed. */ declare class RedisStore extends Store { private readonly redisConfig; private readonly prefix; private client?; constructor(redisConfig: RedisStoreConfig, prefix?: string); getPrefix(): string; private prefixed; private connection; /** * Disconnect the underlying client. Useful for tests and graceful shutdown. */ disconnect(): Promise; get(key: string): Promise; put(key: string, value: unknown, seconds?: number | null): Promise; forever(key: string, value: unknown): Promise; increment(key: string, value?: number): Promise; decrement(key: string, value?: number): Promise; forget(key: string): Promise; flush(): Promise; } //#endregion //#region src/drivers/DatabaseStore.d.ts /** * A cache store that persists entries in a relational table via * `@arkstack/database`. * * The table is expected to have `key` (string, primary), `value` (text), and * `expiration` (nullable integer epoch seconds) columns. Run * `ark publish --tag cache-migrations` to add the migration that creates it. * `@arkstack/database` is an optional peer dependency and is imported lazily. */ declare class DatabaseStore extends Store { private readonly databaseConfig; private readonly prefix; private db?; constructor(databaseConfig: DatabaseStoreConfig, prefix?: string); getPrefix(): string; private prefixed; private get table(); private database; get(key: string): Promise; put(key: string, value: unknown, seconds?: number | null): Promise; forever(key: string, value: unknown): Promise; increment(key: string, value?: number): Promise; decrement(key: string, value?: number): Promise; forget(key: string): Promise; flush(): Promise; } //#endregion export { Cache, CacheConfig, CacheDriverName, CacheRow, CacheStoreConfig, CacheStoreFactory, CacheTtl, CustomCacheStoreRegistry, DatabaseFacade, DatabaseStore, DatabaseStoreConfig, FilePayload, FileStore, FileStoreConfig, MemoryEntry, MemoryStore, MemoryStoreConfig, RedisClient, RedisStore, RedisStoreConfig, Repository, Resolvable, Store, configure, ttlToSeconds };