Here's the modular, type-safe, and performant TypeScript library cachify-function based on your requirements.
// --- Constants and Type Definitions ---
// Cache state constants for clarity and type safety
const STATE_PENDING = 'PENDING' as const;
const STATE_RESOLVED = 'RESOLVED' as const;
const STATE_REJECTED = 'REJECTED' as const;
type CacheState = typeof STATE_PENDING | typeof STATE_RESOLVED | typeof STATE_REJECTED;
/**
* Options for configuring the cachified function.
*/
export interface CachifyOptions {
/**
* The maximum age (in milliseconds) a cached value is considered "fresh".
* - `0` or `undefined`: Values are considered fresh indefinitely.
* - `> 0`: Values older than this will trigger revalidation by `runCache`.
*/
max_age?: number;
/**
* The maximum age (in milliseconds) after which a cached value is automatically
* invalidated and removed from the cache, regardless of `runCache` or `runStale` calls.
* - `0` or `false`: Auto-invalidation is disabled.
* - `> 0`: The value will be removed from cache after this duration.
* Defaults to `max_age * 1.5` if `max_age` is provided and positive, otherwise `false`.
* Must be greater than or equal to `max_age` if both are numbers.
*/
max_age_auto_invalidate?: number | boolean;
/**
* If `true`, errors occurring during background revalidation triggered by `runStale`
* will be suppressed (not thrown to the caller of `runStale`). These errors are logged as warnings.
* Errors from initial function calls (e.g., when no cache exists) or direct `runFresh` calls are always thrown.
* Defaults to `true`.
*/
suppress_stale_revalidate_errors?: boolean;
/**
* A function used to generate a unique string key for cache entries based on the function arguments.
* Defaults to a robust `JSON.stringify`-based serializer that handles common types.
*
* Provide a custom `keyGenerator` if your arguments include:
* - Functions, Symbols, BigInts (where default serialization might not be unique or desired).
* - Circular references (default will attempt to handle, but may fall back to less unique keys).
* - Objects where deep equality is desired (default relies on serialized value equality, not deep object structure).
* - Arguments with non-deterministic property order (JSON stringification depends on order).
*
* @param args The arguments passed to the cachified function.
* @returns A unique string representation of the arguments.
*/
keyGenerator?: (...args: any[]) => string;
}
/**
* Internal structure for a cache entry.
*/
interface CacheEntry<TResult> {
value: TResult | Promise<TResult>; // The cached result, or an in-flight Promise
timestamp: number; // When the entry was last successfully resolved/updated
state: CacheState; // Current state: PENDING, RESOLVED, REJECTED
error?: unknown; // Stored error if state is REJECTED
timeoutId?: ReturnType<typeof setTimeout>; // ID for the auto-invalidation timeout
}
/**
* The context object returned by `cachify`, encapsulating the original function,
* its options, and its internal cache state.
*/
export interface CachifyFunctionContext<TArgs extends any[], TResult> {
_originalFunc: (...args: TArgs) => TResult | Promise<TResult>;
_options: Required<CachifyOptions>;
_cache: Map<string, CacheEntry<TResult>>; // Main cache storage
_inFlightPromises: Map<string, Promise<TResult>>; // Tracks currently resolving promises
_generateKey: (...args: TArgs) => string;
_resolveFunctionResult: (func: (...args: TArgs) => TResult | Promise<TResult>, ...args: TArgs) => Promise<TResult>;
_handlePromiseCompletion: (
key: string,
promise: Promise<TResult>,
suppressErrors: boolean,
) => void;
_setCacheEntry: (key: string, value: TResult | Promise<TResult>, timestamp: number, state: CacheState, error?: unknown) => void;
_deleteCacheEntry: (key: string) => void;
}
// --- Internal Helper Functions ---
/**
* A robust default key generator that attempts to serialize arguments to a string.
* It handles common types and provides a fallback for non-serializable objects.
* For complex cases, users should provide their own `keyGenerator`.
*/
const defaultKeyGenerator = (...args: any[]): string => {
try {
return JSON.stringify(args, (key, value) => {
// Handle non-JSON serializable types
if (typeof value === 'function' || typeof value === 'symbol' || typeof value === 'bigint') {
return String(value); // Convert to string representation
}
if (value === undefined) {
return '__undefined__'; // Explicitly represent undefined
}
// Handle circular references by returning a placeholder or letting JSON.stringify throw
const cache = new Set();
return JSON.parse(JSON.stringify(value, (k, v) => {
if (typeof v === 'object' && v !== null) {
if (cache.has(v)) {
// Circular reference found, discard key
return '[Circular]';
}
// Store value in our collection
cache.add(v);
}
return v;
}));
});
} catch (e) {
// Fallback for cases like deeply nested objects with circular references
// or very complex non-standard types that the replacer couldn't handle.
console.warn('cachify-function: Default keyGenerator encountered non-serializable arguments or circular references. Consider providing a custom keyGenerator for these arguments.', e);
// This fallback is less unique, but prevents crashes.
return args.map(arg => {
try {
if (typeof arg === 'object' && arg !== null) {
return `[Object:${arg.constructor.name}]`;
}
return String(arg);
} catch {
return '[Non-stringifiable argument]';
}
}).join('|');
}
};
/**
* Wraps a function call in a Promise to unify handling of sync/async functions.
* @param func The function to execute.
* @param args Arguments for the function.
* @returns A Promise that resolves with the function's result or rejects with its error.
*/
function _resolveFunctionResult<TArgs extends any[], TResult>(
func: (...args: TArgs) => TResult | Promise<TResult>,
...args: TArgs
): Promise<TResult> {
try {
const result = func(...args);
return result instanceof Promise ? result : Promise.resolve(result);
} catch (error) {
return Promise.reject(error);
}
}
// --- Main `cachify` function ---
/**
* Creates a cachified version of the provided function.
* @param func The function to cachify. Can be synchronous or asynchronous.
* @param options Configuration options for caching.
* @returns A context object representing the cachified function, used by `runCache`, `runStale`, etc.
*/
export function cachify<TArgs extends any[], TResult>(
func: (...args: TArgs) => TResult | Promise<TResult>,
options?: CachifyOptions
): CachifyFunctionContext<TArgs, TResult> {
const resolvedOptions: Required<CachifyOptions> = {
max_age: options?.max_age ?? 0, // Default to 0 (indefinite freshness)
max_age_auto_invalidate: options?.max_age_auto_invalidate ?? false,
suppress_stale_revalidate_errors: options?.suppress_stale_revalidate_errors ?? true,
keyGenerator: options?.keyGenerator ?? defaultKeyGenerator,
};
// Validate `max_age_auto_invalidate`
if (
typeof resolvedOptions.max_age === 'number' && resolvedOptions.max_age > 0 &&
typeof resolvedOptions.max_age_auto_invalidate === 'number' &&
resolvedOptions.max_age_auto_invalidate < resolvedOptions.max_age
) {
throw new Error('cachify-function: `max_age_auto_invalidate` must be greater than or equal to `max_age`.');
}
// Set default for `max_age_auto_invalidate` if `max_age` is positive and `max_age_auto_invalidate` not explicitly set
if (
typeof resolvedOptions.max_age === 'number' && resolvedOptions.max_age > 0 &&
(resolvedOptions.max_age_auto_invalidate === undefined ||
resolvedOptions.max_age_auto_invalidate === true || // allow `true` to mean default behavior
(typeof resolvedOptions.max_age_auto_invalidate === 'number' && resolvedOptions.max_age_auto_invalidate <= 0))
) {
resolvedOptions.max_age_auto_invalidate = resolvedOptions.max_age * 1.5;
}
const cache = new Map<string, CacheEntry<TResult>>();
const inFlightPromises = new Map<string, Promise<TResult>>();
const context: CachifyFunctionContext<TArgs, TResult> = {
_originalFunc: func,
_options: resolvedOptions,
_cache: cache,
_inFlightPromises: inFlightPromises,
_generateKey: resolvedOptions.keyGenerator,
_resolveFunctionResult: _resolveFunctionResult,
// Handles the completion (resolution or rejection) of a function execution promise.
_handlePromiseCompletion: (key, promise, suppressErrors) => {
promise
.then(value => {
// Only update cache if this promise is still the active in-flight promise for the key.
// This prevents older, replaced promises from overwriting newer results.
if (context._inFlightPromises.get(key) === promise) {
context._setCacheEntry(key, value, Date.now(), STATE_RESOLVED);
context._inFlightPromises.delete(key); // Remove from in-flight as it's settled.
}
})
.catch(error => {
// If this promise was the active in-flight one, remove it.
if (context._inFlightPromises.get(key) === promise) {
context._inFlightPromises.delete(key);
// Requirement: "if theres an error, and if so to remove it from storage"
context._deleteCacheEntry(key); // Always delete on error for robustness
}
// Re-throw the error only if not suppressed and it was the active promise.
if (!suppressErrors && context._inFlightPromises.get(key) !== promise) {
// If the error comes from a promise that was replaced (not the active one),
// and errors are not suppressed, rethrow it for the original caller of that promise.
// This ensures that the caller of the now-stale promise still gets their error.
throw error;
} else if (!suppressErrors) {
// This case handles errors for the currently active promise that should not be suppressed.
throw error;
} else {
// Error suppressed (e.g., background revalidation for runStale)
console.warn(`cachify-function: Suppressed error for key "${key}" during revalidation:`, error);
}
});
},
// Sets or updates a cache entry, clearing any existing auto-invalidation timeout.
_setCacheEntry: (key, value, timestamp, state, error?) => {
const existingEntry = context._cache.get(key);
if (existingEntry?.timeoutId) {
clearTimeout(existingEntry.timeoutId); // Clear old timeout if exists
}
const newEntry: CacheEntry<TResult> = { value, timestamp, state, error };
context._cache.set(key, newEntry);
// Set new auto-invalidation timeout if enabled
if (typeof context._options.max_age_auto_invalidate === 'number' && context._options.max_age_auto_invalidate > 0) {
newEntry.timeoutId = setTimeout(() => {
context._deleteCacheEntry(key);
}, context._options.max_age_auto_invalidate);
}
},
// Deletes a cache entry, clearing its auto-invalidation timeout.
_deleteCacheEntry: (key) => {
const entry = context._cache.get(key);
if (entry?.timeoutId) {
clearTimeout(entry.timeoutId);
}
context._cache.delete(key);
}
};
return context;
}
// --- Exported Cache Interaction Functions ---
/**
* Executes the cachified function.
* - Returns a cached value if it's within `max_age` or if an in-flight promise exists.
* - If the cached value is stale or an in-flight promise doesn't exist, it executes the original function,
* caches the result, and returns a promise for it.
* @param cfc The CachifyFunctionContext.
* @param funcArgs Arguments to pass to the original function.
* @returns A Promise resolving to the result of the function.
*/
export function runCache<TArgs extends any[], TResult>(
cfc: CachifyFunctionContext<TArgs, TResult>,
...funcArgs: TArgs
): Promise<TResult> {
const key = cfc._generateKey(...funcArgs);
const inFlight = cfc._inFlightPromises.get(key);
if (inFlight) {
return inFlight; // Return existing in-flight promise
}
const entry = cfc._cache.get(key);
if (entry && entry.state === STATE_RESOLVED) {
const isFresh = cfc._options.max_age === 0 || (Date.now() - entry.timestamp <= cfc._options.max_age);
if (isFresh) {
return Promise.resolve(entry.value as TResult);
}
// If not fresh, fall through to runFresh. The entry will be deleted by runFresh's logic.
}
// No fresh entry or no entry at all. Run fresh. Errors are not suppressed for runCache.
return runFresh(cfc, ...funcArgs);
}
/**
* Executes the cachified function, prioritizing a cached value even if stale.
* - If a cached value exists (regardless of `max_age`), it's returned immediately.
* - Concurrently, if the cached value is stale (beyond `max_age`), the function is revalidated in the background.
* - If no cached value exists, the function is executed directly and its promise returned.
* @param cfc The CachifyFunctionContext.
* @param funcArgs Arguments to pass to the original function.
* @returns A Promise resolving to the result.
*/
export function runStale<TArgs extends any[], TResult>(
cfc: CachifyFunctionContext<TArgs, TResult>,
...funcArgs: TArgs
): Promise<TResult> {
const key = cfc._generateKey(...funcArgs);
const inFlight = cfc._inFlightPromises.get(key);
if (inFlight) {
return inFlight; // Return existing in-flight promise
}
const entry = cfc._cache.get(key);
if (entry) {
// Check auto-invalidation threshold (this cleans up before runStale returns stale if auto-invalidated)
const isAutoInvalidated = typeof cfc._options.max_age_auto_invalidate === 'number' &&
cfc._options.max_age_auto_invalidate > 0 &&
(Date.now() - entry.timestamp > cfc._options.max_age_auto_invalidate);
if (entry.state === STATE_RESOLVED && !isAutoInvalidated) {
const cachedValue = entry.value as TResult;
// Trigger background revalidation if stale (beyond max_age)
const isStale = cfc._options.max_age > 0 && (Date.now() - entry.timestamp > cfc._options.max_age);
if (isStale) {
const revalidationPromise = cfc._resolveFunctionResult(cfc._originalFunc, ...funcArgs);
// Store this new promise as the in-flight one, overwriting any previous.
cfc._inFlightPromises.set(key, revalidationPromise);
// Update cache entry to PENDING with the new promise
cfc._setCacheEntry(key, revalidationPromise, Date.now(), STATE_PENDING);
// Handle completion of this background revalidation promise.
// Errors from background revalidation are suppressed based on options.
cfc._handlePromiseCompletion(key, revalidationPromise, cfc._options.suppress_stale_revalidate_errors);
}
return Promise.resolve(cachedValue); // Return the (possibly stale) cached value immediately
}
// If rejected or auto-invalidated, fall through to runFresh.
cfc._deleteCacheEntry(key); // Clean up invalid entry
}
// No cached value or it was auto-invalidated/rejected. Run fresh.
// Errors from this initial execution (when no cache exists) are not suppressed.
return runFresh(cfc, ...funcArgs);
}
/**
* Executes the original function, always fetching a fresh result.
* - This will initiate a new execution of the original function.
* - The result will be cached and any in-flight promise for these arguments will be updated to this new execution.
* - Errors are always thrown to the caller.
* @param cfc The CachifyFunctionContext.
* @param funcArgs Arguments to pass to the original function.
* @returns A Promise resolving to the fresh result.
*/
export function runFresh<TArgs extends any[], TResult>(
cfc: CachifyFunctionContext<TArgs, TResult>,
...funcArgs: TArgs
): Promise<TResult> {
const key = cfc._generateKey(...funcArgs);
// Clear any existing cache entry and in-flight promise for this key to force a fresh run.
cfc._deleteCacheEntry(key); // Clears cache entry and its timeout
cfc._inFlightPromises.delete(key); // Ensures no old in-flight promise is returned by other functions.
// Execute the original function to get a fresh result.
const newPromise = cfc._resolveFunctionResult(cfc._originalFunc, ...funcArgs);
// Store this new promise as the current in-flight promise.
cfc._inFlightPromises.set(key, newPromise);
cfc._setCacheEntry(key, newPromise, Date.now(), STATE_PENDING);
// Handle completion of this promise. Errors are NEVER suppressed for `runFresh`.
cfc._handlePromiseCompletion(key, newPromise, false);
return newPromise;
}
/**
* Returns a pending promise if one exists for the arguments, otherwise calls `runFresh`.
* - If an in-flight promise (from `runFresh`, `runCache`, or `runStale`'s background revalidation)
* exists for the given arguments, that promise is returned.
* - If no in-flight promise exists, `runFresh` is called to initiate a new execution and its promise is returned.
* @param cfc The CachifyFunctionContext.
* @param funcArgs Arguments to pass to the original function.
* @returns A Promise resolving to the result.
*/
export function runFreshCached<TArgs extends any[], TResult>(
cfc: CachifyFunctionContext<TArgs, TResult>,
...funcArgs: TArgs
): Promise<TResult> {
const key = cfc._generateKey(...funcArgs);
const inFlight = cfc._inFlightPromises.get(key);
if (inFlight) {
return inFlight; // Return existing in-flight promise
}
// No in-flight promise, so run fresh. This will set a new in-flight promise.
return runFresh(cfc, ...funcArgs);
}
/**
* Invalidates a specific cached entry, removing it from the cache and canceling its auto-invalidation timeout.
* If no entry exists for the given arguments, nothing happens.
* @param cfc The CachifyFunctionContext.
* @param funcArgs Arguments corresponding to the cached entry to invalidate.
*/
export function invalidate<TArgs extends any[], TResult>(
cfc: CachifyFunctionContext<TArgs, TResult>,
...funcArgs: TArgs
): void {
const key = cfc._generateKey(...funcArgs);
cfc._deleteCacheEntry(key);
cfc._inFlightPromises.delete(key); // Also clear any in-flight promise for this key
}
/**
* Invalidates all cached entries for the given CachifyFunctionContext,
* clearing the cache and canceling all pending auto-invalidation timeouts.
* @param cfc The CachifyFunctionContext.
*/
export function invalidateAll<TArgs extends any[], TResult>(
cfc: CachifyFunctionContext<TArgs, TResult>
): void {
// Iterate through all entries and clear their timeouts
for (const entry of cfc._cache.values()) {
if (entry.timeoutId) {
clearTimeout(entry.timeoutId);
}
}
cfc._cache.clear(); // Clear the cache Map
cfc._inFlightPromises.clear(); // Clear all in-flight promises
}