// types.ts
export interface CachifyOptions {
max_age: number;
max_age_auto_invalidate?: number | false;
suppress_stale_revalidate_errors?: boolean;
}
export interface CacheEntry<T> {
value: T;
timestamp: number;
promise?: Promise<T>;
}
export interface CachifyFunctionContext<TArgs extends readonly unknown[], TReturn> {
func: (...args: TArgs) => TReturn;
options: Required<CachifyOptions>;
cache: Map<string, CacheEntry<TReturn>>;
timeouts: Map<string, ReturnType<typeof setTimeout>>;
inFlight: Map<string, Promise<TReturn>>;
}
// utils.ts
export function createCacheKey<TArgs extends readonly unknown[]>(args: TArgs): string {
return JSON.stringify(args);
}
export function isExpired(entry: CacheEntry<unknown>, maxAge: number): boolean {
return Date.now() - entry.timestamp > maxAge;
}
export function isAutoInvalidated(entry: CacheEntry<unknown>, autoInvalidateAge: number): boolean {
return Date.now() - entry.timestamp > autoInvalidateAge;
}
// cachify.ts
export function cachify<TArgs extends readonly unknown[], TReturn>(
func: (...args: TArgs) => TReturn,
options: CachifyOptions
): CachifyFunctionContext<TArgs, TReturn> {
const { max_age, max_age_auto_invalidate = max_age * 1.5, suppress_stale_revalidate_errors = true } = options;
if (max_age_auto_invalidate !== false && max_age_auto_invalidate < max_age) {
throw new Error('max_age_auto_invalidate must be >= max_age or false');
}
return {
func,
options: {
max_age,
max_age_auto_invalidate,
suppress_stale_revalidate_errors
},
cache: new Map(),
timeouts: new Map(),
inFlight: new Map()
};
}
export function runCache<TArgs extends readonly unknown[], TReturn>(
cfc: CachifyFunctionContext<TArgs, TReturn>,
...args: TArgs
): TReturn {
const key = createCacheKey(args);
const entry = cfc.cache.get(key);
// Return cached value if valid
if (entry && !isExpired(entry, cfc.options.max_age)) {
return entry.value;
}
// Check for in-flight request
const inFlight = cfc.inFlight.get(key);
if (inFlight) {
return inFlight as TReturn;
}
// Execute and cache
return executeAndCache(cfc, key, args);
}
export function runStale<TArgs extends readonly unknown[], TReturn>(
cfc: CachifyFunctionContext<TArgs, TReturn>,
...args: TArgs
): TReturn {
const key = createCacheKey(args);
const entry = cfc.cache.get(key);
// Check auto-invalidation first
if (entry && cfc.options.max_age_auto_invalidate !== false &&
isAutoInvalidated(entry, cfc.options.max_age_auto_invalidate)) {
cleanupEntry(cfc, key);
}
const validEntry = cfc.cache.get(key);
if (!validEntry) {
// No cached value, run fresh
return runCache(cfc, ...args);
}
// Return stale value and revalidate in background if expired
if (isExpired(validEntry, cfc.options.max_age)) {
revalidateInBackground(cfc, key, args);
}
return validEntry.value;
}
export function runFresh<TArgs extends readonly unknown[], TReturn>(
cfc: CachifyFunctionContext<TArgs, TReturn>,
...args: TArgs
): TReturn {
const key = createCacheKey(args);
return executeAndCache(cfc, key, args);
}
export function runFreshCached<TArgs extends readonly unknown[], TReturn>(
cfc: CachifyFunctionContext<TArgs, TReturn>,
...args: TArgs
): TReturn {
const key = createCacheKey(args);
const inFlight = cfc.inFlight.get(key);
if (inFlight) {
return inFlight as TReturn;
}
return executeAndCache(cfc, key, args);
}
export function invalidate<TArgs extends readonly unknown[], TReturn>(
cfc: CachifyFunctionContext<TArgs, TReturn>,
...args: TArgs
): void {
const key = createCacheKey(args);
cleanupEntry(cfc, key);
}
export function invalidateAll<TArgs extends readonly unknown[], TReturn>(
cfc: CachifyFunctionContext<TArgs, TReturn>
): void {
for (const key of cfc.cache.keys()) {
cleanupEntry(cfc, key);
}
}
// Helper functions
function executeAndCache<TArgs extends readonly unknown[], TReturn>(
cfc: CachifyFunctionContext<TArgs, TReturn>,
key: string,
args: TArgs
): TReturn {
const result = cfc.func(...args);
if (isPromise(result)) {
const promise = result as Promise<Awaited<TReturn>>;
cfc.inFlight.set(key, promise as Promise<TReturn>);
promise
.then(value => {
cacheValue(cfc, key, value as TReturn);
cfc.inFlight.delete(key);
})
.catch(error => {
cfc.inFlight.delete(key);
throw error;
});
return result;
} else {
cacheValue(cfc, key, result);
return result;
}
}
function cacheValue<TArgs extends readonly unknown[], TReturn>(
cfc: CachifyFunctionContext<TArgs, TReturn>,
key: string,
value: TReturn
): void {
cfc.cache.set(key, {
value,
timestamp: Date.now()
});
setupAutoInvalidation(cfc, key);
}
function setupAutoInvalidation<TArgs extends readonly unknown[], TReturn>(
cfc: CachifyFunctionContext<TArgs, TReturn>,
key: string
): void {
if (cfc.options.max_age_auto_invalidate === false) return;
const existingTimeout = cfc.timeouts.get(key);
if (existingTimeout) {
clearTimeout(existingTimeout);
}
const timeout = setTimeout(() => {
cleanupEntry(cfc, key);
}, cfc.options.max_age_auto_invalidate);
cfc.timeouts.set(key, timeout);
}
function revalidateInBackground<TArgs extends readonly unknown[], TReturn>(
cfc: CachifyFunctionContext<TArgs, TReturn>,
key: string,
args: TArgs
): void {
if (cfc.inFlight.has(key)) return;
try {
const result = cfc.func(...args);
if (isPromise(result)) {
const promise = result as Promise<Awaited<TReturn>>;
cfc.inFlight.set(key, promise as Promise<TReturn>);
promise
.then(value => {
cacheValue(cfc, key, value as TReturn);
cfc.inFlight.delete(key);
})
.catch(error => {
cfc.inFlight.delete(key);
if (!cfc.options.suppress_stale_revalidate_errors) {
throw error;
}
});
} else {
cacheValue(cfc, key, result);
}
} catch (error) {
if (!cfc.options.suppress_stale_revalidate_errors) {
throw error;
}
}
}
function cleanupEntry<TArgs extends readonly unknown[], TReturn>(
cfc: CachifyFunctionContext<TArgs, TReturn>,
key: string
): void {
cfc.cache.delete(key);
cfc.inFlight.delete(key);
const timeout = cfc.timeouts.get(key);
if (timeout) {
clearTimeout(timeout);
cfc.timeouts.delete(key);
}
}
function isPromise<T>(value: T): value is T & Promise<unknown> {
return value != null && typeof (value as any).then === 'function';
}