UNPKG

fortify2-js

Version:

MOST POWERFUL JavaScript Security Library! Military-grade cryptography + 19 enhanced object methods + quantum-resistant algorithms + perfect TypeScript support. More powerful than Lodash with built-in security.

1,775 lines (1,756 loc) 320 kB
import { Request, Response, NextFunction, Express, RequestHandler } from 'express'; import { EventEmitter } from 'events'; import { Server } from 'http'; import * as crypto from 'crypto'; import crypto__default from 'crypto'; type CachedData = Record<string, any>; interface MemoryCacheEntry { data: string; iv: string; authTag: string; timestamp: number; expiresAt: number; accessCount: number; lastAccessed: number; compressed: boolean; size: number; version: number; } interface CacheStats { hits: number; misses: number; evictions: number; totalSize: number; entryCount: number; hitRate: number; memoryUsage: { used: number; limit: number; percentage: number; }; totalAccesses: number; size: number; capacity: number; } interface CacheOptions { ttl?: number; compress?: boolean; encrypt?: boolean; } /** * Options for file-based cache operations */ interface FileCacheOptions extends CacheOptions { maxCacheSize: number; /** Directory to store cache files (default: .data/cache) */ directory?: string; /** File extension for cache files (default: .cache) */ extension?: string; /** Enable atomic writes (write to temp file then rename) */ atomic?: boolean; /** Enable file compression */ compress?: boolean; /** Custom file naming strategy */ namingStrategy?: "hash" | "direct" | "hierarchical" | "dated" | "flat"; /** Maximum file size in bytes (default: 10MB) */ maxFileSize?: number; /** Enable file metadata tracking */ trackMetadata?: boolean; } /** * File cache entry metadata */ interface FileCacheMetadata { /** Original cache key */ key: string; /** File creation timestamp */ createdAt: number; /** Last access timestamp */ lastAccessed: number; /** Expiration timestamp */ expiresAt: number; /** File size in bytes */ size: number; /** Number of times accessed */ accessCount: number; /** Whether data is compressed */ compressed: boolean; /** Whether data is encrypted */ encrypted: boolean; /** Data type information */ dataType: string; /** File version for migration support */ version: number; } /** * File cache statistics */ interface FileCacheStats { /** Total number of cache files */ fileCount: number; /** Total disk space used in bytes */ totalSize: number; /** Number of cache hits */ hits: number; /** Number of cache misses */ misses: number; /** Number of expired files cleaned up */ cleanups: number; /** Average file size in bytes */ averageFileSize: number; /** Cache hit rate percentage */ hitRate: number; /** Disk usage by directory */ diskUsage: { used: number; available: number; percentage: number; }; /** File age distribution */ ageDistribution: { fresh: number; recent: number; old: number; }; reads: number; writes: number; deletes: number; errors: number; totalFiles: number; avgResponseTime: number; lastCleanup: number; } /** * File cache cleanup options */ interface FileCacheCleanupOptions { /** Remove expired files */ removeExpired?: boolean; /** Remove files older than specified age in milliseconds */ maxAge?: number; /** Maximum number of files to keep (LRU cleanup) */ maxFiles?: number; /** Maximum total size in bytes (size-based cleanup) */ maxTotalSize?: number; /** Dry run mode (don't actually delete files) */ dryRun?: boolean; } /** * File cache directory structure */ type FileCacheStrategy = "flat" | "hierarchical" | "dated" | "custom"; /** * Enhanced cache configuration */ interface SecureCacheConfig { strategy?: "memory" | "redis" | "hybrid" | "distributed"; memory?: { maxSize?: number; maxEntries?: number; ttl?: number; algorithm?: "lru" | "lfu" | "fifo"; evictionPolicy?: "lru" | "lfu" | "fifo" | "ttl"; preallocation?: boolean; }; redis?: { host?: string; port?: number; password?: string; db?: number; cluster?: { enabled?: boolean; nodes?: Array<{ host: string; port: number; }>; options?: any; }; pool?: { min?: number; max?: number; acquireTimeoutMillis?: number; }; sentinel?: { enabled?: boolean; sentinels?: Array<{ host: string; port: number; }>; name?: string; }; }; performance?: { batchSize?: number; compressionThreshold?: number; hotDataThreshold?: number; prefetchEnabled?: boolean; asyncWrite?: boolean; pipeline?: boolean; connectionPooling?: boolean; }; security?: { encryption?: boolean; keyRotation?: boolean; accessMonitoring?: boolean; sanitization?: boolean; auditLogging?: boolean; }; monitoring?: { enabled?: boolean; metricsInterval?: number; alertThresholds?: { memoryUsage?: number; hitRate?: number; errorRate?: number; latency?: number; }; detailed?: boolean; }; resilience?: { retryAttempts?: number; retryDelay?: number; circuitBreaker?: boolean; fallback?: boolean; healthCheck?: boolean; }; } /** * Enhanced cache statistics */ interface EnhancedCacheStats { memory: CacheStats; redis?: { connected: boolean; commandsProcessed: number; operations: number; memoryUsage: { used: number; peak: number; percentage: number; }; keyspaceHits: number; keyspaceMisses: number; hits: number; misses: number; hitRate: number; connectedClients: number; connections: number; keys: number; uptime: number; lastUpdate: number; }; performance: { totalOperations: number; averageResponseTime: number; hotDataHitRate: number; compressionRatio: number; networkLatency: number; }; security: { encryptedEntries: number; keyRotations: number; suspiciousAccess: number; securityEvents: number; }; } /** * FortifyJS Secure Cache Adapter * Ultra-fast hybrid cache system combining security cache with Redis clustering * * Features: * - Memory-first hybrid architecture for maximum speed * - Redis Cluster support with automatic failover * - Connection pooling and health monitoring * - Advanced tagging and invalidation * - Real-time performance metrics * - Military-grade security from FortifyJS security cache */ /** * UF secure cache adapter */ declare class SecureCacheAdapter extends EventEmitter { private config; private memoryCache; private redisClient?; private connectionPool; private metadata; private stats; private healthMonitor?; private metricsCollector?; private masterEncryptionKey; constructor(config?: SecureCacheConfig); /** * Initialize statistics */ private initializeStats; /** * Initialize master encryption key for consistent encryption */ private initializeMasterKey; /** * Initialize memory cache with security features */ private initializeMemoryCache; /** * Connect to cache backends */ connect(): Promise<void>; /** * Initialize Redis with clustering and failover support */ private initializeRedis; /** * Setup Redis event handlers for monitoring and failover */ private setupRedisEventHandlers; /** * Start monitoring and health checks */ private startMonitoring; /** * Perform health check on all cache backends */ private performHealthCheck; /** * Collect performance metrics */ private collectMetrics; /** * Update performance metrics */ private updatePerformanceMetrics; /** * Generate cache key with namespace and security */ private generateKey; /** * Determine if data should be considered "hot" (frequently accessed) */ private isHotData; /** * Update access metadata for performance optimization */ private updateAccessMetadata; /** * Convert any data to CachedData format for SecurityCache compatibility */ private toCachedData; /** * Extract raw data from CachedData format */ private fromCachedData; /** * Serialize data for Redis storage with proper encryption */ private serializeForRedis; /** * Deserialize data from Redis storage with proper decryption */ private deserializeFromRedis; /** * Get value from cache with ultra-fast hybrid strategy */ get(key: string): Promise<any>; /** * Set value in cache with intelligent placement */ set(key: string, value: any, options?: { ttl?: number; tags?: string[]; }): Promise<boolean>; /** * Delete value from cache */ delete(key: string): Promise<boolean>; /** * Check if key exists in cache */ exists(key: string): Promise<boolean>; /** * Clear all cache entries */ clear(): Promise<void>; /** * Get value from Redis with encryption support */ private getFromRedis; /** * Set value in Redis with encryption and TTL support */ private setInRedis; /** * Set tags for cache invalidation */ private setTags; /** * Record response time for performance monitoring */ private recordResponseTime; /** * Invalidate cache entries by tags */ invalidateByTags(tags: string[]): Promise<number>; /** * Get multiple values at once (batch operation) */ mget(keys: string[]): Promise<Record<string, any>>; /** * Set multiple values at once (batch operation) */ mset(entries: Record<string, any> | Array<[string, any]>, options?: { ttl?: number; tags?: string[]; }): Promise<boolean>; /** * Get TTL for a specific key */ getTTL(key: string): Promise<number>; /** * Set expiration time for a key */ expire(key: string, ttl: number): Promise<boolean>; /** * Get all keys matching a pattern */ keys(pattern?: string): Promise<string[]>; /** * Extract original key from cache key */ private extractOriginalKey; /** * Get comprehensive cache statistics */ getStats(): Promise<EnhancedCacheStats>; /** * Update Redis statistics using Redis INFO command */ private updateRedisStats; /** * Calculate Redis memory usage percentage */ private calculateRedisMemoryPercentage; /** * Get cache health status */ getHealth(): { status: "healthy" | "degraded" | "unhealthy"; details: any; }; /** * Disconnect from all cache backends */ disconnect(): Promise<void>; } interface UltraMemoryCacheEntry extends MemoryCacheEntry { hotness: number; priority: number; tags: Set<string>; metadata: Record<string, any>; checksum: string; } interface UltraCacheOptions extends CacheOptions { priority?: number; tags?: string[]; metadata?: Record<string, any>; skipEncryption?: boolean; skipCompression?: boolean; onEvict?: (key: string, value: CachedData) => void; } interface UltraStats extends CacheStats { averageAccessTime: number; compressionRatio: number; encryptionOverhead: number; hotKeys: string[]; coldKeys: string[]; tagStats: Map<string, number>; } /** * Enhanced Secure In-Memory Cache (SIMC) v2.0 * * Now powered by Ultra-Fast Secure In-Memory Cache (UFSIMC) for significantly improved performance * while maintaining 100% backward compatibility with existing SIMC API. * * Performance improvements over SIMC v1.0: * - 10-50x faster cache operations through optimized algorithms * - Advanced hotness tracking and intelligent caching strategies * - Optimized memory management with object pooling * - Smart compression and encryption with minimal overhead * - Real-time performance monitoring and adaptive optimization * - Sub-millisecond cache hits with predictive prefetching * * Backward Compatibility: * All existing SIMC code will work without any changes while automatically benefiting * from UFSIMC's enhanced performance and advanced features. No API changes required. * * Migration Benefits: * - Existing applications get instant performance boost * - Same security guarantees with enhanced encryption * - Better memory efficiency and automatic cleanup * - Advanced monitoring and health diagnostics * - Zero code changes required for existing users */ /** * Enhanced Secure In-Memory Cache (SIMC) v2.0 * * Backward-compatible wrapper around UFSIMC that provides the same API as SIMC v1.0 * while delivering significantly enhanced performance and advanced features. */ declare class SIMC extends EventEmitter { private ultraCache; constructor(); /** * Setup event forwarding from UFSIMC to maintain compatibility */ private setupEventForwarding; /** * Convert SIMC options to UFSIMC-compatible format */ private convertToUFSIMCOptions; /** * Convert UFSIMC stats to SIMC-compatible format */ private convertToSIMCStats; /** * Validate and normalize cache key */ private validateKey; /** * Store data in cache with optional TTL and compression * * Enhanced with UFSIMC's intelligent caching strategies while maintaining * the exact same API as SIMC v1.0 for seamless backward compatibility. * * @param key - Unique identifier for the cached data * @param data - Data to cache (any serializable type) * @param options - Optional cache configuration * @returns Promise resolving to true if successful */ set(key: string, data: CachedData, options?: Partial<CacheOptions>): Promise<boolean>; /** * Retrieve data from cache * * Enhanced with UFSIMC's predictive prefetching and hotness tracking * for significantly faster retrieval times. * * @param key - Unique identifier for the cached data * @returns Promise resolving to cached data or null */ get(key: string): Promise<CachedData | null>; /** * Delete entry from cache * * @param key - Cache key to remove * @returns True if entry was deleted, false otherwise */ delete(key: string): boolean; /** * Check if key exists in cache * * @param key - Cache key to check * @returns True if key exists and is not expired */ has(key: string): boolean; /** * Clear all cache entries */ clear(): void; /** * Get cache statistics in SIMC v1.0 compatible format * * Enhanced with additional performance metrics from UFSIMC * while maintaining the same return structure for compatibility. * * @returns Cache statistics */ get getStats(): CacheStats; /** * Get cache size information * * @returns Object with entries count and total bytes */ get size(): { entries: number; bytes: number; }; /** * Clean up expired entries * * Enhanced with UFSIMC's intelligent cleanup strategies. * Note: UFSIMC handles cleanup automatically, this method is for compatibility. * * @returns Number of entries cleaned up (estimated based on stats) */ cleanup(): number; /** * Shutdown cache and cleanup resources * * Properly shuts down UFSIMC and cleans up all resources. */ shutdown(): void; } interface SimpleLogger { warn(component: string, message: string, ...args: any[]): void; securityWarning(message: string, ...args: any[]): void; } /** * Ultra-Fast Secure In-Memory Cache (UFSIMC) * Extends SIMC with extreme performance optimizations and advanced features */ declare class UFSIMC extends EventEmitter { private lru; private keyHashMap; private tagIndex; private priorityQueues; private hotnessDecayTimer?; private stats; private encryptionKey; private keyRotationTimer?; private cleanupTimer?; private securityTimer?; private performanceTimer?; private encryptionPool; private accessTimes; private accessPatterns; private rateLimiter; private integrityCheck; private anomalyThreshold; private logger?; constructor(maxEntries?: number, logger?: SimpleLogger); /** * Warm up cipher pools for better performance */ private warmUpPools; /** * Start performance monitoring */ private startPerformanceMonitoring; /** * Enhanced encryption initialization with key derivation */ private initializeEncryption; /** * Ultra-fast key validation and hashing */ private validateAndHashKey; /** * High-performance compression with adaptive algorithms */ private smartCompress; /** * Smart decompression */ private smartDecompress; /** * High-performance encryption with pooling */ private fastEncrypt; /** * High-performance decryption */ private fastDecrypt; /** * Calculate data checksum for integrity */ private calculateChecksum; /** * Rate limiting check */ private checkRateLimit; /** * Ultra-fast SET operation with advanced features */ set(key: string, value: CachedData, options?: UltraCacheOptions): Promise<boolean>; /** * Ultra-fast GET operation with hotness tracking */ get(key: string): Promise<CachedData | null>; /** * Helper method for decryption and decompression */ private decryptAndDecompress; /** * Batch GET operation for multiple keys */ getMultiple(keys: string[]): Promise<Map<string, CachedData | null>>; /** * Set multiple key-value pairs */ setMultiple(entries: Array<{ key: string; value: CachedData; options?: UltraCacheOptions; }>): Promise<boolean[]>; /** * Delete by tag */ deleteByTag(tag: string): Promise<number>; /** * Get keys by tag */ getKeysByTag(tag: string): string[]; /** * Advanced cache statistics */ get getUltraStats(): UltraStats; /** * Export cache data for backup */ exportData(): Promise<any>; /** * Import cache data from backup */ importData(data: any): Promise<boolean>; /** * Performance and maintenance methods */ private updatePerformanceMetrics; private updateHotColdKeys; private optimizeHotness; private decayHotness; private recordAccessTime; private updateStatsAfterSet; private trackAccess; private cleanupIndexes; private findOriginalKey; private startMaintenanceTasks; private cleanup; private rotateEncryptionKey; private performSecurityChecks; private emergencyCleanup; private detectAnomalies; /** * Get cache health report */ getHealthReport(): { status: "healthy" | "warning" | "critical"; issues: string[]; recommendations: string[]; metrics: UltraStats; }; /** * Optimize cache configuration automatically */ autoOptimize(): void; /** * Prefetch data based on access patterns */ prefetch(predictor: (key: string, metadata: any) => Promise<CachedData | null>): Promise<number>; /** * Create a cache snapshot for debugging */ createSnapshot(): any; /** * Validate cache integrity */ validateIntegrity(): Promise<{ valid: number; invalid: number; errors: string[]; }>; /** * Enhanced delete with pattern matching */ delete(key: string): boolean; /** * Delete with pattern (supports wildcards) */ deletePattern(pattern: string): number; /** * Check if key exists */ has(key: string): boolean; /** * Clear all entries */ clear(): void; /** * Get cache size */ get size(): { entries: number; bytes: number; }; /** * Graceful shutdown */ shutdown(): Promise<void>; } declare const CONFIG: { CACHE_EXPIRY_MS: number; KEY_ROTATION_MS: number; ALGORITHM: "aes-256-gcm"; ENCODING: crypto.BinaryToTextEncoding; KEY_ITERATIONS: number; KEY_LENGTH: number; MAX_CACHE_SIZE_MB: number; MAX_ENTRIES: number; COMPRESSION_THRESHOLD_BYTES: number; CLEANUP_INTERVAL_MS: number; SECURITY_CHECK_INTERVAL_MS: number; MAX_KEY_LENGTH: number; MAX_VALUE_SIZE_MB: number; }; /** * Default configuration for file-based cache */ declare const DEFAULT_FILE_CACHE_CONFIG: Required<FileCacheOptions>; /** * Comprehensive File Cache System */ declare class FileCache { private config; private stats; constructor(options?: Partial<FileCacheOptions>); /** * Initialize cache statistics by scanning existing files */ private initializeStats; /** * Ensure base cache directory exists */ private ensureBaseDirectory; /** * Update cache statistics */ private updateStats; /** * Update disk usage statistics */ private updateDiskUsage; /** * Calculate directory size recursively */ private getDirectorySize; /** * Update age distribution statistics */ private updateAgeDistribution; /** * Write data to file cache */ set(key: string, value: CachedData, options?: Partial<FileCacheOptions>): Promise<boolean>; /** * Read data from file cache */ get(key: string, updatedContent?: boolean): Promise<CachedData | null>; /** * Delete cache entry */ delete(key: string): Promise<boolean>; /** * Check if key exists and is not expired */ has(key: string): Promise<boolean>; /** * Clear all cache files */ clear(): Promise<void>; /** * Recursively delete directory */ private deleteDirectory; /** * Cleanup expired entries */ cleanup(_options?: Partial<FileCacheCleanupOptions>): Promise<{ cleaned: number; errors: number; totalSize: number; }>; /** * Get all cache files recursively */ private getAllCacheFiles; /** * Get cache statistics with real-time updates */ getStats(): Promise<FileCacheStats>; /** * Get cache size information */ get size(): { files: number; bytes: number; }; /** * Get detailed cache information */ getCacheInfo(): Promise<{ config: Required<FileCacheOptions>; stats: FileCacheStats; health: { healthy: boolean; issues: string[]; recommendations: string[]; }; }>; } /*************************************************************************** * FortifyJS - Secure Array Types * * This file contains type definitions for the SecureArray modular architecture * * @author Nehonix * @license MIT * * Copyright (c) 2025 Nehonix. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. ***************************************************************************** */ /** * @fileoverview FortifyJS Unified Cache System - Enterprise-Grade Caching Solution * * A comprehensive, caching solution combining multiple strategies * with military-grade security and ultra-fast performance optimization. * * ## Cache Strategies * - **Memory Cache**: Ultra-fast in-process storage with LRU eviction * - **File Cache**: Persistent cross-process storage with real disk monitoring * - **Hybrid Cache**: Automatic optimization between memory and file storage * - **Redis Cache**: Distributed scalable storage (via integrations) * * ## Security Features * - AES-256-GCM encryption for all cached data * - PBKDF2 key derivation with automatic key rotation * - Tamper-evident storage with integrity verification * - Secure key management and access pattern monitoring * - Memory-safe operations with automatic cleanup * * ## Performance Features * - Zlib compression for large values (configurable threshold) * - LRU eviction with intelligent memory pressure management * - Real-time disk space monitoring and automatic cleanup * - Atomic file operations for data consistency * - Sub-millisecond cache hits with object pooling * - Configurable TTL with background expiration cleanup * * ## Production Features * - Comprehensive error handling with graceful degradation * - Real-time performance metrics and health monitoring * - Configurable naming strategies (flat, hierarchical, dated, direct) * - Cross-platform compatibility (Windows, macOS, Linux) * - Zero-dependency core with optional integrations * - TypeScript support with complete type definitions * * @example * ```typescript * // Quick start with default memory cache * import { Cache } from "fortify2-js"; * * await Cache.set('user:123', { name: 'John', role: 'admin' }, { ttl: 3600000 }); * const user = await Cache.get('user:123'); * * // File-based persistent cache * import { FileCache } from "fortify2-js"; * * const fileCache = new FileCache({ * directory: './cache', * encrypt: true, * compress: true, * maxCacheSize: 1024 * 1024 * 100 // 100MB * }); * * await fileCache.set('session:abc', sessionData, { ttl: 86400000 }); * * // Hybrid cache for optimal performance * import { createOptimalCache } from "fortify2-js"; * * const hybridCache = createOptimalCache({ * type: 'hybrid', * config: { encrypt: true, compress: true } * }); * ``` * * @version 4.2.3 * @author FortifyJS Team * @since 2024-12-19 * @license MIT */ /** * Default secure in-memory cache instance * * Pre-configured singleton instance with optimal security settings for immediate use. * Features AES-256-GCM encryption, LRU eviction, and automatic memory management. * * @example * ```typescript * import { Cache } from "fortify2-js"; * * // Store user session with 1-hour TTL * await Cache.set('session:user123', { * userId: 123, * permissions: ['read', 'write'], * loginTime: Date.now() * }, { ttl: 3600000 }); * * // Retrieve cached data * const session = await Cache.get('session:user123'); * * // Check cache statistics * const stats = Cache.getStats(); * console.log(`Hit rate: ${stats.hitRate}%`); * ``` * * @since 4.2.2 */ declare const Cache: SIMC; /** * Generate a secure file path for cache storage * * Creates secure, collision-resistant file paths using configurable naming strategies. * All keys are hashed using SHA-256 to prevent directory traversal attacks and * ensure consistent path generation across platforms. * * @param key - The cache key to generate a path for * @param options - Optional configuration for path generation * @returns Secure file path for the given key * * @example * ```typescript * import { generateFilePath } from "fortify2-js"; * * // Hierarchical structure (recommended for large caches) * const path1 = generateFilePath('user:123', { * namingStrategy: 'hierarchical', * directory: './cache' * }); * // Result: ./cache/a1/b2/a1b2c3d4...cache * * // Date-based organization (good for time-series data) * const path2 = generateFilePath('daily-report', { * namingStrategy: 'dated', * directory: './reports' * }); * // Result: ./reports/2024/12/19/hash...cache * * // Direct naming (human-readable, limited special chars) * const path3 = generateFilePath('config-settings', { * namingStrategy: 'direct', * directory: './config' * }); * // Result: ./config/config-settings.cache * ``` * * @since 4.2.2 */ declare const generateFilePath: (key: string, options?: Partial<FileCacheOptions>) => string; declare const defaultFileCache: FileCache; /** * Write data to file cache with automatic optimization * * Stores data in the file cache with intelligent compression and encryption. * Automatically handles large objects and provides atomic write operations. * * @param key - Unique identifier for the cached data * @param data - Data to cache (any serializable type) * @param options - Optional cache configuration * @returns Promise resolving to true if successful * * @example * ```typescript * import { writeFileCache } from "fortify2-js"; * * // Cache user profile with encryption * const success = await writeFileCache('profile:user123', { * name: 'John Doe', * preferences: { theme: 'dark', lang: 'en' } * }, { * encrypt: true, * ttl: 3600000 // 1 hour * }); * ``` * * @since 4.2.2 */ declare const writeFileCache: (key: string, data: CachedData, options?: Partial<FileCacheOptions>) => Promise<boolean>; /** * Read data from file cache with automatic decryption * * Retrieves and automatically decrypts/decompresses cached data. * Returns null for expired or non-existent entries. * * @param key - Unique identifier for the cached data * @returns Promise resolving to cached data or null * * @example * ```typescript * import { readFileCache } from "fortify2-js"; * * const userData = await readFileCache('profile:user123'); * if (userData) { * console.log('Welcome back,', userData.name); * } else { * console.log('Cache miss - loading from database'); * } * ``` * * @since 4.2.2 */ declare const readFileCache: (key: string) => Promise<CachedData | null>; /** * Remove specific entry from file cache * * Permanently deletes a cache entry and updates disk usage statistics. * Safe to call on non-existent keys. * * @param key - Unique identifier for the cached data * @returns Promise resolving to true if entry was deleted * * @example * ```typescript * import { removeFileCache } from "fortify2-js"; * * // Remove expired session * const removed = await removeFileCache('session:expired123'); * console.log(removed ? 'Session cleared' : 'Session not found'); * ``` * * @since 4.2.2 */ declare const removeFileCache: (key: string) => Promise<boolean>; /** * Check if file cache entry exists and is valid * * Verifies cache entry existence without loading the data. * Automatically removes expired entries during check. * * @param key - Unique identifier for the cached data * @returns Promise resolving to true if entry exists and is valid * * @example * ```typescript * import { hasFileCache } from "fortify2-js"; * * if (await hasFileCache('config:app-settings')) { * const config = await readFileCache('config:app-settings'); * } else { * // Load from default configuration * } * ``` * * @since 4.2.2 */ declare const hasFileCache: (key: string) => Promise<boolean>; /** * Clear all file cache entries * * Removes all cached files and resets statistics. * Use with caution in production environments. * * @example * ```typescript * import { clearFileCache } from "fortify2-js"; * * // Clear cache during maintenance * await clearFileCache(); * console.log('Cache cleared successfully'); * ``` * * @since 4.2.2 */ declare const clearFileCache: () => Promise<void>; /** * Get comprehensive file cache statistics * * Returns real-time statistics including disk usage, hit rates, * and performance metrics with health assessment. * * @returns Promise resolving to detailed cache statistics * * @example * ```typescript * import { getFileCacheStats } from "fortify2-js"; * * const stats = await getFileCacheStats(); * console.log(`Cache efficiency: ${stats.hitRate}%`); * console.log(`Disk usage: ${stats.diskUsage.percentage}%`); * console.log(`Average response time: ${stats.avgResponseTime}ms`); * ``` * * @since 4.2.2 */ declare const getFileCacheStats: () => Promise<FileCacheStats>; /** * Clean up expired file cache entries * * Removes expired entries and optimizes disk usage. * Automatically runs in background but can be triggered manually. * * @param options - Optional cleanup configuration * @returns Promise resolving to cleanup results * * @example * ```typescript * import { cleanupFileCache } from "fortify2-js"; * * const result = await cleanupFileCache(); * console.log(`Cleaned ${result.cleaned} files, freed ${result.totalSize} bytes`); * ``` * * @since 4.2.2 */ declare const cleanupFileCache: (options?: Partial<FileCacheCleanupOptions>) => Promise<{ cleaned: number; errors: number; totalSize: number; }>; /** * Read data from memory cache with fallback * * Retrieves data from the default memory cache instance. * Returns empty object if key is not found (legacy behavior). * * @param args - Arguments passed to Cache.get() * @returns Promise resolving to cached data or empty object * * @example * ```typescript * import { readCache } from "fortify2-js"; * * const sessionData = await readCache('session:user123'); * console.log('User ID:', sessionData.userId || 'Not found'); * ``` * * @since 4.2.2 */ declare const readCache: (...args: Parameters<typeof Cache.get>) => Promise<CachedData>; /** * Write data to memory cache * * Stores data in the default memory cache instance with encryption * and automatic compression for large values. * * @param args - Arguments passed to Cache.set() * @returns Promise resolving to true if successful * * @example * ```typescript * import { writeCache } from "fortify2-js"; * * await writeCache('user:profile', userData, { ttl: 1800000 }); // 30 min * ``` * * @since 4.2.2 */ declare const writeCache: (...args: Parameters<typeof Cache.set>) => Promise<boolean>; /** * Get memory cache performance statistics * * Returns comprehensive statistics including hit rates, memory usage, * and performance metrics for the default cache instance. * * @returns Current cache statistics * * @example * ```typescript * import { getCacheStats } from "fortify2-js"; * * const stats = getCacheStats(); * console.log(`Hit rate: ${stats.hitRate}%`); * console.log(`Memory usage: ${stats.memoryUsage} bytes`); * ``` * * @since 4.2.2 */ declare const getCacheStats: () => CacheStats; /** * Remove entry from memory cache * * Immediately removes a cache entry and frees associated memory. * Safe to call on non-existent keys. * * @param key - Cache key to remove * @returns Promise that resolves when deletion is complete * * @example * ```typescript * import { expireCache } from "fortify2-js"; * * await expireCache('session:expired123'); * console.log('Session removed from cache'); * ``` * * @since 4.2.2 */ declare const expireCache: (key: string) => Promise<void>; /** * Clear all memory cache entries * * Removes all cached data and resets statistics. * Use with caution in production environments. * * @returns Promise that resolves when cache is cleared * * @example * ```typescript * import { clearAllCache } from "fortify2-js"; * * await clearAllCache(); * console.log('Memory cache cleared'); * ``` * * @since 4.2.2 */ declare const clearAllCache: () => Promise<void>; /** * Legacy filepath function * @deprecated use generateFilePath instead */ declare const filepath: (origin: string) => string; /** * Create optimal cache instance based on performance requirements * * Factory function that creates the most suitable cache instance for your use case. * Automatically configures security settings and performance optimizations. * * @param options - Cache configuration options * @param options.type - Cache strategy: 'memory' (fastest), 'file' (persistent), 'hybrid' (balanced) * @param options.config - Optional file cache configuration (ignored for memory-only) * @returns Configured cache instance optimized for the specified requirements * * @example * ```typescript * import { createOptimalCache } from "fortify2-js"; * * // Ultra-fast memory cache for session data * const sessionCache = createOptimalCache({ type: 'memory' }); * * // Persistent file cache for application data * const appCache = createOptimalCache({ * type: 'file', * config: { * directory: './app-cache', * encrypt: true, * maxCacheSize: 100 * 1024 * 1024 // 100MB * } * }); * * // Hybrid cache for optimal performance and persistence * const hybridCache = createOptimalCache({ * type: 'hybrid', * config: { encrypt: true, compress: true } * }); * * // Use hybrid cache (memory-first with file backup) * await hybridCache.set('user:123', userData); * const user = await hybridCache.get('user:123'); // Served from memory * ``` * * @since 4.2.2 */ declare const createOptimalCache: (options: { type: "memory" | "file" | "hybrid"; config?: Partial<FileCacheOptions>; }) => SIMC | FileCache | { memory: SIMC; file: FileCache; get(key: string): Promise<CachedData | null>; set(key: string, value: CachedData, options?: any): Promise<boolean>; }; /** * Legacy file cache function names for backward compatibility * @deprecated Use the new function names for better clarity */ declare const deleteFileCache: (key: string) => Promise<boolean>; /** * Cache module version and metadata * @since 4.2.0 */ declare const CACHE_VERSION = "4.2.3"; declare const CACHE_BUILD_DATE = "2025-04-06"; interface ClusterConfig { enabled?: boolean; workers?: number | "auto"; processManagement?: { respawn?: boolean; maxRestarts?: number; restartDelay?: number; gracefulShutdownTimeout?: number; killTimeout?: number; zombieDetection?: boolean; memoryThreshold?: string; cpuThreshold?: number; }; healthCheck?: { enabled?: boolean; interval?: number; timeout?: number; maxFailures?: number; endpoint?: string; customCheck?: (worker: any) => Promise<boolean>; }; loadBalancing?: { strategy?: "round-robin" | "least-connections" | "ip-hash" | "weighted" | "adaptive" | "least-response-time" | "resource-based"; weights?: number[]; stickySession?: boolean; sessionAffinityKey?: string; circuitBreakerThreshold?: number; circuitBreakerTimeout?: number; }; ipc?: { enabled?: boolean; channel?: string; messageQueue?: { maxSize?: number; timeout?: number; }; broadcast?: boolean; events?: { [eventName: string]: (data: any, workerId: string) => void; }; }; autoScaling?: { enabled?: boolean; minWorkers?: number; maxWorkers?: number; scaleUpThreshold?: { cpu?: number; memory?: number; responseTime?: number; queueLength?: number; }; scaleDownThreshold?: { cpu?: number; memory?: number; idleTime?: number; }; cooldownPeriod?: number; scaleStep?: number; }; resources?: { maxMemoryPerWorker?: string; maxCpuPerWorker?: number; priorityLevel?: "low" | "normal" | "high" | "critical"; fileDescriptorLimit?: number; networkConnections?: { max?: number; timeout?: number; }; }; monitoring?: { enabled?: boolean; collectMetrics?: boolean; metricsInterval?: number; logLevel?: "error" | "warn" | "info" | "debug" | "trace"; logWorkerEvents?: boolean; logPerformance?: boolean; customMetrics?: { [metricName: string]: (workerId: string) => number; }; }; errorHandling?: { uncaughtException?: "restart" | "log" | "ignore"; unhandledRejection?: "restart" | "log" | "ignore"; customErrorHandler?: (error: Error, workerId: string) => void; errorThreshold?: number; crashRecovery?: { enabled?: boolean; saveState?: boolean; stateStorage?: "memory" | "redis" | "file"; }; }; security?: { isolateWorkers?: boolean; sandboxMode?: boolean; resourceLimits?: boolean; preventForkBombs?: boolean; workerAuthentication?: boolean; encryptIPC?: boolean; }; development?: { hotReload?: boolean; debugMode?: boolean; profiling?: boolean; inspectPorts?: number[]; }; resilience?: { circuitBreaker?: { enabled?: boolean; failureThreshold?: number; recoveryTimeout?: number; halfOpenRequests?: number; }; bulkhead?: { enabled?: boolean; maxConcurrentRequests?: number; queueSize?: number; }; timeout?: { enabled?: boolean; requestTimeout?: number; healthCheckTimeout?: number; }; retryPolicy?: { enabled?: boolean; maxRetries?: number; backoffStrategy?: "linear" | "exponential" | "constant"; baseDelay?: number; maxDelay?: number; }; }; advanced?: { stateSync?: { enabled?: boolean; strategy?: "redis" | "gossip" | "consensus"; syncInterval?: number; }; deployment?: { rollingUpdates?: boolean; maxUnavailable?: number; maxSurge?: number; healthCheckGracePeriod?: number; }; networking?: { tcpNoDelay?: boolean; keepAlive?: boolean; keepAliveInitialDelay?: number; }; }; persistence?: { enabled?: boolean; type?: "redis" | "file" | "memory" | "custom"; redis?: { host?: string; port?: number; password?: string; db?: number; keyPrefix?: string; ttl?: number; }; file?: { path?: string; backup?: boolean; maxBackups?: number; compression?: boolean; }; memory?: { maxSize?: number; ttl?: number; }; custom?: { saveHandler?: (state: any) => Promise<void>; loadHandler?: () => Promise<any>; }; }; } interface RequestPattern { id: string; route: string; method: string; frequency: number; avgResponseTime: number; cacheHitRate: number; complexity: number; lastSeen: Date; optimizationLevel: "none" | "basic" | "advanced" | "ultra"; } interface CompiledRoute { pattern: RequestPattern; compiledHandler: Function; optimizedMiddleware: Function[]; cacheStrategy: "memory" | "redis" | "hybrid" | "skip"; executionPath: "fast" | "standard" | "complex"; precomputedData?: any; } interface DynamicResponseGenerator { pattern: string | RegExp; generator: (req: Request, pattern: RequestPattern) => Promise<any> | any; priority?: number; } interface ResponseTemplate { route: string; method: string; template: any; cacheTTL?: number; } interface PreCompilerConfig { enabled: boolean; learningPeriod: number; optimizationThreshold: number; maxCompiledRoutes: number; aggressiveOptimization: boolean; predictivePreloading: boolean; customResponseGenerators?: DynamicResponseGenerator[]; responseTemplates?: ResponseTemplate[]; systemInfo?: { serviceName?: string; version?: string; environment?: string; customHealthData?: () => any; customStatusData?: () => any; }; } /** * Request Pre-Compiler * * Revolutionary optimization system that analyzes request patterns and pre-compiles * optimized execution paths for ultra-fast request processing (<1ms overhead). * * Key Features: * - Pattern recognition and route optimization * - Pre-compiled execution paths * - Intelligent caching strategies * - Zero-allocation hot paths * - Predictive request handling */ declare class RequestPreCompiler { private patterns; private compiledRoutes; private cache; private config; private learningMode; private optimizationStats; private customResponseGenerators; private responseTemplates; private readonly fastPathContext; constructor(cache: SecureCacheAdapter, config?: Partial<PreCompilerConfig>); /** * Analyze incoming request and update patterns */ analyzeRequest(req: Request, res: Response, next: NextFunction): void; /** * Get optimized handler for request if available */ getOptimizedHandler(req: Request): CompiledRoute | null; /** * Pre-compile optimized execution paths for hot routes */ private compileOptimizedRoutes; /** * Compile individual route for maximum performance */ private compileRoute; /** * Create ultra-fast optimized handler */ private createOptimizedHandler; /** * Handle ultra-fast execution path (<0.5ms target) */ private handleUltraFastPath; /** * Handle standard optimized path with template processing and fallback */ private handleOptimizedPath; /** * Process template data with parameter substitution */ private processTemplateData; /** * Generate dynamic response for known patterns when precomputed data is not available * Library-agnostic implementation with configurable response generators */ private generateDynamicResponse; /** * Generate pattern key for request classification */ private generatePatternKey; /** * Generate fast cache key with minimal overhead */ private generateFastCacheKey; /** * Hash query parameters for pattern matching */ private hashQueryParams; /** * Create new request pattern */ private createNewPattern; /** * Calculate optimization potential for a pattern */ private calculateOptimizationPotential; /** * Calculate route complexity */ private calculateRouteComplexity; /** * Calculate recency score */ private calculateRecencyScore; /** * Determine optimal cache strategy */ private determineCacheStrategy; /** * Determine execution path */ private determineExecutionPath; /** * Create optimized middleware stack */ private createOptimizedMiddleware; /** * Pre-compute route data for ultra-fast responses * Generates static/semi-static response data for instant serving */ private precomputeRouteData; /** * Update optimization statistics */ private updateOptimizationStats; /** * Get optimization statistics */ getStats(): { patternsLearned: number; routesCompiled: number; optimizationRate: number; customGenerators: number; responseTemplates: number; totalRequests: number; optimizedRequests: number; avgOptimizationGain: number; compilationTime: number; }; /** * Register a custom dynamic response generator * Allows developers to extend the optimization system with their own response logic */ registerResponseGenerator(generator: DynamicResponseGenerator): void; /** * Register a response template for pre-computation * Allows developers to define static response structures for their routes */ registerResponseTemplate(template: ResponseTemplate): void; /** * Remove a custom response generator */ unregisterResponseGenerator(pattern: string | RegExp): void; /** * Clear all custom configurations */ clearCustomConfigurations(): void; /** * Force immediate compilation of registered templates and generators * Useful for testing or when you want immediate optimization without waiting for learning period */ forceCompileTemplates(): void; /** * Initialize custom response generators from configuration */ private initializeCustomGenerators; /** * Initialize response templates from configuration */ private initializeResponseTemplates; } type RoutePattern = string | RegExp; interface