UNPKG

@ai-growth/nextjs

Version:

Seamlessly integrate Sanity CMS with Next.js applications for automated blog routing and rendering

300 lines 7.52 kB
/** * @fileoverview Advanced Cache Management System * * This module provides a comprehensive caching solution with multi-layer storage, * SWR patterns, cache invalidation, and performance monitoring for CMS content. */ /** * Cache storage options */ export type CacheStorageType = 'memory' | 'localStorage' | 'sessionStorage' | 'indexedDB'; /** * Cache invalidation strategy */ export type CacheInvalidationStrategy = 'ttl' | 'tag-based' | 'webhook' | 'manual'; /** * Cache entry metadata */ export interface CacheEntry<T = any> { /** Cached data */ data: T; /** Timestamp when data was cached */ timestamp: number; /** TTL (time to live) in milliseconds */ ttl: number; /** Stale time in milliseconds */ staleTime: number; /** Cache tags for invalidation */ tags: string[]; /** ETag for HTTP cache validation */ etag?: string; /** Content version for optimistic updates */ version: number; /** Access count for LRU eviction */ accessCount: number; /** Last accessed timestamp */ lastAccessed: number; } /** * Cache configuration options */ export interface CacheConfig { /** Primary storage type */ storage: CacheStorageType; /** Fallback storage types */ fallbackStorage?: CacheStorageType[]; /** Default TTL in milliseconds */ defaultTTL: number; /** Default stale time in milliseconds */ defaultStaleTime: number; /** Maximum cache size (entries) */ maxSize: number; /** Maximum memory usage (bytes) */ maxMemorySize?: number; /** Enable debug logging */ debug: boolean; /** Enable performance metrics */ enableMetrics: boolean; /** Cache key prefix */ keyPrefix: string; } /** * Cache operation result */ export interface CacheResult<T = any> { /** Retrieved data (null if cache miss) */ data: T | null; /** Whether this was a cache hit */ hit: boolean; /** Whether data is stale */ stale: boolean; /** Time until expiry (ms) */ timeToExpiry?: number; /** Cache entry metadata */ metadata?: Partial<CacheEntry<T>>; } /** * Cache metrics */ export interface CacheMetrics { /** Total cache operations */ totalOperations: number; /** Cache hits */ hits: number; /** Cache misses */ misses: number; /** Cache hit ratio */ hitRatio: number; /** Average response time (ms) */ averageResponseTime: number; /** Total cache size (entries) */ cacheSize: number; /** Memory usage (bytes) */ memoryUsage: number; /** Operations per second */ operationsPerSecond: number; } /** * Cache invalidation options */ export interface CacheInvalidationOptions { /** Invalidation strategy */ strategy: CacheInvalidationStrategy; /** Tags to invalidate */ tags?: string[]; /** Specific keys to invalidate */ keys?: string[]; /** Pattern to match keys */ pattern?: RegExp; /** Whether to clear all cache */ clearAll?: boolean; } /** * Advanced multi-layer cache manager */ export declare class CacheManager { private config; private memoryCache; private metrics; private operationTimes; private lastMetricsReset; constructor(config?: Partial<CacheConfig>); /** * Get data from cache */ get<T>(key: string): Promise<CacheResult<T>>; /** * Set data in cache */ set<T>(key: string, data: T, options?: Partial<{ ttl: number; staleTime: number; tags: string[]; etag: string; version: number; }>): Promise<void>; /** * Check if data exists and is fresh */ has(key: string): Promise<{ exists: boolean; fresh: boolean; stale: boolean; }>; /** * Delete specific cache entry */ delete(key: string): Promise<boolean>; /** * Clear cache based on invalidation options */ invalidate(options: CacheInvalidationOptions): Promise<void>; /** * Clear entire cache */ clear(): Promise<void>; /** * Get data with SWR pattern */ getWithSWR<T>(key: string, fetcher: () => Promise<T>, options?: Partial<{ ttl: number; staleTime: number; tags: string[]; revalidateInBackground: boolean; }>): Promise<CacheResult<T> & { revalidating?: boolean; }>; /** * Revalidate data in background */ private revalidateInBackground; /** * Get from memory cache */ private getFromMemory; /** * Set in memory cache */ private setInMemory; /** * Get from persistent storage */ private getFromPersistentStorage; /** * Set in persistent storage */ private setInPersistentStorage; /** * Delete from persistent storage */ private deleteFromPersistentStorage; /** * Clear persistent storage */ private clearPersistentStorage; /** * Get from specific storage type */ private getFromStorage; /** * Set in specific storage type */ private setInStorage; /** * Delete from specific storage type */ private deleteFromStorage; /** * Clear specific storage type */ private clearStorage; private getFromIndexedDB; private setInIndexedDB; private deleteFromIndexedDB; private clearIndexedDB; /** * Invalidate by tags */ private invalidateByTags; /** * Invalidate by pattern */ private invalidateByPattern; /** * Evict LRU entries when cache is full */ private evictLRUEntries; /** * Start cleanup interval */ private startCleanupInterval; /** * Clean up expired entries */ private cleanupExpiredEntries; /** * Record cache operation metrics */ private recordMetrics; /** * Start metrics calculation interval */ private startMetricsCalculation; /** * Update calculated metrics */ private updateMetrics; /** * Get current cache metrics */ getMetrics(): CacheMetrics; /** * Reset metrics */ resetMetrics(): void; /** * Estimate memory usage */ private estimateMemoryUsage; /** * Build full cache key with prefix */ private buildKey; /** * Debug logging */ private log; } /** * Default cache manager instance */ export declare const defaultCacheManager: CacheManager; /** * Create cache manager with custom config */ export declare function createCacheManager(config: Partial<CacheConfig>): CacheManager; /** * Cache key builders for different content types */ export declare const CacheKeys: { readonly content: (contentType: string, slug: string) => string; readonly contentById: (id: string) => string; readonly contentList: (contentType: string, options: any) => string; readonly route: (path: string) => string; readonly author: (authorId: string) => string; readonly category: (categoryId: string) => string; readonly search: (query: string) => string; }; /** * Common cache tags for invalidation */ export declare const CacheTags: { readonly CONTENT: "content"; readonly CONTENT_LIST: "content-list"; readonly AUTHOR: "author"; readonly CATEGORY: "category"; readonly SEARCH: "search"; readonly NAVIGATION: "navigation"; readonly SETTINGS: "settings"; }; //# sourceMappingURL=cache-manager.d.ts.map