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 OptimizedRoute {
    pattern: RoutePattern;
    methods?: string[];
    handler?: (req: Request, res: Response) => any | Promise<any>;
    schema?: any;
    cacheTTL?: number;
    priority?: number;
    enableCache?: boolean;
    precompile?: boolean;
}

type LogLevel$1 = "silent" | "error" | "warn" | "info" | "debug" | "verbose";
type LogComponent = "middleware" | "server" | "cache" | "cluster" | "performance" | "fileWatcher" | "plugins" | "security" | "monitoring" | "routes" | "userApp" | "typescript" | "console" | "other" | "router";
type LogType = "startup" | "warnings" | "errors" | "performance" | "debug" | "hotReload" | "portSwitching";

/**
 * Type definitions for Console Interception System
 */

/**
 * Enhanced preserve option configuration
 * Provides fine-grained control over console output behavior
 */
interface PreserveOption {
    enabled: boolean;
    mode: "original" | "intercepted" | "both" | "none";
    showPrefix: boolean;
    allowDuplication: boolean;
    customPrefix?: string;
    separateStreams: boolean;
    onlyUserApp: boolean;
    colorize: boolean;
}
interface ConsoleEncryptionConfig {
    enabled?: boolean;
    algorithm?: "aes-128-gcm" | "aes-192-gcm" | "aes-256-gcm";
    keyDerivation?: "pbkdf2" | "scrypt" | "argon2";
    iterations?: number;
    saltLength?: number;
    ivLength?: number;
    tagLength?: number;
    encoding?: "base64" | "hex";
    key?: string;
    displayMode?: "readable" | "encrypted" | "both";
    showEncryptionStatus?: boolean;
    externalLogging?: {
        enabled?: boolean;
        endpoint?: string;
        headers?: Record<string, string>;
        batchSize?: number;
        flushInterval?: number;
    };
}
interface ConsoleInterceptionConfig {
    enabled: boolean;
    interceptMethods: readonly ("log" | "error" | "warn" | "info" | "debug" | "trace")[];
    preserveOriginal: boolean | PreserveOption;
    filterUserCode: boolean;
    performanceMode: boolean;
    sourceMapping: boolean;
    stackTrace: boolean;
    maxInterceptionsPerSecond: number;
    encryption?: ConsoleEncryptionConfig;
    filters: {
        minLevel: "debug" | "info" | "warn" | "error";
        maxLength: number;
        includePatterns: readonly string[];
        excludePatterns: readonly string[];
        userAppPatterns?: readonly string[];
        systemPatterns?: readonly string[];
        categoryBehavior?: {
            userApp?: "intercept" | "passthrough" | "both";
            system?: "intercept" | "passthrough" | "both";
            unknown?: "intercept" | "passthrough" | "both";
        };
    };
    fallback: {
        onError: "silent" | "console" | "throw";
        gracefulDegradation: boolean;
        maxErrors: number;
    };
}
interface ConsoleInterceptionStats {
    totalInterceptions: number;
    interceptionsPerSecond: number;
    errorCount: number;
    lastInterceptionTime: number;
    methodCounts: Record<string, number>;
    averageOverhead: number;
    isActive: boolean;
}

/**
 * FortifyJS Express Types
 * Core type definitions for Express features (excluding cluster types)
 */

type DeepPartial<T> = {
    [K in keyof T]?: T[K] extends infer U ? U extends object ? U extends readonly any[] ? U extends readonly (infer V)[] ? readonly DeepPartial<V>[] : U : U extends Function ? U : DeepPartial<U> : U : never;
};
interface ServerConfig {
    port?: number;
    host?: string;
    environment?: "development" | "production" | "test";
    autoPortSwitch?: {
        enabled?: boolean;
        maxAttempts?: number;
        startPort?: number;
        portRange?: [number, number];
        strategy?: "increment" | "random" | "predefined";
        predefinedPorts?: number[];
        onPortSwitch?: (originalPort: number, newPort: number) => void;
    };
    security?: SecurityConfig;
    cache?: CacheConfig;
    monitoring?: PerformanceConfig;
    middleware?: MiddlewareConfig[];
    ssl?: SSLConfig;
    cors?: CORSConfig;
    rateLimit?: RateLimitConfig;
    compression?: CompressionConfig;
    logging?: LoggingConfig;
    cluster?: {
        enabled?: boolean;
        config?: ClusterConfig;
    };
}
interface SecurityConfig {
    level?: "basic" | "enhanced" | "maximum";
    csrf?: boolean;
    helmet?: boolean;
    xss?: boolean;
    sqlInjection?: boolean;
    bruteForce?: boolean;
    encryption?: {
        algorithm?: string;
        keySize?: number;
    };
    authentication?: {
        jwt?: JWTConfig;
        session?: SessionConfig;
    };
}
interface CacheConfig {
    type?: "memory" | "redis" | "hybrid" | "distributed";
    redis?: RedisConfig;
    memory?: MemoryConfig;
    ttl?: number;
    maxSize?: number;
    maxEntries?: number;
    compression?: boolean;
    encryption?: boolean;
    serialization?: "json" | "msgpack" | "protobuf";
    strategies?: CacheStrategy[];
    singleton?: boolean;
    performance?: CachePerformanceConfig;
    security?: CacheSecurityConfig;
    monitoring?: CacheMonitoringConfig;
    resilience?: CacheResilienceConfig;
}
interface RedisConfig {
    host?: string;
    port?: number;
    password?: string;
    db?: number;
    cluster?: boolean;
    nodes?: Array<{
        host: string;
        port: number;
    }>;
    shards?: Array<{
        host: string;
        port: number;
        weight?: number;
    }>;
    options?: {
        retryDelayOnFailover?: number;
        maxRetriesPerRequest?: number;
        lazyConnect?: boolean;
    };
    pool?: {
        min?: number;
        max?: number;
        acquireTimeoutMillis?: number;
        idleTimeoutMillis?: number;
    };
    sentinel?: {
        enabled?: boolean;
        masters?: string[];
        sentinels?: Array<{
            host: string;
            port: number;
        }>;
    };
}
interface MemoryConfig {
    maxSize?: number;
    algorithm?: "lru" | "lfu" | "fifo";
    evictionPolicy?: "lru" | "lfu" | "fifo" | "ttl";
    checkPeriod?: number;
    preallocation?: boolean;
}
interface PerformanceConfig {
    enabled?: boolean;
    metrics?: string[];
    interval?: number;
    alerts?: AlertConfig[];
    dashboard?: boolean;
    export?: {
        custom?: (metrics: any) => void;
    };
}
interface CachePerformanceConfig {
    batchSize?: number;
    compressionThreshold?: number;
    hotDataThreshold?: number;
    prefetchEnabled?: boolean;
    asyncWrite?: boolean;
    pipeline?: boolean;
    connectionPooling?: boolean;
}
interface CacheSecurityConfig {
    encryption?: boolean;
    keyRotation?: boolean;
    accessMonitoring?: boolean;
    sanitization?: boolean;
    auditLogging?: boolean;
}
interface CacheMonitoringConfig {
    enabled?: boolean;
    metricsInterval?: number;
    alertThresholds?: {
        memoryUsage?: number;
        hitRate?: number;
        errorRate?: number;
        latency?: number;
    };
    detailed?: boolean;
}
interface CacheResilienceConfig {
    retryAttempts?: number;
    retryDelay?: number;
    circuitBreaker?: boolean;
    fallback?: boolean;
    healthCheck?: boolean;
}
interface CacheMetrics {
    hits: number;
    misses: number;
    sets: number;
    deletes: number;
    errors: number;
    operations: number;
    hitRate?: number;
    missRate?: number;
    errorRate?: number;
    totalMemory?: number;
}
type MiddlewareFunction = (req: EnhancedRequest, res: EnhancedResponse, next: NextFunction) => Promise<void> | void;
interface EnhancedRequest extends Request {
    cache: {
        get: (key: string) => Promise<any>;
        set: (key: string, value: any, ttl?: number) => Promise<void>;
        del: (key: string) => Promise<void>;
        tags: (tags: string[]) => Promise<void>;
    };
    security: {
        encrypt: (data: any) => Promise<string>;
        decrypt: (data: string) => Promise<any>;
        hash: (data: string) => string;
        verify: (data: string, hash: string) => boolean;
        generateToken: () => string;
        sessionKey: string;
    };
    performance: {
        start: () => void;
        end: () => number;
        mark: (name: string) => void;
        measure: (name: string, start: string, end: string) => number;
    };
    validate: {
        body: (schema: any) => ValidationResult$1;
        query: (schema: any) => ValidationResult$1;
        params: (schema: any) => ValidationResult$1;
    };
    user?: UserContext;
    session?: SessionData;
}
interface EnhancedResponse extends Response {
    cache: {
        set: (ttl?: number, tags?: string[]) => void;
        invalidate: (tags: string[]) => Promise<void>;
    };
    security: {
        encrypt: (data: any) => EnhancedResponse;
        sign: (data: any) => EnhancedResponse;
    };
    performance: {
        timing: (name: string, value: number) => void;
        metric: (name: string, value: number) => void;
    };
    success: (data?: any, message?: string) => void;
    error: (error: string | Error, code?: number) => void;
    paginated: (data: any[], pagination: PaginationInfo) => void;
}
type CacheBackendStrategy = "memory" | "redis" | "hybrid" | "distributed";
interface CacheStrategy {
    name: string;
    condition: (req: Request) => boolean;
    ttl: number;
    tags?: string[];
}
interface AlertConfig {
    metric: string;
    threshold: number;
    action: "log" | "email" | "webhook" | "custom";
    target?: string;
    cooldown?: number;
}
interface ValidationResult$1 {
    valid: boolean;
    errors: string[];
    data: any;
}
interface UserContext {
    id: string;
    roles: string[];
    permissions: string[];
    metadata: Record<string, any>;
}
interface SessionData {
    id: string;
    userId?: string;
    data: Record<string, any>;
    expires: Date;
}
interface PaginationInfo {
    page: number;
    limit: number;
    total: number;
    pages: number;
}
interface MiddlewareConfig {
    name: string;
    handler: MiddlewareFunction;
    order?: number;
    routes?: string[];
}
interface SSLConfig {
    key: string;
    cert: string;
    ca?: string;
    passphrase?: string;
}
interface CORSConfig {
    origin?: string | string[] | boolean;
    methods?: string[];
    allowedHeaders?: string[];
    credentials?: boolean;
}
interface RateLimitConfig {
    windowMs?: number;
    max?: number;
    message?: string;
    standardHeaders?: boolean;
    legacyHeaders?: boolean;
}
type MiddlewarePriority = "critical" | "high" | "normal" | "low";
interface MiddlewareConfiguration {
    rateLimit?: boolean | RateLimitMiddlewareOptions;
    cors?: boolean | CorsMiddlewareOptions;
    compression?: boolean | CompressionMiddlewareOptions;
    security?: boolean | SecurityMiddlewareOptions;
    helmet?: boolean;
    customHeaders?: Record<string, string>;
    enableOptimization?: boolean;
    enableCaching?: boolean;
    enablePerformanceTracking?: boolean;
}
interface SecurityMiddlewareOptions {
    helmet?: boolean | any;
    cors?: boolean | CorsMiddlewareOptions;
    rateLimit?: boolean | RateLimitMiddlewareOptions;
    customHeaders?: Record<string, string>;
    csrfProtection?: boolean;
    contentSecurityPolicy?: boolean | any;
    hsts?: boolean | any;
}
interface CompressionMiddlewareOptions {
    enabled?: boolean;
    level?: number;
    threshold?: number;
    filter?: (req: Request, res: Response) => boolean;
    chunkSize?: number;
    windowBits?: number;
    memLevel?: number;
    strategy?: number;
}
interface RateLimitMiddlewareOptions {
    enabled?: boolean;
    windowMs?: number;
    max?: number;
    message?: string;
    standardHeaders?: boolean;
    legacyHeaders?: boolean;
    keyGenerator?: (req: Request) => string;
    skip?: (req: Request) => boolean;
    onLimitReached?: (req: Request, res: Response) => void;
}
interface CorsMiddlewareOptions {
    enabled?: boolean;
    origin?: string | string[] | boolean | ((origin: string, callback: (err: Error | null, allow?: boolean) => void) => void);
    methods?: string[];
    allowedHeaders?: string[];
    exposedHeaders?: string[];
    credentials?: boolean;
    maxAge?: number;
    preflightContinue?: boolean;
    optionsSuccessStatus?: number;
}
interface MiddlewareInfo {
    name: string;
    priority: MiddlewarePriority;
    enabled: boolean;
    order: number;
    routes?: string[];
    executionCount: number;
    averageExecutionTime: number;
    lastExecuted?: Date;
    cacheEnabled?: boolean;
    optimized?: boolean;
}
interface MiddlewareStats {
    totalMiddleware: number;
    enabledMiddleware: number;
    totalExecutions: number;
    averageExecutionTime: number;
    cacheHitRate: number;
    optimizationRate: number;
    byPriority: Record<MiddlewarePriority, number>;
    byType: Record<string, MiddlewareInfo>;
    performance: {
        fastestMiddleware: string;
        slowestMiddleware: string;
        mostUsedMiddleware: string;
        cacheEfficiency: number;
    };
}
interface CustomMiddleware {
    name: string;
    handler: RequestHandler;
    priority?: MiddlewarePriority;
    routes?: string[];
    enabled?: boolean;
    cacheable?: boolean;
    ttl?: number;
    metadata?: Record<string, any>;
}
interface MiddlewareAPIInterface {
    register: (middleware: CustomMiddleware | RequestHandler, options?: {
        name?: string;
        priority?: MiddlewarePriority;
        routes?: string[];
        cacheable?: boolean;
        ttl?: number;
    }) => MiddlewareAPIInterface;
    unregister: (id: string) => MiddlewareAPIInterface;
    enable: (id: string) => MiddlewareAPIInterface;
    disable: (id: string) => MiddlewareAPIInterface;
    getInfo: (id?: string) => MiddlewareInfo | MiddlewareInfo[];
    getStats: () => MiddlewareStats;
    getConfig: () => MiddlewareConfiguration;
    clear: () => MiddlewareAPIInterface;
    optimize: () => Promise<MiddlewareAPIInterface>;
}
interface CompressionConfig {
    enabled?: boolean;
    level?: number;
    threshold?: number;
    filter?: (req: Request, res: Response) => boolean;
}
interface LoggingConfig {
    level?: "error" | "warn" | "info" | "debug";
    format?: "json" | "combined" | "common" | "dev";
    destination?: "console" | "file" | "both";
    requests?: boolean;
    errors?: boolean;
    file?: {
        path: string;
        maxSize?: string;
        maxFiles?: number;
    };
}
interface JWTConfig {
    secret: string;
    expiresIn?: string;
    algorithm?: string;
    issuer?: string;
    audience?: string;
}
interface SessionConfig {
    secret: string;
    name?: string;
    cookie?: {
        maxAge?: number;
        secure?: boolean;
        httpOnly?: boolean;
        sameSite?: boolean | "lax" | "strict" | "none";
    };
    store?: "memory" | "redis" | "custom";
}
interface ServerOptions {
    env?: "development" | "production" | "test";
    cache?: {
        strategy?: "auto" | "memory" | "redis" | "hybrid" | "distributed";
        ttl?: number;
        redis?: {
            host?: string;
            port?: number;
            password?: string;
            cluster?: boolean;
            nodes?: Array<{
                host: string;
                port: number;
            }>;
        };
        memory?: {
            maxSize?: number;
            algorithm?: "lru" | "lfu" | "fifo";
        };
        enabled?: boolean;
    };
    security?: {
        encryption?: boolean;
        accessMonitoring?: boolean;
        sanitization?: boolean;
        auditLogging?: boolean;
        cors?: boolean;
        helmet?: boolean;
    };
    performance?: {
        compression?: boolean;
        batchSize?: number;
        connectionPooling?: boolean;
        asyncWrite?: boolean;
        prefetch?: boolean;
        optimizationEnabled?: boolean;
        requestClassification?: boolean;
        predictivePreloading?: boolean;
        aggressiveCaching?: boolean;
        parallelProcessing?: boolean;
        preCompilerEnabled?: boolean;
        learningPeriod?: number;
        optimizationThreshold?: number;
        aggressiveOptimization?: boolean;
        maxCompiledRoutes?: number;
        ultraFastRulesEnabled?: boolean;
        staticRouteOptimization?: boolean;
        patternRecognitionEnabled?: boolean;
        cacheWarmupEnabled?: boolean;
        warmupOnStartup?: boolean;
        precomputeCommonResponses?: boolean;
        customHealthData?: () => any | Promise<any>;
        customStatusData?: () => any | Promise<any>;
    };
    monitoring?: {
        enabled?: boolean;
        healthChecks?: boolean;
        metrics?: boolean;
        detailed?: boolean;
        alertThresholds?: {
            memoryUsage?: number;
            hitRate?: number;
            errorRate?: number;
            latency?: number;
        };
    };
    server?: {
        port?: number;
        host?: string;
        trustProxy?: boolean;
        jsonLimit?: string;
        urlEncodedLimit?: string;
        enableMiddleware?: boolean;
        logPerfomances?: boolean;
        serviceName?: string;
        version?: string;
        autoPortSwitch?: {
            enabled?: boolean;
            maxAttempts?: number;
            startPort?: number;
            portRange?: [number, number];
            strategy?: "increment" | "random" | "predefined";
            predefinedPorts?: number[];
            onPortSwitch?: (originalPort: number, newPort: number) => void;
        };
    };
    cluster?: {
        enabled?: boolean;
        config?: Omit<ClusterConfig, "enabled">;
    };
    fileWatcher?: {
        enabled?: boolean;
        watchPaths?: string[];
        ignorePaths?: string[];
        extensions?: string[];
        debounceMs?: number;
        restartDelay?: number;
        maxRestarts?: number;
        gracefulShutdown?: boolean;
        verbose?: boolean;
        typeCheck?: {
            enabled?: boolean;
            configFile?: string;
            checkOnSave?: boolean;
            checkBeforeRestart?: boolean;
            showWarnings?: boolean;
            showInfos?: boolean;
            maxErrors?: number;
            failOnError?: boolean;
            excludePatterns?: string[];
            includePatterns?: string[];
            verbose?: boolean;
        };
        typescript?: {
            enabled?: boolean;
            runner?: "auto" | "tsx" | "ts-node" | "bun" | "node" | string;
            runnerArgs?: string[];
            fallbackToNode?: boolean;
            autoDetectRunner?: boolean;
        };
    };
    middleware?: MiddlewareConfiguration;
    logging?: {
        enabled?: boolean;
        level?: "silent" | "error" | "warn" | "info" | "debug" | "verbose";
        components?: {
            server?: boolean;
            cache?: boolean;
            cluster?: boolean;
            performance?: boolean;
            fileWatcher?: boolean;
            plugins?: boolean;
            security?: boolean;
            monitoring?: boolean;
            routes?: boolean;
            userApp?: boolean;
            console?: boolean;
            other?: boolean;
            middleware?: boolean;
            router?: boolean;
            typescript?: boolean;
        };
        types?: {
            startup?: boolean;
            warnings?: boolean;
            errors?: boolean;
            performance?: boolean;
            debug?: boolean;
            hotReload?: boolean;
            portSwitching?: boolean;
        };
        format?: {
            timestamps?: boolean;
            colors?: boolean;
            prefix?: boolean;
            compact?: boolean;
        };
        consoleInterception?: DeepPartial<ConsoleInterceptionConfig>;
        customLogger?: (level: LogLevel$1, component: LogComponent, message: string, ...args: any[]) => void;
    };
    router?: {
        enabled?: boolean;
        precompileCommonRoutes?: boolean;
        enableSecurity?: boolean;
        enableCaching?: boolean;
        warmUpOnStart?: boolean;
        performance?: {
            targetResponseTime?: number;
            complexRouteTarget?: number;
            enableProfiling?: boolean;
            enableOptimizations?: boolean;
        };
        security?: {
            enableValidation?: boolean;
            enableSanitization?: boolean;
            enableRateLimit?: boolean;
            defaultRateLimit?: number;
        };
        cache?: {
            enabled?: boolean;
            defaultTTL?: number;
            maxCacheSize?: number;
        };
    };
    golang?: {
        enabled?: boolean;
        goPort?: number;
        workers?: number;
        cacheSize?: number;
        timeout?: number;
        autoStart?: boolean;
        binaryPath?: string;
        logLevel?: 'debug' | 'info' | 'warn' | 'error';
        features?: {
            fastRouting?: boolean;
            jsonOptimization?: boolean;
            memoryPooling?: boolean;
            zeroAllocation?: boolean;
        };
        routingStrategy?: {
            useForApiRoutes?: boolean;
            useForGetRequests?: boolean;
            useForFastRoutes?: boolean;
            customMatcher?: (req: any) => boolean;
        };
    };
}
interface RouteOptions {
    cache?: {
        enabled?: boolean;
        ttl?: number;
        key?: string | ((req: Request) => string);
        tags?: string[];
        invalidateOn?: string[];
        strategy?: "memory" | "redis" | "hybrid";
    };
    security?: {
        auth?: boolean;
        roles?: string[];
        encryption?: boolean;
        sanitization?: boolean;
    };
    performance?: {
        compression?: boolean;
        timeout?: number;
    };
}
type RedirectMode = "transparent" | "message" | "redirect";
interface RedirectStats {
    totalRequests: number;
    successfulRedirects: number;
    failedRedirects: number;
    averageResponseTime: number;
    lastRequestTime?: Date;
    startTime: Date;
    uptime: number;
    requestTimes: number[];
}
interface RedirectOptions {
    /**
     * Redirect behavior mode
     * - transparent: Proxy requests seamlessly (default)
     * - message: Show custom message with new URL
     * - redirect: Send HTTP 301/302 redirect responses
     */
    mode?: RedirectMode;
    /**
     * Custom message to display when mode is 'message'
     */
    customMessage?: string;
    /**
     * HTTP status code for redirect mode (301 or 302)
     */
    redirectStatusCode?: 301 | 302;
    /**
     * Enable/disable redirect logging
     */
    enableLogging?: boolean;
    /**
     * Enable/disable usage statistics tracking
     */
    enableStats?: boolean;
    /**
     * Auto-disconnect after specified time (in milliseconds)
     */
    autoDisconnectAfter?: number;
    /**
     * Auto-disconnect after specified number of requests
     */
    autoDisconnectAfterRequests?: number;
    /**
     * Custom response headers to add to all responses
     */
    customHeaders?: Record<string, string>;
    /**
     * Custom HTML template for message mode
     */
    customHtmlTemplate?: string;
    /**
     * Timeout for proxy requests in milliseconds
     */
    proxyTimeout?: number;
    /**
     * Enable CORS headers for cross-origin requests
     */
    enableCors?: boolean;
    /**
     * Custom error message for failed redirects
     */
    customErrorMessage?: string;
    /**
     * Rate limiting for redirect requests
     */
    rateLimit?: {
        maxRequests: number;
        windowMs: number;
    };
}
interface RedirectServerInstance {
    fromPort: number;
    toPort: number;
    options: RedirectOptions;
    server: any;
    stats: RedirectStats;
    disconnect: () => Promise<boolean>;
    getStats: () => RedirectStats;
    updateOptions: (newOptions: Partial<RedirectOptions>) => void;
}
interface UltraFastApp extends Express {
    cache: SecureCacheAdapter;
    getWithCache: (path: string, options: RouteOptions, handler: RequestHandler) => void;
    postWithCache: (path: string, options: RouteOptions, handler: RequestHandler) => void;
    putWithCache: (path: string, options: RouteOptions, handler: RequestHandler) => void;
    deleteWithCache: (path: string, options: RouteOptions, handler: RequestHandler) => void;
    invalidateCache: (pattern: string) => Promise<void>;
    getCacheStats: () => Promise<any>;
    warmUpCache: (data: Array<{
        key: string;
        value: any;
        ttl?: number;
    }>) => Promise<void>;
    start: (port?: number, callback?: () => void) => Promise<Server> | Server;
    waitForReady: () => Promise<void>;
    getPort: () => number;
    forceClosePort: (port: number) => Promise<boolean>;
    redirectFromPort: (fromPort: number, toPort: number, options?: RedirectOptions) => Promise<RedirectServerInstance | boolean>;
    getRedirectInstance: (fromPort: number) => RedirectServerInstance | null;
    getAllRedirectInstances: () => RedirectServerInstance[];
    disconnectRedirect: (fromPort: number) => Promise<boolean>;
    disconnectAllRedirects: () => Promise<boolean>;
    getRedirectStats: (fromPort: number) => RedirectStats | null;
    getRequestPreCompiler: () => RequestPreCompiler;
    getConsoleInterceptor: () => any;
    enableConsoleInterception: () => void;
    disableConsoleInterception: () => void;
    getConsoleStats: () => any;
    resetConsoleStats: () => void;
    getFileWatcherStatus: () => any;
    getFileWatcherStats: () => any;
    stopFileWatcher: () => Promise<void>;
    checkTypeScript: (files?: string[]) => Promise<any>;
    getTypeScriptStatus: () => any;
    enableTypeScriptChecking: () => void;
    disableTypeScriptChecking: () => void;
    enableConsoleEncryption: (key?: string) => void;
    disableConsoleEncryption: () => void;
    encrypt: (key: string) => void;
    setConsoleEncryptionKey: (key: string) => void;
    setConsoleEncryptionDisplayMode: (displayMode: "readable" | "encrypted" | "both", showEncryptionStatus?: boolean) => void;
    getEncryptedLogs: () => string[];
    restoreConsoleFromEncrypted: (encryptedData: string[], key: string) => Promise<string[]>;
    isConsoleEncryptionEnabled: () => boolean;
    getConsoleEncryptionStatus: () => {
        enabled: boolean;
        algorithm?: string;
        hasKey: boolean;
        externalLogging?: boolean;
    };
    ultraGet?: (path: string, options: any, handler: Function) => any;
    ultraPost?: (path: string, options: any, handler: Function) => any;
    ultraPut?: (path: string, options: any, handler: Function) => any;
    ultraDelete?: (path: string, options: any, handler: Function) => any;
    ultraRoutes?: (routes: Array<{
        method: string;
        path: string;
        options: any;
        handler: Function;
    }>) => any;
    getRouterStats?: () => any;
    getRouterInfo?: () => any;
    warmUpRoutes?: () => Promise<void>;
    resetRouterStats?: () => void;
    registerRouteTemplate?: (template: OptimizedRoute) => void;
    unregisterRouteTemplate?: (route: string | RegExp, method?: string) => void;
    registerOptimizationPattern?: (pattern: OptimizedRoute) => void;
    getOptimizerStats?: () => any;
    middleware: (config?: MiddlewareConfiguration) => MiddlewareAPIInterface;
    useSecure: (middleware: RequestHandler | RequestHandler[]) => UltraFastApp;
    usePerformance: (middleware: RequestHandler | RequestHandler[]) => UltraFastApp;
    useCached: (middleware: RequestHandler | RequestHandler[], ttl?: number) => UltraFastApp;
    getMiddleware: (name?: string) => MiddlewareInfo | MiddlewareInfo[];
    removeMiddleware: (name: string) => boolean;
    enableSecurity: (options?: SecurityMiddlewareOptions) => UltraFastApp;
    enableCompression: (options?: CompressionMiddlewareOptions) => UltraFastApp;
    enableRateLimit: (options?: RateLimitMiddlewareOptions) => UltraFastApp;
    enableCors: (options?: CorsMiddlewareOptions) => UltraFastApp;
    getMiddlewareStats: () => MiddlewareStats;
    scaleUp?: (count?: number) => Promise<void>;
    scaleDown?: (count?: number) => Promise<void>;
    autoScale?: () => Promise<void>;
    getClusterMetrics?: () => Promise<any>;
    getClusterHealth?: () => Promise<any>;
    getAllWorkers?: () => any[];
    getOptimalWorkerCount?: () => Promise<number>;
    restartCluster?: () => Promise<void>;
    stopCluster?: (graceful?: boolean) => Promise<void>;
    broadcastToWorkers?: (message: any) => Promise<void>;
    sendToRandomWorker?: (message: any) => Promise<void>;
    registerPlugin?: (plugin: any) => Promise<void>;
    unregisterPlugin?: (pluginId: string) => Promise<void>;
    getPlugin?: (pluginId: string) => any;
    getAllPlugins?: () => any[];
    getPluginsByType?: (type: any) => any[];
    getPluginStats?: (pluginId?: string) => any;
    getPluginRegistryStats?: () => any;
    getPluginEngineStats?: () => any;
    initializeBuiltinPlugins?: () => Promise<void>;
    getServerStats?: () => Promise<any>;
}

/**
 * Type definitions for the FortifyJS library
 */

/**
 * Security level enum
 */
declare enum SecurityLevel$1 {
    STANDARD = "standard",
    HIGH = "high",
    MAXIMUM = "maximum"
}
/**
 * Token type enum
 */
declare enum TokenType {
    GENERAL = "general",
    API_KEY = "api_key",
    SESSION = "session",
    JWT = "jwt",
    TOTP = "totp"
}
/**
 * Hash algorithm enum - can be used as values
 */
declare enum HashAlgorithm$2 {
    SHA256 = "sha256",
    SHA512 = "sha512",
    SHA3_256 = "sha3-256",
    SHA3_512 = "sha3-512",
    BLAKE3 = "blake3",
    BLAKE2B = "blake2b",
    BLAKE2S = "blake2s",
    PBKDF2 = "pbkdf2"
}
/**
 * Supported hash algorithms - accepts both string literals AND enum values
 *
 * Usage examples:
 * - String literal: algorithm: "sha256"
 * - Enum value: algorithm: HashAlgorithmEnum.SHA256
 * - Both are type-safe and supported!
 */
type HashAlgorithmType = "sha256" | "sha512" | "sha3-256" | "sha3-512" | "blake3" | "blake2b" | "blake2s" | "pbkdf2";
/**
 * Key derivation algorithm enum
 */
declare enum KeyDerivationAlgorithm {
    PBKDF2 = "pbkdf2",
    ARGON2 = "argon2",
    BALLOON = "balloon"
}
/**
 * Entropy source enum
 */
declare enum EntropySource {
    SYSTEM = "system",
    BROWSER = "browser",
    USER = "user",
    NETWORK = "network",
    COMBINED = "combined",
    CSPRNG = "csprng",
    MATH_RANDOM = "math_random",
    CUSTOM = "custom"
}
/**
 * Secure token options
 */
interface SecureTokenOptions {
    /**
     * Length of the token
     * @default 32
     */
    length?: number;
    /**
     * Include uppercase letters
     * @default true
     */
    includeUppercase?: boolean;
    /**
     * Include lowercase letters
     * @default true
     */
    includeLowercase?: boolean;
    /**
     * Include numbers
     * @default true
     */
    includeNumbers?: boolean;
    /**
     * Include symbols
     * @default false
     */
    includeSymbols?: boolean;
    /**
     * Exclude similar characters (e.g., 1, l, I, 0, O)
     * @default false
     */
    excludeSimilarCharacters?: boolean;
    /**
     * Entropy level
     * @default 'high'
     */
    entropy: "high" | "maximum" | "standard";
    maxValidityLength?: number;
}
/**
 * Hash options
 */
interface HashOptions {
    /**
     * Salt for the hash
     * If not provided, a random salt will be generated
     */
    salt?: string | Uint8Array;
    /**
     * Pepper for the hash (secret server-side value)
     */
    pepper?: string | Uint8Array;
    /**
     * Number of iterations
     * @default 10000
     */
    iterations?: number;
    /**
     * Hash algorithm
     * @default 'sha256'
     */
    algorithm?: HashAlgorithm$2 | HashAlgorithmType;
    /**
     * Output format ()
     * @default 'hex'
     */
    outputFormat?: EncodingHashType$1;
    /**
     * Output length in bytes
     * @default 32
     */
    outputLength?: number;
}
/**
 * Key derivation options
 */
interface KeyDerivationOptions {
    /**
     * Salt for key derivation
     * If not provided, a random salt will be generated
     */
    salt?: string | Uint8Array;
    /**
     * Number of iterations
     * @default 100000
     */
    iterations?: number;
    /**
     * Key derivation algorithm
     * @default 'pbkdf2'
     */
    algorithm?: KeyDerivationAlgorithm | string;
    /**
     * Hash function to use (for PBKDF2)
     * @default 'sha256'
     */
    hashFunction?: HashAlgorithm$2 | string;
    /**
     * Output length in bytes
     * @default 32
     */
    keyLength?: number;
    /**
     * Memory cost for memory-hard functions (in KB)
     * @default 65536 (64 MB)
     */
    memoryCost?: number;
    /**
     * Parallelism factor for memory-hard functions
     * @default 4
     */
    parallelism?: number;
}
/**
 * API key options
 */
interface APIKeyOptions {
    /**
     * Prefix for the API key
     * @default ''
     */
    prefix?: string;
    /**
     * Include timestamp in the API key
     * @default true
     */
    includeTimestamp?: boolean;
    /**
     * Length of the random part
     * @default 32
     */
    randomPartLength?: number;
    /**
     * Separator between parts
     * @default '_'
     */
    separator?: string;
    /**
     * Encoding type for the API key
     */
    encoding?: EncodingHashType$1;
}
/**
 * Session token options
 */
interface SessionTokenOptions {
    /**
     * User ID to include in the token
     */
    userId?: string | number;
    /**
     * IP address to include in the token
     */
    ipAddress?: string;
    /**
     * User agent to include in the token
     */
    userAgent?: string;
    /**
     * Expiration time in seconds
     * @default 3600 (1 hour)
     */
    expiresIn?: number;
}
/**
 * Middleware options
 */
interface MiddlewareOptions {
    /**
     * Custom headers to add to the response
     * @default {}
     */
    customHeaders?: Record<string, string>;
    /**
     * Callback function to handle rate limit exceeded
     */
    onRateLimit?: (req: any, res: any) => void;
    /**
     * Callback function to handle CSRF errors
     */
    onCSRFError?: (req: any, res: any) => void;
    /**
     * Callback function to handle errors
     */
    onError?: (req: any, res: any) => void;
    /**
     * Callback function to handle metrics
     */
    metricsHook?: (metrics: any) => void;
    /**
     * Enable CSRF protection
     * @default false
     */
    csrfProtection?: boolean;
    /**
     * Enable secure headers
     * @default true
     */
    secureHeaders?: boolean;
    /**
     * Enable rate limiting
     * @default true
     */
    rateLimit?: boolean | RateLimitMiddlewareOptions;
    /**
     * Maximum requests per minute
     * @default 100
     */
    maxRequestsPerMinute?: number;
    /**
     * Secret for token generation
     * If not provided, a random secret will be generated (use Random.getRandomBytes)
     */
    tokenSecret?: string;
    /**
     * Name of the CSRF cookie
     * @default 'nehonix_fortify_csrf'
     */
    cookieName?: string;
    /**
     * Name of the CSRF header
     * @default 'X-FORTIFY_CSRF-Token'
     */
    headerName?: string;
    /**
     * Paths to exclude from CSRF protection
     * @default ['/api/health', '/api/status']
     */
    excludePaths?: string[];
    /**
     * Whether to log requests
     * @default true
     */
    logRequests?: boolean;
    /**
     * Logger to use
     * @default console
     */
    logger?: Console;
    /**
     * Content Security Policy header value
     * @default "default-src 'self'; script-src 'self'; object-src 'none'; frame-ancestors 'none'"
     */
    contentSecurityPolicy?: string;
}
/**
 * Crypto stats
 */
interface CryptoStats {
    /**
     * Number of tokens generated
     */
    tokensGenerated: number;
    /**
     * Number of hashes computed
     */
    hashesComputed: number;
    /**
     * Number of keys derived
     */
    keysDerivated: number;
    /**
     * Average entropy in bits
     */
    averageEntropyBits: number;
    /**
     * Timestamp of the last operation
     */
    lastOperationTime: string;
    /**
     * Performance metrics
     */
    performance: {
        /**
         * Average token generation time in milliseconds
         */
        tokenGenerationAvgMs: number;
        /**
         * Average hash computation time in milliseconds
         */
        hashComputationAvgMs: number;
        /**
         * Average key derivation time in milliseconds
         */
        keyDerivationAvgMs: number;
    };
    /**
     * Memory usage metrics
     */
    memory: {
        /**
         * Average memory usage in bytes
         */
        averageUsageBytes: number;
        /**
         * Peak memory usage in bytes
         */
        peakUsageBytes: number;
    };
}
/**
 * Security test result
 */
interface SecurityTestResult {
    /**
     * Whether all tests passed
     */
    passed: boolean;
    /**
     * Test results
     */
    results: {
        /**
         * Random number generation test
         */
        randomness: {
            passed: boolean;
            details: any;
        };
        /**
         * Hash function test
         */
        hashing: {
            passed: boolean;
            details: any;
        };
        /**
         * Timing attack resistance test
         */
        timingAttacks: {
            passed: boolean;
            details: any;
        };
    };
}
/**
 * Password strength result
 */
interface PasswordStrengthResult {
    /**
     * Password strength score (0-100)
     */
    score: number;
    /**
     * Feedback messages
     */
    feedback: string[];
    /**
     * Estimated time to crack
     */
    estimatedCrackTime: string;
    /**
     * Detailed analysis
     */
    analysis: {
        /**
         * Length score
         */
        length: number;
        /**
         * Entropy score
         */
        entropy: number;
        /**
         * Character variety score
         */
        variety: number;
        /**
         * Pattern penalty
         */
        patterns: number;
    };
}
interface EnhancedHashOptions extends HashOptions {
    strength?: HashStrength;
    memoryHard?: boolean;
    quantumResistant?: boolean;
    timingSafe?: boolean;
    validateInput?: boolean;
    secureWipe?: boolean;
}
type BaseEncodingType = "unicode" | "htmlEntity" | "punycode" | "asciihex" | "asciioct" | "rot13" | "base32" | "urlSafeBase64" | "jsEscape" | "cssEscape" | "utf7" | "quotedPrintable" | "decimalHtmlEntity";
type EncodingHashType$1 = "hex" | "base64" | "base64url" | "binary" | "utf8" | "buffer" | "base58" | BaseEncodingType;
interface SecureHashOptions {
    algorithm?: string;
    iterations?: number;
    salt?: string | Buffer | Uint8Array;
    pepper?: string | Buffer | Uint8Array;
    outputFormat?: "hex" | "base64" | "base58" | "binary" | "base64url" | "buffer";
    keyDerivation?: "argon2" | "scrypt" | "pbkdf2" | "bcrypt";
    parallelism?: number;
    memorySize?: number;
    timeCost?: number;
    quantumResistant?: boolean;
    domainSeparation?: string;
}

/**
 * Hash types and interfaces
 * Centralized type definitions for the hash module
 */
declare enum HashStrength {
    WEAK = "WEAK",
    FAIR = "FAIR",
    GOOD = "GOOD",
    STRONG = "STRONG",
    MILITARY = "MILITARY"
}
type HashSecurityLevel = "LOW" | "MEDIUM" | "HIGH" | "MILITARY";
interface HashMonitoringResult {
    securityLevel: HashSecurityLevel;
    threats: string[];
    recommendations: string[];
    timestamp: number;
}
interface HashEntropyAnalysis {
    shannonEntropy: number;
    minEntropy: number;
    compressionRatio: number;
    randomnessScore: number;
    qualityGrade: "POOR" | "FAIR" | "GOOD" | "EXCELLENT";
    recommendations: string[];
}
interface HashAgilityResult {
    hash: string | Buffer;
    algorithm: string;
    fallbacks: string[];
    metadata: {
        version: string;
        timestamp: number;
        strength: string;
    };
}
interface HSMHashOptions {
    keySlot?: number;
    algorithm?: "sha256" | "sha512" | "sha3-256";
    outputFormat?: "hex" | "base64" | "buffer";
    validateIntegrity?: boolean;
}
interface SideChannelOptions {
    constantTime?: boolean;
    memoryProtection?: boolean;
    powerAnalysisResistant?: boolean;
    outputFormat?: "hex" | "base64" | "buffer";
}
interface StrengthConfiguration {
    minIterations: number;
    saltLength: number;
    algorithm?: string;
    memoryCost?: number;
    timeCost?: number;
    parallelism?: number;
    hashLength?: number;
    fallbackIterations?: number;
}
interface HashOperationData {
    input: string | Uint8Array;
    algorithm: string;
    iterations: number;
}
interface AgilityHashOptions {
    primaryAlgorithm?: "sha256" | "sha512" | "blake3" | "sha3-256";
    fallbackAlgorithms?: string[];
    futureProof?: boolean;
    outputFormat?: "hex" | "base64" | "buffer";
}

/**
 * Hash utilities - Common utility functions for hash operations
 */

declare class HashUtils {
    /**
     * Format hash output in the specified format
     * @param data - Data to format
     * @param format - Output format
     * @returns Formatted output
     */
    static formatOutput(data: Uint8Array | Buffer, format?: "hex" | "base64" | "base58" | "binary" | "base64url" | "buffer"): string | Buffer;
    /**
     * Get strength-based configuration
     * @param strength - Hash strength level
     * @returns Configuration object
     */
    static getStrengthConfiguration(strength: HashStrength): StrengthConfiguration;
    /**
     * Get Argon2 configuration based on strength
     * @param strength - Hash strength level
     * @returns Argon2 configuration
     */
    static getArgon2Configuration(strength: HashStrength): StrengthConfiguration;
    /**
     * Get scrypt configuration based on strength
     * @param strength - Hash strength level
     * @returns Scrypt configuration
     */
    static getScryptConfiguration(strength: HashStrength): {
        N: number;
        r: number;
        p: number;
    };
    /**
     * Perform secure memory wipe
     * @param input - Input to wipe
     * @param salt - Salt to wipe
     * @param pepper - Pepper to wipe
     */
    static performSecureWipe(input: string | Buffer | Uint8Array, salt?: string | Buffer | Uint8Array, pepper?: string | Buffer | Uint8Array): void;
    /**
     * Validate hash algorithm
     * @param algorithm - Algorithm to validate
     * @returns True if valid
     */
    static isValidAlgorithm(algorithm: string): boolean;
    /**
     * Get algorithm security level
     * @param algorithm - Algorithm to check
     * @returns Security level
     */
    static getAlgorithmSecurityLevel(algorithm: string): "LOW" | "MEDIUM" | "HIGH" | "MILITARY";
    /**
     * Convert string or Uint8Array to Buffer
     * @param input - Input to convert
     * @returns Buffer
     */
    static toBuffer(input: string | Uint8Array | Buffer): Buffer;
    /**
     * Generate random salt with specified length
     * @param length - Salt length in bytes
     * @returns Random salt buffer
     */
    static generateRandomSalt(length: number): Buffer;
    /**
     * Combine multiple buffers securely
     * @param buffers - Buffers to combine
     * @returns Combined buffer
     */
    static combineBuffers(buffers: Buffer[]): Buffer;
    /**
     * XOR two buffers of equal length
     * @param a - First buffer
     * @param b - Second buffer
     * @returns XORed result
     */
    static xorBuffers(a: Buffer, b: Buffer): Buffer;
}

/**
 * Hash validator - Input validation and security checks
 */

declare class HashValidator {
    /**
     * Validate hash input for security
     * @param input - Input to validate
     * @param options - Validation options
     */
    static validateHashInput(input: string | Uint8Array, options: EnhancedHashOptions): void;
    /**
     * Check for weak patterns in input
     * @param input - String input to check
     * @returns True if weak patterns found
     */
    private static hasWeakPatterns;
    /**
     * Validate hash options
     * @param options - Options to validate
     */
    private static validateOptions;
    /**
     * Validate password strength
     * @param password - Password to validate
     * @returns Validation result
     */
    static validatePasswordStrength(password: string): {
        isSecure: boolean;
        score: number;
        issues: string[];
        recommendations: string[];
    };
    /**
     * Enhanced timing-safe string comparison
     * @param a - First string/buffer
     * @param b - Second string/buffer
     * @returns True if equal
     */
    static timingSafeEqual(a: string | Buffer | Uint8Array, b: string | Buffer | Uint8Array): boolean;
    /**
     * Manual timing-safe comparison implementation
     */
    private static manualTimingSafeEqual;
    /**
     * Validate salt quality
     * @param salt - Salt to validate
     * @returns Validation result
     */
    static validateSalt(salt: string | Buffer | Uint8Array): {
        isValid: boolean;
        issues: string[];
        recommendations: string[];
    };
}

/**
 * Hash Algorithms - Enterprise-grade cryptographic hashing
 * Maintains backward compatibility while adding quantum-resistant features
 */

declare class HashAlgorithms {
    private static readonly QUANTUM_ALGORITHMS;
    private static readonly SECURITY_CONSTANTS;
    /**
     * Initialize crypto libraries asynchronously (NEW METHOD)
     */
    static initialize(): Promise<void>;
    /**
     * Core secure hash function with multiple algorithm support
     *
     * BEHAVIOR: This method produces consistent hashes for the same input. Unlike Hash.createSecureHash(), this method
     * does NOT auto-generate random salts, ensuring deterministic results.
     *
     * Use this method when you need:
     * - Consistent hashes for data integrity verification
     * - Content-based hashing (like file checksums)
     * - Deterministic hash generation
     *
     * @param input - Input to hash
     * @param options - Hash options (salt is optional and won't be auto-generated)
     * @returns Hash result (consistent for same input/options)
     */
    static secureHash(input: string | Uint8Array, options?: {
        algorithm?: string;
        iterations?: number;
        salt?: string | Buffer | Uint8Array;
        pepper?: string | Buffer | Uint8Array;
        outputFormat?: "hex" | "base64" | "base58" | "binary" | "base64url" | "buffer";
    }): string | Buffer;
    /**
     *  more algorithms and better implementations
     * Hash data with specified algorithm
     * @param data - Data to hash
     * @param algorithm - Algorithm to use
     * @returns Hash result
     */
    private static hashWithAlgorithm;
    /**
     *  real BLAKE3 implementation
     * BLAKE3 hash implementation
     * @param data - Data to hash
     * @returns BLAKE3 hash
     */
    private static blake3Hash;
    /**
     *  real BLAKE2b implementation
     * BLAKE2b hash implementation
     * @param data - Data to hash
     * @returns BLAKE2b hash
     */
    private static blake2bHash;
    /**
     *  real BLAKE2s implementation
     * BLAKE2s hash implementation
     * @param data - Data to hash
     * @returns BLAKE2s hash
     */
    private static blake2sHash;
    /**
     *  better security parameters
     * PBKDF2 hash implementation
     * @param data - Data to hash
     * @returns PBKDF2 hash
     */
    private static pbkdf2Hash;
    /**
     *  better constants and rounds
     * Fallback BLAKE3 implementation (simplified)
     * @param data - Data to hash
     * @returns Simplified BLAKE3-like hash
     */
    private static fallbackBlake3;
    /**
     *  quantum resistance option
     * Enhanced HMAC generation
     * @param algorithm - Hash algorithm
     * @param key - HMAC key
     * @param data - Data to authenticate
     * @param options - HMAC options
     * @returns HMAC digest
     */
    static createSecureHMAC(algorithm: "sha256" | "sha512" | "sha3-256" | "sha3-512", key: string | Buffer | Uint8Array, data: string | Buffer | Uint8Array, options?: {
        encoding?: "hex" | "base64" | "base64url";
        keyDerivation?: boolean;
        iterations?: number;
    }): string;
    /**
     *  better algorithm selection and quantum resistance
     * Multi-algorithm hash for quantum resistance
     * @param input - Input to hash
     * @param algorithms - Algorithms to use
     * @param iterations - Iterations per algorithm
     * @returns Combined hash result
     */
    static multiAlgorithmHash(input: string | Uint8Array, algorithms?: string[], iterations?: number): Buffer;
    /**
     *  better chunk processing and algorithms
     * Streamed hash for large data
     * @param algorithm - Hash algorithm
     * @param chunkSize - Chunk size for processing
     * @returns Hash stream processor
     */
    static createStreamHash(algorithm?: string, chunkSize?: number): {
        update: (chunk: Buffer) => void;
        digest: () => Buffer;
        reset: () => void;
    };
    /**
     *  better timing attack prevention
     * Constant-time hash comparison
     * @param hash1 - First hash
     * @param hash2 - Second hash
     * @returns True if hashes match
     */
    static constantTimeCompare(hash1: string | Buffer, hash2: string | Buffer): boolean;
    /**
     * NEW METHOD - Ultra-secure hash function with quantum resistance
     */
    static quantumResistantHash(input: string | Uint8Array, options?: SecureHashOptions): Promise<string | Buffer>;
    /**
     * NEW METHOD - Argon2 key derivation
     */
    private static argon2Derive;
    /**
     * NEW METHOD - Scrypt key derivation
     */
    private static scryptDerive;
    /**
     * NEW METHOD - BCrypt key derivation
     */
    private static bcryptDerive;
    /**
     * NEW METHOD - Enhanced PBKDF2 key derivation
     */
    private static pbkdf2Derive;
    /**
     * NEW METHOD - Multi-algorithm quantum-resistant hashing
     */
    private static multiQuantumHash;
    /**
     * NEW METHOD - Ultra-secure HMAC with quantum resistance
     */
    static createQuantumHMAC(algorithm: string, key: string | Buffer | Uint8Array, data: string | Buffer | Uint8Array, options?: {
        encoding?: "hex" | "base64" | "base64url";
        keyDerivation?: boolean;
        iterations?: number;
        quantumResistant?: boolean;
    }): Promise<string>;
    /**
     * NEW METHOD - BLAKE3-based HMAC
     */
    private static blake3HMAC;
    /**
     * NEW METHOD - Secure random salt generation
     */
    static generateSecureSalt(size?: number): Buffer;
    /**
     * NEW METHOD - Enhanced secure comparison with additional timing normalization
     */
    static secureCompare(hash1: string | Buffer, hash2: string | Buffer): boolean;
    /**
     * NEW METHOD - Secure hash verification
     */
    static verifyHash(input: string | Uint8Array, expectedHash: string | Buffer, options?: SecureHashOptions): Promise<boolean>;
    /**
     * NEW METHOD - Memory-hard proof of work
     */
    static proofOfWork(challenge: string, difficulty?: number): Promise<{
        nonce: string;
        hash: string;
        attempts: number;
    }>;
}

/**
 * Hash security features - Advanced security implementations
 */

declare class HashSecurity {
    /**
     * Hardware Security Module (HSM) compatible hashing
     * @param input - Input to hash
     * @param options - HSM options
     * @returns HSM-compatible hash
     */
    static hsmCompatibleHash(input: string | Uint8Array, options?: HSMHashOptions): string | Buffer;
    /**
     * Derive HSM-compatible key
     * @param keySlot - HSM key slot number
     * @returns Derived key
     */
    private static deriveHSMKey;
    /**
     * Verify HSM integrity
     * @param hash - Hash to verify
     * @param key - HSM key
     * @returns Verification result
     */
    private static verifyHSMIntegrity;
    /**
     * Real-time security monitoring for hash operations
     * @param operation - Operation being monitored
     * @param data - Data being processed
     * @returns Monitoring results
     */
    static monitorHashSecurity(operation: string, data: HashOperationData): HashMonitoringResult;
    /**
     * Timing-safe hashing to prevent timing attacks
     * @param input - Input to hash
     * @param options - Hashing options
     * @returns Timing-safe hash
     */
    static timingSafeHash(input: string | Uint8Array, options?: {
        algorithm?: string;
        iterations?: number;
        salt?: string | Buffer | Uint8Array;
        outputFormat?: "hex" | "base64" | "buffer";
        targetTime?: number;
    }): string | Buffer;
    /**
     * Memory-hard hashing using Argon2 (military-grade)
     * @param input - Input to hash
     * @param options - Hashing options
     * @returns Promise resolving to hash
     */
    static memoryHardHash(input: string | Uint8Array, options?: {
        memoryCost?: number;
        timeCost?: number;
        parallelism?: number;
        hashLength?: number;
        salt?: string | Buffer | Uint8Array;
        outputFormat?: "hex" | "base64" | "buffer";
    }): Promise<string | Buffer>;
    /**
     * Quantum-resistant hashing with enhanced entropy
     * @param input - Input to hash
     * @param options - Hashing options
     * @returns Quantum-resistant hash
     */
    static quantumResistantHash(input: string | Uint8Array, options?: {
        algorithms?: string[];
        iterations?: number;
        salt?: string | Buffer | Uint8Array;
        outputFormat?: "hex" | "base64" | "buffer";
    }): string | Buffer;
    /**
     * Secure hash verification with timing attack protection
     * @param input - Input to verify
     * @param expectedHash - Expected hash value
     * @param options - Verification options
     * @returns True if hash matches
     */
    static secureVerify(input: string | Uint8Array, expectedHash: string | Buffer, options?: {
        algorithm?: string;
        iterations?: number;
        salt?: string | Buffer | Uint8Array;
        constantTime?: boolean;
    }): boolean;
    /**
     * Manual constant-time comparison
     * @param a - First buffer
     * @param b - Second buffer
     * @returns True if buffers are equal
     */
    private static manualConstantTimeCompare;
}

/**
 * Hash advanced features - Cutting-edge hash implementations
 */

declare class HashAdvanced {
    /**
     * Cryptographic agility - support for algorithm migration
     * @param input - Input to hash
     * @param options - Migration options
     * @returns Hash with algorithm metadata
     */
    static agilityHash(input: string | Uint8Array, options?: AgilityHashOptions): HashAgilityResult;
    /**
     * Side-channel attack resistant hashing
     * @param input - Input to hash
     * @param options - Resistance options
     * @returns Side-channel resistant hash
     */
    static sideChannelResistantHash(input: string | Uint8Array, options?: SideChannelOptions): string | Buffer;
    /**
     * Constant-time hash processing
     * @param inputBuffer - Input buffer
     * @param memoryProtection - Enable memory protection
     * @param outputFormat - Output format
     * @returns Constant-time hash
     */
    private static constantTimeHash;
    /**
     * Power analysis resistant hash processing
     * @param inputBuffer - Input buffer
     * @param outputFormat - Output format
     * @returns Power analysis resistant hash
     */
    private static powerAnalysisResistantHash;
    /**
     * Parallel hash processing for performance
     * @param input - Input to hash
     * @param options - Parallel processing options
     * @returns Promise resolving to hash result
     */
    static parallelHash(input: string | Uint8Array, options?: {
        chunkSize?: number;
        workers?: number;
        algorithm?: string;
        outputFormat?: "hex" | "base64" | "buffer";
    }): Promise<string | Buffer>;
    /**
     * Streaming hash for large data processing
     * @param algorithm - Hash algorithm
     * @param options - Streaming options
     * @returns Stream hash processor
     */
    static createStreamingHash(algorithm?: string, options?: {
        chunkSize?: number;
        progressCallback?: (processed: number, total?: number) => void;
    }): {
        update: (chunk: Buffer) => void;
        digest: () => Buffer;
        reset: () => void;
        getProgress: () => {
            processed: number;
            chunks: number;
        };
    };
    /**
     * Merkle tree hash for data integrity
     * @param data - Array of data chunks
     * @param algorithm - Hash algorithm
     * @returns Merkle root hash
     */
    static merkleTreeHash(data: (string | Uint8Array | Buffer)[], algorithm?: string): Buffer;
    /**
     * Incremental hash for append-only data
     * @param previousHash - Previous hash state
     * @param newData - New data to append
     * @param algorithm - Hash algorithm
     * @returns Updated hash
     */
    static incrementalHash(previousHash: string | Buffer, newData: string | Uint8Array | Buffer, algorithm?: string): Buffer;
    /**
     * Hash chain for sequential data integrity
     * @param data - Array of data items
     * @param algorithm - Hash algorithm
     * @returns Array of chained hashes
     */
    static hashChain(data: (string | Uint8Array | Buffer)[], algorithm?: string): Buffer[];
}

/**
 * Hash entropy analysis and quality assessment
 */

declare class HashEntropy {
    /**
     * Advanced entropy analysis for hash quality assessment
     * @param data - Data to analyze
     * @returns Entropy analysis results
     */
    static analyzeHashEntropy(data: Buffer | Uint8Array): HashEntropyAnalysis;
    /**
     * Perform statistical randomness tests
     * @param data - Data to test
     * @returns Test results
     */
    static performRandomnessTests(data: Buffer): {
        monobitTest: {
            passed: boolean;
            score: number;
        };
        runsTest: {
            passed: boolean;
            score: number;
        };
        frequencyTest: {
            passed: boolean;
            score: number;
        };
        serialTest: {
            passed: boolean;
            score: number;
        };
        overallScore: number;
    };
    /**
     * Monobit test - checks balance of 0s and 1s
     * @param data - Data to test
     * @returns Test result
     */
    private static monobitTest;
    /**
     * Runs test - checks for proper distribution of runs
     * @param data - Data to test
     * @returns Test result
     */
    private static runsTest;
    /**
     * Frequency test - checks distribution of byte values
     * @param data - Data to test
     * @returns Test result
     */
    private static frequencyTest;
    /**
     * Serial test - checks correlation between consecutive bytes
     * @param data - Data to test
     * @returns Test result
     */
    private static serialTest;
    /**
     * Estimate entropy rate of data
     * @param data - Data to analyze
     * @returns Entropy rate in bits per byte
     */
    static estimateEntropyRate(data: Buffer): number;
    /**
     * Generate entropy quality report
     * @param data - Data to analyze
     * @returns Comprehensive entropy report
     */
    static generateEntropyReport(data: Buffer): {
        analysis: HashEntropyAnalysis;
        randomnessTests: ReturnType<typeof HashEntropy.performRandomnessTests>;
        entropyRate: number;
        recommendations: string[];
        overallGrade: "POOR" | "FAIR" | "GOOD" | "EXCELLENT";
    };
}

/**
 * Hash Core - Main Hash class with modular architecture
 * This is the primary interface for all hashing operations
 */

/**
 * Military-grade hashing functionality with enhanced security features
 * Modular architecture for maintainable and scalable hash operations
 */
declare class Hash {
    /**
     * Create secure hash with military-grade security options
     *
     * IMPORTANT: This method automatically generates a random salt
     * when no salt is provided, resulting in different hashes for the same input.
     * This is designed for password hashing where randomness enhances security.
     *
     * For consistent hashes, either:
     * - Provide a fixed salt parameter, or
     * - Use Hash.create() method instead
     *
     * @param input - The input to hash
     * @param salt - Salt for the hash (if not provided, random salt is auto-generated)
     * @param options - Enhanced hashing options
     * @returns The hash in the specified format
     */
    static createSecureHash(input: string | Uint8Array, salt?: string | Buffer | Uint8Array, options?: EnhancedHashOptions): string | Promise<string>;
    /**
     * Verify hash with secure comparison
     * @param input - Input to verify
     * @param expectedHash - Expected hash value
     * @param salt - Salt used in original hash
     * @param options - Verification options
     * @returns True if hash matches
     */
    static verifyHash(input: string | Uint8Array, expectedHash: string | Buffer, salt?: string | Buffer | Uint8Array, options?: EnhancedHashOptions): boolean;
    /**
     * Async verify hash with secure comparison
     * @param input - Input to verify
     * @param expectedHash - Expected hash value
     * @param salt - Salt used in original hash
     * @param options - Verification options
     * @returns Promise resolving to true if hash matches
     */
    static verifyHashAsync(input: string | Uint8Array, expectedHash: string | Buffer, salt?: string | Buffer | Uint8Array, options?: EnhancedHashOptions): Promise<boolean>;
    /**
     * Enhanced PBKDF2 key derivation
     */
    static deriveKeyPBKDF2: typeof HashSecurity.memoryHardHash;
    /**
     * Enhanced scrypt key derivation
     */
    static deriveKeyScrypt(password: string | Buffer, salt: string | Buffer, keyLength?: number, options?: {
        N?: number;
        r?: number;
        p?: number;
        encoding?: "hex" | "base64" | "buffer";
        validateStrength?: boolean;
    }): string | Buffer;
    /**
     * Enhanced Argon2 key derivation
     */
    static deriveKeyArgon2: typeof HashSecurity.memoryHardHash;
    /**
     * Standard PBKDF2 key derivation
     *
     * BEHAVIOR: Uses Node.js crypto.pbkdf2Sync for reliable, standard PBKDF2 implementation.
     * Produces consistent results and is widely compatible.
     * With crypto:
     * @example
     * crypto.pbkdf2Sync(
            password,
            salt,
            iterations,
            keyLength,
            hashFunction
        );
     *
     * @param password - Password to derive key from
     * @param salt - Salt for the derivation
     * @param iterations - Number of iterations (default: 100000)
     * @param keyLength - Desired key length in bytes (default: 32)
     * @param hashFunction - Hash function to use (default: "sha256")
     * @param outputFormat - Output format (default: "hex")
     * @returns PBKDF2 derived key
     */
    static pbkdf2(password: string, salt: string, iterations?: number, keyLength?: number, hashFunction?: "sha256" | "sha512", outputFormat?: "hex" | "base64" | "buffer"): string | Buffer;
    /**
     * Hardware Security Module (HSM) compatible hashing
     */
    static hsmCompatibleHash: typeof HashSecurity.hsmCompatibleHash;
    /**
     * Cryptographic agility hash
     */
    static agilityHash: typeof HashAdvanced.agilityHash;
    /**
     * Side-channel attack resistant hashing
     */
    static sideChannelResistantHash: typeof HashAdvanced.sideChannelResistantHash;
    /**
     * Real-time security monitoring
     */
    static monitorHashSecurity: typeof HashSecurity.monitorHashSecurity;
    /**
     * Analyze hash entropy
     */
    static analyzeHashEntropy: typeof HashEntropy.analyzeHashEntropy;
    /**
     * Generate entropy report
     */
    static generateEntropyReport: typeof HashEntropy.generateEntropyReport;
    /**
     * Perform randomness tests
     */
    static performRandomnessTests: typeof HashEntropy.performRandomnessTests;
    /**
     * Validate password strength
     */
    static validatePasswordStrength: typeof HashValidator.validatePasswordStrength;
    /**
     * Timing-safe string comparison
     */
    static timingSafeEqual: typeof HashValidator.timingSafeEqual;
    /**
     * Validate salt quality
     */
    static validateSalt: typeof HashValidator.validateSalt;
    /**
     * Parallel hash processing
     */
    static parallelHash: typeof HashAdvanced.parallelHash;
    /**
     * Streaming hash for large data
     */
    static createStreamingHash: typeof HashAdvanced.createStreamingHash;
    /**
     * Merkle tree hash
     */
    static merkleTreeHash: typeof HashAdvanced.merkleTreeHash;
    /**
     * Incremental hash
     */
    static incrementalHash: typeof HashAdvanced.incrementalHash;
    /**
     * Hash chain
     */
    static hashChain: typeof HashAdvanced.hashChain;
    /**
     * Format hash output
     */
    static formatOutput: typeof HashUtils.formatOutput;
    /**
     * Get strength configuration
     */
    static getStrengthConfiguration: typeof HashUtils.getStrengthConfiguration;
    /**
     * Get algorithm security level
     */
    static getAlgorithmSecurityLevel: typeof HashUtils.getAlgorithmSecurityLevel;
    /**
     * Handle secure wipe if requested
     * IMPORTANT: Only wipe copies, not the original salt/pepper that might be needed for verification
     */
    private static handleSecureWipe;
    /**
     * Legacy secure hash method (for backward compatibility)
     *
     * BEHAVIOR: Produces consistent hashes for the same input (like CryptoJS).
     * This method does NOT auto-generate random salts, ensuring deterministic results.
     *
     * For password hashing with auto-salt generation, use Hash.createSecureHash() instead.
     */
    static create: typeof HashAlgorithms.secureHash;
    /**
     * Legacy HMAC creation (for backward compatibility)
     */
    static createSecureHMAC: typeof HashAlgorithms.createSecureHMAC;
}

/**
 * Random types - Type definitions and interfaces for random operations
 */

type EncodingHashType = "hex" | "base64" | "base58" | "buffer";
declare enum RNGState {
    UNINITIALIZED = "uninitialized",
    INITIALIZING = "initializing",
    READY = "ready",
    ERROR = "error",
    RESEEDING = "reseeding"
}
declare enum EntropyQuality {
    POOR = "poor",
    FAIR = "fair",
    GOOD = "good",
    EXCELLENT = "excellent",
    MILITARY = "military"
}
interface RandomGenerationOptions {
    useEntropyPool?: boolean;
    quantumSafe?: boolean;
    reseedThreshold?: number;
    securityLevel?: SecurityLevel$1;
    validateOutput?: boolean;
}
interface TokenGenerationOptions {
    includeUppercase?: boolean;
    includeLowercase?: boolean;
    includeNumbers?: boolean;
    includeSymbols?: boolean;
    excludeSimilarCharacters?: boolean;
    entropyLevel?: SecurityLevel$1;
    outputFormat?: EncodingHashType;
    customCharset?: string;
    minEntropy?: number;
}
interface IVGenerationOptions {
    algorithm?: "aes-128-cbc" | "aes-192-cbc" | "aes-256-cbc" | "aes-128-gcm" | "aes-192-gcm" | "aes-256-gcm" | "aes-128-ctr" | "aes-192-ctr" | "aes-256-ctr" | "chacha20" | "chacha20-poly1305" | "des-ede3-cbc" | "blowfish-cbc";
    quantumSafe?: boolean;
    useEntropyPool?: boolean;
    validateSize?: boolean;
}
interface CryptoUtilityOptions {
    keySize?: number;
    algorithm?: string;
    quantumSafe?: boolean;
    useHardwareEntropy?: boolean;
    validateStrength?: boolean;
}
interface SecurityMonitoringResult {
    entropyQuality: EntropyQuality;
    securityLevel: SecurityLevel$1;
    threats: string[];
    recommendations: string[];
    timestamp: number;
    bytesGenerated: number;
    reseedCount: number;
    libraryStatus: Record<string, boolean>;
}
interface EntropyAnalysisResult$1 {
    shannonEntropy: number;
    minEntropy: number;
    compressionRatio: number;
    randomnessScore: number;
    qualityGrade: EntropyQuality;
    recommendations: string[];
    testResults: {
        monobitTest: {
            passed: boolean;
            score: number;
        };
        runsTest: {
            passed: boolean;
            score: number;
        };
        frequencyTest: {
            passed: boolean;
            score: number;
        };
        serialTest: {
            passed: boolean;
            score: number;
        };
    };
}
interface LibraryStatus extends Record<string, boolean> {
    sodium: boolean;
    forge: boolean;
    secureRandom: boolean;
    randombytes: boolean;
    nobleHashes: boolean;
    tweetnacl: boolean;
    kyber: boolean;
    entropyString: boolean;
    cryptoJs: boolean;
    elliptic: boolean;
    nobleCurves: boolean;
}
interface RandomState {
    entropyPool: Buffer;
    lastReseed: number;
    state: RNGState;
    bytesGenerated: number;
    entropyQuality: EntropyQuality;
    securityLevel: SecurityLevel$1;
    quantumSafeMode: boolean;
    reseedCounter: number;
    hardwareEntropyAvailable: boolean;
    sidechannelProtection: boolean;
    entropyAugmentation: boolean;
    realTimeMonitoring: boolean;
    lastEntropyTest: number;
    entropyTestResults: Map<string, number>;
    securityAlerts: string[];
    additionalEntropySources: Map<string, () => Buffer>;
}

type EncodingType = "hex" | "base64" | "base64url" | "base58" | "binary" | "utf8" | BaseEncodingType;

/**
 * Enhanced Uint8Array with encoding support and improved security
 */
declare class EnhancedUint8Array extends Uint8Array {
    private _isCleared;
    /**
     * Convert to string with specified encoding
     * @param encoding - Encoding type (optional, defaults to hex for security)
     * @returns Encoded string
     */
    toString(encoding?: EncodingType): string;
    /**
     * Secure hex conversion
     */
    private _toHexSecure;
    /**
     * Secure base64 conversion
     */
    private _toBase64Secure;
    /**
     * Secure Base58 conversion with improved error handling
     */
    private _toBase58Secure;
    /**
     * Secure binary conversion
     */
    private _toBinarySecure;
    /**
     * Secure UTF-8 conversion
     */
    private _toUtf8Secure;
    /**
     * Get entropy information with enhanced analysis
     */
    getEntropyInfo(): {
        bytes: number;
        bits: number;
        quality: string;
        entropy: number;
    };
    /**
     * Calculate Shannon entropy for quality assessment
     */
    private _calculateShannonEntropy;
    /**
     * Get quality rating based on entropy and length
     */
    private _getQualityRating;
    /**
     * Get as Buffer with proper typing and security
     * @returns Buffer<ArrayBufferLike> containing the same data
     */
    getBuffer(): Buffer<ArrayBufferLike>;
    /**
     * Securely clear the array contents
     */
    clear(): void;
    /**
     * Check if array has been cleared
     */
    private _checkCleared;
    /**
     * Create a secure copy of the array
     */
    secureClone(): EnhancedUint8Array;
    /**
     * Compare with another array in constant time to prevent timing attacks
     */
    constantTimeEquals(other: Uint8Array): boolean;
    /**
     * Convert to regular Uint8Array for safe Buffer operations
     */
    toUint8Array(): Uint8Array;
    /**
     * Override valueOf to provide safe primitive conversion
     * Returns this instance for Buffer.from() compatibility
     */
    valueOf(): this;
}

/**
 * Ultra-secure random number generation with modular architecture
 * Provides military-grade security with multiple entropy sources
 */
declare class SecureRandom {
    private static instance;
    private state;
    private stats;
    private constructor();
    /**
     * Get singleton instance
     */
    static getInstance(): SecureRandom;
    /**
     * Initialize entropy pool
     */
    private initializeEntropyPool;
    /**
     * Setup additional entropy sources
     */
    private setupAdditionalEntropySources;
    /**
     * Detect hardware entropy availability
     */
    private detectHardwareEntropy;
    /**
     * Generate ultra-secure random bytes with enhanced entropy
     * @param length - Number of bytes to generate
     * @param options - Generation options
     * @returns Enhanced random bytes
     */
    static getRandomBytes(length: number, options?: RandomGenerationOptions): EnhancedUint8Array;
    /**
     * Get system random bytes (fallback method)
     */
    static getSystemRandomBytes(length: number): Uint8Array;
    /**
     * Generate secure random integer
     */
    static getSecureRandomInt(min: number, max: number, options?: RandomGenerationOptions): number;
    /**
     * Generate secure UUID v4
     */
    static generateSecureUUID(options?: RandomGenerationOptions): string;
    /**
     * Generate secure random float
     */
    static getSecureRandomFloat(options?: RandomGenerationOptions): number;
    /**
     * Generate secure random boolean
     */
    static getSecureRandomBoolean(options?: RandomGenerationOptions): boolean;
    /**
     * Generate salt
     */
    static generateSalt(length?: number, options?: RandomGenerationOptions): Buffer;
    /**
     * Reseed entropy pool
     */
    reseedEntropyPool(): void;
    /**
     * Get entropy analysis
     */
    static getEntropyAnalysis(data?: Buffer): EntropyAnalysisResult$1;
    /**
     * Assess entropy quality
     */
    static assessEntropyQuality(data: Buffer): EntropyQuality;
    /**
     * Get security monitoring result
     */
    static getSecurityStatus(): SecurityMonitoringResult;
    /**
     * Get library status
     */
    static getLibraryStatus(): LibraryStatus;
    /**
     * Check if secure random is available
     */
    static isSecureRandomAvailable(): boolean;
    /**
     * Get current state
     */
    getState(): RandomState;
    /**
     * Get statistics
     */
    static getStatistics(): {
        bytesGenerated: number;
        reseedCount: number;
        lastReseed: number;
        entropyQuality: EntropyQuality;
        state: RNGState;
    };
    /**
     * Reset instance (for testing)
     */
    static resetInstance(): void;
    /**
     * Enable quantum-safe mode
     */
    static enableQuantumSafeMode(): void;
    /**
     * Disable quantum-safe mode
     */
    static disableQuantumSafeMode(): void;
    /**
     * Set security level
     */
    static setSecurityLevel(level: SecurityLevel$1): void;
}

/**
 * Random tokens - Token and password generation utilities
 */

declare class RandomTokens {
    /**
     * Generate a secure token with specified options
     * @param length - Length of the token
     * @param options - Token generation options
     * @returns Secure random token
     */
    static generateSecureToken(length: number, options?: TokenGenerationOptions): string;
    /**
     * Generate secure password with complexity requirements
     * @param length - Password length
     * @param options - Generation options
     * @returns Secure password
     */
    static generateSecurePassword(length?: number, options?: TokenGenerationOptions): string;
    /**
     * Generate session token
     * @param length - Token length in bytes
     * @param encoding - Output encoding
     * @param options - Generation options
     * @returns Secure session token
     */
    static generateSessionToken(length?: number, encoding?: "hex" | "base64" | "base64url", options?: RandomGenerationOptions): string;
    /**
     * Generate API key
     * @param length - Key length
     * @param prefix - Optional prefix
     * @param options - Generation options
     * @returns Secure API key
     */
    static generateAPIKey(length?: number, prefix?: string, options?: TokenGenerationOptions): string;
    /**
     * Generate secure PIN
     * @param length - PIN length
     * @param options - Generation options
     * @returns Secure numeric PIN
     */
    static generateSecurePIN(length?: number, options?: RandomGenerationOptions): string;
    /**
     * Generate secure OTP (One-Time Password)
     * @param length - OTP length
     * @param options - Generation options
     * @returns Secure OTP
     */
    static generateSecureOTP(length?: number, options?: TokenGenerationOptions): string;
    /**
     * Generate recovery codes
     * @param count - Number of codes to generate
     * @param codeLength - Length of each code
     * @param options - Generation options
     * @returns Array of recovery codes
     */
    static generateRecoveryCodes(count?: number, codeLength?: number, options?: TokenGenerationOptions): string[];
    /**
     * Get random character from character set
     */
    private static getRandomCharFromSet;
    /**
     * Build character set based on options
     */
    private static buildCharset;
    /**
     * Validate token strength
     * @param token - Token to validate
     * @returns Strength assessment
     */
    static validateTokenStrength(token: string): {
        score: number;
        strength: "weak" | "fair" | "good" | "strong" | "excellent";
        issues: string[];
    };
}

/**
 * Random crypto - Cryptographic utilities (IV, keys, nonces)
 */

declare class RandomCrypto {
    /**
     * Generate secure nonce/IV for encryption
     * @param algorithm - Algorithm requiring the nonce
     * @param options - Generation options
     * @returns Nonce as Uint8Array
     */
    static generateNonce(algorithm: "aes-gcm" | "chacha20-poly1305" | "aes-cbc" | "custom", options?: {
        quantumSafe?: boolean;
        useEntropyPool?: boolean;
        customLength?: number;
    }): Uint8Array;
    /**
     * Generate a secure Initialization Vector (IV) for encryption algorithms
     * @param length - Length of the IV in bytes
     * @param options - Generation options including algorithm
     * @returns Secure IV as EnhancedUint8Array
     */
    static generateSecureIV(length: number, options?: IVGenerationOptions): EnhancedUint8Array;
    /**
     * Generate multiple IVs efficiently
     * @param count - Number of IVs to generate
     * @param length - Length of each IV
     * @param options - Generation options
     * @returns Array of IVs
     */
    static generateSecureIVBatch(count: number, length: number, options?: IVGenerationOptions): EnhancedUint8Array[];
    /**
     * Generate IV for specific algorithm
     * @param algorithm - Encryption algorithm
     * @param options - Generation options
     * @returns Algorithm-specific IV
     */
    static generateSecureIVForAlgorithm(algorithm: string, options?: IVGenerationOptions): EnhancedUint8Array;
    /**
     * Generate multiple IVs for specific algorithm
     * @param count - Number of IVs to generate
     * @param algorithm - Encryption algorithm
     * @param options - Generation options
     * @returns Array of algorithm-specific IVs
     */
    static generateSecureIVBatchForAlgorithm(count: number, algorithm: string, options?: IVGenerationOptions): EnhancedUint8Array[];
    /**
     * Validate IV for algorithm
     * @param iv - IV to validate
     * @param algorithm - Target algorithm
     * @returns Validation result
     */
    static validateIV(iv: Uint8Array | Buffer, algorithm: string): {
        valid: boolean;
        expectedLength?: number;
        actualLength: number;
        message: string;
    };
    /**
     * Create secure cipher with auto-generated IV
     * @param algorithm - Cipher algorithm
     * @param key - Encryption key
     * @param options - Cipher options
     * @returns Cipher and IV
     */
    static createSecureCipheriv(algorithm: string, key: crypto__default.CipherKey, options?: CryptoUtilityOptions): {
        cipher: crypto__default.Cipher;
        iv: Buffer;
    };
    /**
     * Create secure decipher
     * @param algorithm - Cipher algorithm
     * @param key - Decryption key
     * @param iv - Initialization vector
     * @returns Decipher
     */
    static createSecureDecipheriv(algorithm: string, key: crypto__default.CipherKey, iv: crypto__default.BinaryLike): crypto__default.Decipher;
    /**
     * Generate cryptographic key
     * @param length - Key length in bytes
     * @param options - Generation options
     * @returns Cryptographic key
     */
    static generateCryptoKey(length: number, options?: CryptoUtilityOptions): Buffer;
    /**
     * Validate key strength
     * @param key - Key to validate
     * @returns Validation result
     */
    static validateKeyStrength(key: Buffer): {
        valid: boolean;
        strength: "weak" | "fair" | "good" | "strong";
        issues: string[];
    };
    /**
     * Generate key derivation salt
     * @param length - Salt length
     * @param options - Generation options
     * @returns KDF salt
     */
    static generateKDFSalt(length?: number, options?: RandomGenerationOptions): Buffer;
    /**
     * Generate HMAC key
     * @param algorithm - HMAC algorithm
     * @param options - Generation options
     * @returns HMAC key
     */
    static generateHMACKey(algorithm?: string, options?: CryptoUtilityOptions): Buffer;
}

declare enum MemoryProtectionLevel {
    BASIC = "basic",
    ENHANCED = "enhanced",
    MILITARY = "military",
    QUANTUM_SAFE = "quantum_safe"
}
declare enum BufferState {
    UNINITIALIZED = "uninitialized",
    ACTIVE = "active",
    LOCKED = "locked",
    DESTROYED = "destroyed",
    CORRUPTED = "corrupted"
}
interface SecureBufferOptions {
    protectionLevel?: MemoryProtectionLevel;
    enableEncryption?: boolean;
    enableFragmentation?: boolean;
    enableCanaries?: boolean;
    enableObfuscation?: boolean;
    autoLock?: boolean;
    lockTimeout?: number;
    quantumSafe?: boolean;
}

/**
 * This module provides military-grade utilities for securely handling sensitive data in memory:
 * - Secure buffers with advanced protection against memory dumps and swapping
 * - Multiple encryption layers for data at rest in memory
 * - Hardware-level security features when available
 * - Protection against cold boot attacks and memory forensics
 * - Canary tokens for tamper detection
 * - Memory fragmentation and obfuscation techniques
 * - Quantum-resistant security measures
 * - Side-channel attack resistance
 */

declare class SecureBuffer {
    private fragments;
    private encryptionKey;
    private nonce;
    private canaryTokens;
    private obfuscationMask;
    private state;
    private protectionLevel;
    private options;
    private accessCount;
    private lastAccess;
    private lockTimer;
    private originalSize;
    private checksum;
    /**
     * Creates a new enhanced secure buffer with military-grade protection
     *
     * @param size - Size of the buffer in bytes
     * @param fill - Optional value to fill the buffer with
     * @param options - Security options
     */
    constructor(size: number, fill?: number, options?: SecureBufferOptions);
    /**
     * Initialize the secure buffer with enhanced protection
     */
    private initializeSecureBuffer;
    /**
     * Setup automatic locking mechanism
     */
    private setupAutoLock;
    /**
     * Reset the auto-lock timer
     */
    private resetLockTimer;
    /**
     * Generate a cryptographically secure key
     */
    private generateSecureKey;
    /**
     * Create memory fragments for enhanced security
     */
    private createFragments;
    /**
     * Generate canary tokens for tamper detection
     */
    private generateCanaryTokens;
    /**
     * Get the unencrypted buffer by combining fragments
     */
    private getUnencryptedBuffer;
    /**
     * Lock the buffer to prevent access
     */
    lock(): void;
    /**
     * Unlock the buffer to allow access
     */
    unlock(): void;
    /**
     * Check if buffer is locked
     */
    isLocked(): boolean;
    /**
     * Check if buffer is destroyed
     */
    isDestroyed(): boolean;
    /**
     * Verify buffer integrity using canary tokens and checksum
     */
    verifyIntegrity(): boolean;
    /**
     * Encrypt fragments using ChaCha20-Poly1305 or AES-GCM
     */
    private encryptFragments;
    /**
     * Decrypt fragments
     */
    private decryptFragments;
    /**
     * Sets data directly in fragments (private method for initialization)
     *
     * @param data - Data to set in the fragments
     */
    private setDataInFragments;
    /**
     * Creates a secure buffer from existing data
     *
     * @param data - Data to store in the secure buffer
     * @param options - Security options
     * @returns A new secure buffer containing the data
     */
    static from(data: Uint8Array | Array<number> | string, options?: SecureBufferOptions): SecureBuffer;
    /**
     * Gets the underlying buffer (decrypted if necessary)
     * Throws if the buffer has been destroyed or locked
     *
     * @returns The underlying buffer
     */
    getBuffer(): Uint8Array;
    /**
     * Gets the length of the buffer
     *
     * @returns The length of the buffer in bytes
     */
    length(): number;
    /**
     * Copies data to another buffer
     *
     * @param target - Target buffer
     * @param targetStart - Start position in the target buffer
     * @param sourceStart - Start position in this buffer
     * @param sourceEnd - End position in this buffer
     * @returns Number of bytes copied
     */
    copy(target: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number;
    /**
     * Fills the buffer with the specified value
     *
     * @param value - Value to fill the buffer with
     * @param start - Start position
     * @param end - End position
     * @returns This buffer
     */
    fill(value: number, start?: number, end?: number): SecureBuffer;
    /**
     * Compares this buffer with another buffer using constant-time comparison
     *
     * @param otherBuffer - Buffer to compare with
     * @returns True if the buffers are equal, false otherwise
     */
    equals(otherBuffer: Uint8Array | SecureBuffer): boolean;
    /**
     * Destroys the buffer by securely wiping its contents
     * After calling this method, the buffer can no longer be used
     */
    destroy(): void;
    /**
     * Get security statistics and information
     */
    getSecurityInfo(): {
        protectionLevel: MemoryProtectionLevel;
        isEncrypted: boolean;
        isFragmented: boolean;
        hasCanaries: boolean;
        isObfuscated: boolean;
        accessCount: number;
        lastAccess: number;
        fragmentCount: number;
        state: BufferState;
    };
    /**
     * Clone the secure buffer with the same protection settings
     */
    clone(): SecureBuffer;
    /**
     * Resize the buffer (creates a new buffer with copied data)
     */
    resize(newSize: number): SecureBuffer;
    /**
     * Update the checksum after buffer modification
     */
    updateChecksum(): void;
    /**
     * Registers a finalizer to clean up the buffer when it's garbage collected
     * This is a best-effort approach as JavaScript doesn't guarantee finalization
     */
    private registerFinalizer;
}
/**
 * Securely wipes a section of memory
 *
 * This implementation follows recommendations from security standards
 * for secure data deletion, using multiple overwrite patterns to ensure
 * data cannot be recovered even with advanced forensic techniques.
 *
 * @param buffer - Buffer to wipe
 * @param start - Start position
 * @param end - End position
 * @param passes - Number of overwrite passes (default: 3)
 */
declare function secureWipe(buffer: Uint8Array, start?: number, end?: number, passes?: number): void;

/**
 * Entropy Augmentation Module
 *
 * This module provides methods to enhance the entropy (randomness) of
 * cryptographic operations by collecting additional entropy from various sources
 * and combining it with the system's built-in random number generator.
 *
 * This helps protect against weak or compromised random number generators
 * by adding multiple layers of entropy.
 */

/**
 * Entropy collection options
 */
interface EntropyOptions {
    /**
     * Whether to collect timing entropy
     * @default true
     */
    useTiming?: boolean;
    /**
     * Whether to collect performance entropy
     * @default true
     */
    usePerformance?: boolean;
    /**
     * Whether to collect device entropy
     * @default true
     */
    useDevice?: boolean;
    /**
     * Whether to collect network entropy
     * @default false
     */
    useNetwork?: boolean;
    /**
     * Whether to collect user interaction entropy
     * @default false
     */
    useInteraction?: boolean;
    /**
     * Custom entropy sources to include
     */
    customSources?: Array<() => Uint8Array>;
}
/**
 * Entropy pool that collects and mixes entropy from multiple sources
 */
declare class EntropyPool {
    private static instance;
    private pool;
    private poolSize;
    private poolPosition;
    private reseedCounter;
    private lastReseed;
    private isInitialized;
    private entropyCollected;
    private options;
    /**
     * Creates a new entropy pool
     *
     * @param poolSize - Size of the entropy pool in bytes
     * @param options - Entropy collection options
     */
    private constructor();
    /**
     * Gets the singleton instance of the entropy pool
     *
     * @param poolSize - Size of the entropy pool in bytes
     * @param options - Entropy collection options
     * @returns The entropy pool instance
     */
    static getInstance(poolSize?: number, options?: EntropyOptions): EntropyPool;
    /**
     * Initializes the entropy pool with system random data
     */
    private initializePool;
    /**
     * Sets up continuous entropy collection from various sources
     */
    private setupEntropyCollection;
    /**
     * Collects entropy from timing variations
     */
    private collectTimingEntropy;
    /**
     * Collects entropy from performance measurements
     */
    private collectPerformanceEntropy;
    /**
     * Collects entropy from device information
     */
    private collectDeviceEntropy;
    /**
     * Collects entropy from network information
     */
    private collectNetworkEntropy;
    /**
     * Sets up collection of entropy from user interactions
     */
    private setupInteractionCollection;
    /**
     * Adds entropy to the pool
     *
     * @param data - Entropy data to add
     * @param estimatedEntropy - Estimated entropy in bits (conservative)
     */
    addEntropy(data: Uint8Array, estimatedEntropy?: number): void;
    /**
     * Remixes the entire entropy pool to distribute entropy
     */
    private remixPool;
    /**
     * Gets random bytes from the entropy pool
     *
     * @param length - Number of bytes to get
     * @returns Random bytes
     */
    getRandomBytes(length: number): Uint8Array;
    /**
     * Gets the current entropy source
     *
     * @returns The current entropy source
     */
    getEntropySource(): EntropySource;
    /**
     * Gets the estimated amount of entropy collected
     *
     * @returns Estimated entropy in bits
     */
    getEstimatedEntropy(): number;
}

/**
 * Log level
 */
declare enum LogLevel {
    DEBUG = "DEBUG",
    INFO = "INFO",
    WARNING = "WARNING",
    ERROR = "ERROR",
    CRITICAL = "CRITICAL"
}
/**
 * Log entry
 */
interface LogEntry {
    /**
     * Unique identifier for the log entry
     */
    id: string;
    /**
     * Timestamp when the log entry was created
     */
    timestamp: number;
    /**
     * Log level
     */
    level: LogLevel;
    /**
     * Log message
     */
    message: string;
    /**
     * Additional data
     */
    data?: any;
    /**
     * Hash of the previous log entry
     */
    previousHash: string;
    /**
     * Hash of this log entry
     */
    hash: string;
    /**
     * Sequence number
     */
    sequence: number;
}
/**
 * Log verification result
 */
interface LogVerificationResult {
    /**
     * Whether the log chain is valid
     */
    valid: boolean;
    /**
     * List of invalid entries
     */
    invalidEntries: number[];
    /**
     * List of missing entries
     */
    missingEntries: number[];
    /**
     * List of tampered entries
     */
    tamperedEntries: number[];
}
/**
 * Tamper-evident logger
 */
declare class TamperEvidentLogger {
    private entries;
    private lastHash;
    private sequence;
    private key;
    private storageKey?;
    /**
     * Creates a new tamper-evident logger
     *
     * @param key - Secret key for hashing
     * @param storageKey - Key for storing logs in localStorage (if available)
     */
    constructor(key?: string, storageKey?: string);
    /**
     * Adds a genesis entry to the log
     */
    private addGenesisEntry;
    /**
     * Generates a unique ID for a log entry
     *
     * @returns Unique ID
     */
    private generateId;
    /**
     * Calculates the hash of a log entry
     *
     * @param entry - Log entry to hash
     * @returns Hash of the log entry
     */
    private calculateHash;
    /**
     * Loads logs from storage
     */
    private loadFromStorage;
    /**
     * Saves logs to storage
     */
    private saveToStorage;
    /**
     * Adds a log entry
     *
     * @param level - Log level
     * @param message - Log message
     * @param data - Additional data
     * @returns The created log entry
     */
    log(level: LogLevel, message: string, data?: any): LogEntry;
    /**
     * Logs a debug message
     *
     * @param message - Log message
     * @param data - Additional data
     * @returns The created log entry
     */
    debug(message: string, data?: any): LogEntry;
    /**
     * Logs an info message
     *
     * @param message - Log message
     * @param data - Additional data
     * @returns The created log entry
     */
    info(message: string, data?: any): LogEntry;
    /**
     * Logs a warning message
     *
     * @param message - Log message
     * @param data - Additional data
     * @returns The created log entry
     */
    warning(message: string, data?: any): LogEntry;
    /**
     * Logs an error message
     *
     * @param message - Log message
     * @param data - Additional data
     * @returns The created log entry
     */
    error(message: string, data?: any): LogEntry;
    /**
     * Logs a critical message
     *
     * @param message - Log message
     * @param data - Additional data
     * @returns The created log entry
     */
    critical(message: string, data?: any): LogEntry;
    /**
     * Gets all log entries
     *
     * @returns All log entries
     */
    getEntries(): LogEntry[];
    /**
     * Gets log entries by level
     *
     * @param level - Log level
     * @returns Log entries with the specified level
     */
    getEntriesByLevel(level: LogLevel): LogEntry[];
    /**
     * Gets log entries by time range
     *
     * @param startTime - Start time
     * @param endTime - End time
     * @returns Log entries within the specified time range
     */
    getEntriesByTimeRange(startTime: number, endTime: number): LogEntry[];
    /**
     * Verifies the integrity of the log chain
     *
     * @returns Verification result
     */
    verify(): LogVerificationResult;
    /**
     * Exports the logs to a string
     *
     * @returns Exported logs
     */
    export(): string;
    /**
     * Imports logs from a string
     *
     * @param data - Exported logs
     * @param verify - Whether to verify the logs after importing
     * @returns Verification result if verify is true
     */
    import(data: string, verify?: boolean): LogVerificationResult | undefined;
    /**
     * Clears all logs
     */
    clear(): void;
}

/**
 * Options for HMAC operations
 */
interface HMACOptions {
    key: string | SecureString | Uint8Array;
    algorithm: HMACAlgorithm;
}
/**
 * Options for PBKDF2 key derivation
 */
interface PBKDF2Options {
    salt: string | Uint8Array;
    iterations: number;
    keyLength: number;
    hash: HashAlgorithm$1;
}
/**
 * Hash output formats
 */
type HashOutputFormat = "hex" | "base64" | "base64url" | "uint8array";
/**
 * Supported cryptographic hash algorithms
 */
type HashAlgorithm$1 = "SHA-1" | "SHA-256" | "SHA-384" | "SHA-512";
/**
 * Supported HMAC algorithms
 */
type HMACAlgorithm = "HMAC-SHA-1" | "HMAC-SHA-256" | "HMAC-SHA-384" | "HMAC-SHA-512";
/**
 * Supported key derivation algorithms
 */
type KDFAlgorithm = "PBKDF2" | "HKDF";
/**
 * All supported cryptographic algorithms
 */
type CryptoAlgorithm = HashAlgorithm$1 | HMACAlgorithm | KDFAlgorithm;
/**
 * Algorithm metadata including output size and security level
 */
interface AlgorithmInfo {
    readonly name: string;
    readonly outputSize: number;
    readonly securityLevel: "weak" | "acceptable" | "strong" | "very-strong";
    readonly deprecated: boolean;
    readonly description: string;
}

/**
 * Type definitions for SecureString modular architecture
 */

/**
 * Configuration options for SecureString
 */
interface SecureStringOptions {
    /** Protection level for the underlying buffer */
    protectionLevel?: "basic" | "enhanced" | "maximum";
    /** Enable encryption for the buffer */
    enableEncryption?: boolean;
    /** Enable fragmentation for the buffer */
    enableFragmentation?: boolean;
    /** Enable canaries for the buffer */
    enableCanaries?: boolean;
    /** Enable obfuscation for the buffer */
    enableObfuscation?: boolean;
    /** Auto-lock the buffer */
    autoLock?: boolean;
    /** Use quantum-safe protection */
    quantumSafe?: boolean;
    /** Text encoding to use */
    encoding?: string;
    /** Enable advanced memory tracking */
    enableMemoryTracking?: boolean;
}
/**
 * String comparison result
 */
interface ComparisonResult {
    isEqual: boolean;
    timeTaken?: number;
    constantTime: boolean;
}
/**
 * String search options
 */
interface SearchOptions {
    caseSensitive?: boolean;
    wholeWord?: boolean;
    startPosition?: number;
    endPosition?: number;
}
/**
 * String split options
 */
interface SplitOptions {
    limit?: number;
    removeEmpty?: boolean;
    trim?: boolean;
}
/**
 * String validation result
 */
interface ValidationResult {
    isValid: boolean;
    errors: string[];
    warnings: string[];
    score?: number;
}
/**
 * String statistics
 */
interface StringStatistics {
    length: number;
    byteLength: number;
    characterCount: Record<string, number>;
    hasUpperCase: boolean;
    hasLowerCase: boolean;
    hasNumbers: boolean;
    hasSpecialChars: boolean;
    entropy: number;
}
/**
 * Event types for SecureString operations
 */
type SecureStringEvent = "created" | "modified" | "accessed" | "hashed" | "compared" | "destroyed";
/**
 * Event listener callback for SecureString
 */
type SecureStringEventListener = (event: SecureStringEvent, details?: any) => void;
/**
 * Memory usage information
 */
interface MemoryUsage {
    bufferSize: number;
    actualLength: number;
    overhead: number;
    isFragmented: boolean;
    isEncrypted: boolean;
}

/**
 * String Validator Module
 * Handles validation and analysis of string content
 */

/**
 * Handles string validation and analysis
 */
declare class StringValidator {
    /**
     * Validates if a string meets password requirements
     */
    static validatePassword(password: string, requirements?: {
        minLength?: number;
        maxLength?: number;
        requireUppercase?: boolean;
        requireLowercase?: boolean;
        requireNumbers?: boolean;
        requireSpecialChars?: boolean;
        forbiddenPatterns?: RegExp[];
        customRules?: Array<(password: string) => string | null>;
    }): ValidationResult;
    /**
     * Validates email format
     */
    static validateEmail(email: string): ValidationResult;
    /**
     * Validates URL format
     */
    static validateURL(url: string): ValidationResult;
    /**
     * Validates phone number format
     */
    static validatePhoneNumber(phone: string, format?: 'international' | 'us' | 'flexible'): ValidationResult;
    /**
     * Validates credit card number using Luhn algorithm
     */
    static validateCreditCard(cardNumber: string): ValidationResult;
    /**
     * Calculates password strength score (0-100)
     */
    static calculatePasswordStrength(password: string): number;
    /**
     * Calculates Shannon entropy of a string
     */
    static calculateEntropy(str: string): number;
    /**
     * Gets detailed string statistics
     */
    static getStringStatistics(str: string): StringStatistics;
    /**
     * Checks if string contains only printable ASCII characters
     */
    static isPrintableASCII(str: string): boolean;
    /**
     * Checks if string is valid UTF-8
     */
    static isValidUTF8(str: string): boolean;
    /**
     * Validates JSON string
     */
    static validateJSON(str: string): ValidationResult;
    /**
     * Validates XML string (basic check)
     */
    static validateXML(str: string): ValidationResult;
}

/**
 * Advanced Entropy Analyzer Module
 * Provides sophisticated entropy analysis for SecureString
 */
/**
 * Advanced entropy analysis results
 */
interface EntropyAnalysisResult {
    shannonEntropy: number;
    minEntropy: number;
    maxEntropy: number;
    compressionRatio: number;
    patternComplexity: number;
    characterDistribution: Record<string, number>;
    bigramEntropy: number;
    trigramEntropy: number;
    predictability: number;
    randomnessScore: number;
    recommendations: string[];
}
/**
 * Pattern analysis results
 */
interface PatternAnalysisResult {
    repeatingPatterns: Array<{
        pattern: string;
        count: number;
        positions: number[];
    }>;
    sequentialPatterns: Array<{
        pattern: string;
        type: 'ascending' | 'descending';
    }>;
    keyboardPatterns: Array<{
        pattern: string;
        layout: string;
    }>;
    dictionaryWords: Array<{
        word: string;
        position: number;
        confidence: number;
    }>;
    commonSubstitutions: Array<{
        original: string;
        substituted: string;
    }>;
    overallComplexity: number;
}

/**
 * Quantum-Safe Operations Module
 * Provides quantum-resistant cryptographic operations for SecureString
 */

/**
 * Quantum-safe algorithm options
 */
interface QuantumSafeOptions {
    algorithm: "CRYSTALS-Dilithium" | "FALCON" | "SPHINCS+" | "Post-Quantum-Hash";
    securityLevel: 128 | 192 | 256;
    useHybridMode?: boolean;
    classicalFallback?: HashAlgorithm$1;
}
/**
 * Quantum-safe hash result
 */
interface QuantumSafeHashResult {
    hash: string | Uint8Array;
    algorithm: string;
    securityLevel: number;
    isQuantumSafe: boolean;
    hybridMode: boolean;
    metadata: {
        timestamp: Date;
        rounds: number;
        saltLength: number;
        keyLength: number;
    };
}
/**
 * Quantum-safe key derivation result
 */
interface QuantumSafeKeyResult {
    derivedKey: string | Uint8Array;
    salt: string | Uint8Array;
    algorithm: string;
    iterations: number;
    securityLevel: number;
    isQuantumSafe: boolean;
    metadata: {
        timestamp: Date;
        memoryUsage: number;
        computationTime: number;
    };
}

/**
 * Performance statistics
 */
interface PerformanceStats {
    totalOperations: number;
    averageDuration: number;
    minDuration: number;
    maxDuration: number;
    totalMemoryUsed: number;
    averageMemoryUsage: number;
    operationBreakdown: Record<string, number>;
    throughputStats: {
        average: number;
        peak: number;
        current: number;
    };
    recommendations: string[];
}
/**
 * Performance benchmark result
 */
interface BenchmarkResult {
    operation: string;
    iterations: number;
    totalTime: number;
    averageTime: number;
    operationsPerSecond: number;
    memoryEfficiency: number;
    scalabilityScore: number;
    recommendations: string[];
}

/**
 * A secure string that can be explicitly cleared from memory with modular architecture
 */
declare class SecureString {
    private bufferManager;
    private eventListeners;
    private _isDestroyed;
    private readonly _id;
    private _memoryTracking;
    private _createdAt;
    private secureStringPool?;
    /**
     * Creates a new secure string with enhanced memory management
     */
    constructor(value?: string, options?: SecureStringOptions);
    /**
     * Creates a SecureString from another SecureString (copy constructor)
     */
    static from(other: SecureString): SecureString;
    /**
     * Creates a SecureString from a buffer
     */
    static fromBuffer(buffer: Uint8Array, options?: SecureStringOptions, encoding?: string): SecureString;
    /**
     * Gets the string value
     */
    toString(): string;
    /**
     * Gets the raw buffer (copy)
     */
    toBuffer(): Uint8Array;
    /**
     * Gets the length of the string
     */
    length(): number;
    /**
     * Gets the byte length of the string in UTF-8 encoding
     */
    byteLength(): number;
    /**
     * Checks if the string is empty
     */
    isEmpty(): boolean;
    /**
     * Checks if the SecureString has been destroyed
     */
    isDestroyed(): boolean;
    /**
     * Appends another string
     */
    append(value: string | SecureString): SecureString;
    /**
     * Prepends another string
     */
    prepend(value: string | SecureString): SecureString;
    /**
     * Replaces the entire content with a new value
     */
    replace(value: string | SecureString): SecureString;
    /**
     * Extracts a substring
     */
    substring(start: number, end?: number): SecureString;
    /**
     * Splits the string into an array of SecureStrings
     */
    split(separator: string | RegExp, options?: SplitOptions): SecureString[];
    /**
     * Trims whitespace from both ends
     */
    trim(): SecureString;
    /**
     * Converts to uppercase
     */
    toUpperCase(): SecureString;
    /**
     * Converts to lowercase
     */
    toLowerCase(): SecureString;
    /**
     * Compares this SecureString with another string (constant-time comparison)
     */
    equals(other: string | SecureString, constantTime?: boolean): boolean;
    /**
     * Performs detailed comparison with timing information
     */
    compare(other: string | SecureString, constantTime?: boolean): ComparisonResult;
    /**
     * Checks if the string contains a substring
     */
    includes(searchString: string | SecureString, options?: SearchOptions): boolean;
    /**
     * Checks if the string starts with a prefix
     */
    startsWith(searchString: string | SecureString, options?: SearchOptions): boolean;
    /**
     * Checks if the string ends with a suffix
     */
    endsWith(searchString: string | SecureString, options?: SearchOptions): boolean;
    /**
     * Validates the string as a password
     */
    validatePassword(requirements?: Parameters<typeof StringValidator.validatePassword>[1]): ValidationResult;
    /**
     * Validates the string as an email
     */
    validateEmail(): ValidationResult;
    /**
     * Gets detailed string statistics
     */
    getStatistics(): StringStatistics;
    /**
     * Ensures the SecureString hasn't been destroyed
     */
    private ensureNotDestroyed;
    /**
     * Emits an event to all registered listeners
     */
    private emit;
    /**
     * Creates a hash of the string content
     */
    hash(algorithm?: HashAlgorithm$1, format?: HashOutputFormat): Promise<string | Uint8Array>;
    /**
     * Creates an HMAC of the string content
     */
    hmac(options: HMACOptions, format?: HashOutputFormat): Promise<string | Uint8Array>;
    /**
     * Derives a key using PBKDF2
     */
    deriveKeyPBKDF2(options: PBKDF2Options, format?: HashOutputFormat): Promise<string | Uint8Array>;
    /**
     * Performs comprehensive entropy analysis
     */
    analyzeEntropy(): EntropyAnalysisResult;
    /**
     * Analyzes patterns in the string
     */
    analyzePatterns(): PatternAnalysisResult;
    /**
     * Creates a quantum-safe hash
     */
    createQuantumSafeHash(options: QuantumSafeOptions, format?: HashOutputFormat): Promise<QuantumSafeHashResult>;
    /**
     * Derives a quantum-safe key
     */
    deriveQuantumSafeKey(options: QuantumSafeOptions, keyLength?: number, format?: HashOutputFormat): Promise<QuantumSafeKeyResult>;
    /**
     * Verifies a quantum-safe hash
     */
    verifyQuantumSafeHash(expectedHash: string | Uint8Array, options: QuantumSafeOptions, format?: HashOutputFormat): Promise<boolean>;
    /**
     * Starts performance monitoring for this SecureString
     */
    startPerformanceMonitoring(): void;
    /**
     * Stops performance monitoring
     */
    stopPerformanceMonitoring(): void;
    /**
     * Gets performance statistics
     */
    getPerformanceStats(): PerformanceStats;
    /**
     * Benchmarks a specific operation on this SecureString
     */
    benchmarkOperation(operation: () => Promise<any> | any, operationName: string, iterations?: number): Promise<BenchmarkResult>;
    /**
     * Measures an operation with automatic performance recording
     */
    measureOperation<T>(operation: () => Promise<T> | T, operationType: string): Promise<T>;
    /**
     * Adds an event listener
     */
    addEventListener(event: SecureStringEvent, listener: SecureStringEventListener): void;
    /**
     * Removes an event listener
     */
    removeEventListener(event: SecureStringEvent, listener: SecureStringEventListener): void;
    /**
     * Removes all event listeners
     */
    removeAllEventListeners(event?: SecureStringEvent): void;
    /**
     * Gets memory usage information
     */
    getMemoryUsage(): MemoryUsage;
    /**
     * Gets the current options
     */
    getOptions(): Required<SecureStringOptions>;
    /**
     * Updates the options (may recreate buffer)
     */
    updateOptions(newOptions: Partial<SecureStringOptions>): void;
    /**
     * Creates a shallow copy of the SecureString
     */
    clone(): SecureString;
    /**
     * Executes a function with the string value and optionally clears it afterward
     */
    use<T>(fn: (value: string) => T, autoClear?: boolean): T;
    /**
     * Initialize secure string pool for efficient memory reuse
     */
    private initializeSecureStringPool;
    /**
     * Handle memory pressure situations
     */
    private handleMemoryPressure;
    /**
     * Secure wipe of buffer memory
     */
    private secureWipe;
    /**
     * Get enhanced memory usage statistics
     */
    getEnhancedMemoryUsage(): {
        bufferSize: number;
        actualLength: number;
        overhead: number;
        isFragmented: boolean;
        isEncrypted: boolean;
        formattedSize: string;
        age: number;
        poolStats?: any;
    };
    /**
     * Force garbage collection for this SecureString
     */
    forceGarbageCollection(): void;
    /**
     * Enable memory tracking for this SecureString
     */
    enableMemoryTracking(): this;
    /**
     * Disable memory tracking for this SecureString
     */
    disableMemoryTracking(): this;
    /**
     * Clears the string by zeroing its contents and marks as destroyed
     */
    clear(): void;
    /**
     * Alias for clear() - destroys the SecureString
     */
    destroy(): void;
    /**
     * Securely wipes the content without destroying the SecureString
     */
    wipe(): void;
    /**
     * Creates a JSON representation (warning: exposes the value)
     */
    toJSON(): {
        value: string;
        length: number;
        byteLength: number;
    };
    /**
     * Gets information about available algorithms
     */
    static getAlgorithmInfo(): Record<CryptoAlgorithm, AlgorithmInfo>;
    /**
     * Lists all supported hash algorithms
     */
    static getSupportedHashAlgorithms(): HashAlgorithm$1[];
    /**
     * Lists all supported HMAC algorithms
     */
    static getSupportedHMACAlgorithms(): HMACAlgorithm[];
    /**
     * Generates a cryptographically secure salt
     */
    static generateSalt(length?: number, format?: HashOutputFormat): string | Uint8Array<ArrayBufferLike>;
    /**
     * Performs constant-time hash comparison
     */
    static constantTimeHashCompare(hash1: string, hash2: string): boolean;
}

/**
 * Factory functions for common use cases
 */
/**
 * Creates a new SecureString with default settings
 */
declare function createSecureString(...args: ConstructorParameters<typeof SecureString>): SecureString;

/***************************************************************************
 * 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.
 ***************************************************************************** */
/**
 * Type definitions for SecureObject modular architecture
 */

/**
 * Types that can be stored securely
 */
type SecureValue = string | number | boolean | Uint8Array | SecureString | any | null | undefined;
/**
 * Serialization options for SecureObject
 */
interface SerializationOptions$1 {
    includeMetadata?: boolean;
    encryptSensitive?: boolean;
    format?: "json" | "binary";
}
/**
 * Metadata for tracking secure values
 */
interface ValueMetadata {
    type: string;
    isSecure: boolean;
    created: Date;
    lastAccessed: Date;
    accessCount: number;
}
/**
 * Event types for SecureObject
 */
type SecureObjectEvent = "set" | "get" | "delete" | "clear" | "destroy" | "filtered" | "gc";
/**
 * Event listener callback
 */
type EventListener = (event: SecureObjectEvent, key?: string, value?: any) => void | Promise<void>;
/**
 * Configuration options for SecureObject
 */
interface SecureObjectOptions {
    readOnly?: boolean;
    autoDestroy?: boolean;
    encryptionKey?: string;
    maxMemory?: number;
    gcThreshold?: number;
    enableMemoryTracking?: boolean;
    autoCleanup?: boolean;
}
/**
 * Internal data structure for storing values
 */
interface SecureObjectData {
    data: Map<string, any>;
    secureBuffers: Map<string, any>;
    metadata: Map<string, ValueMetadata>;
}

/***************************************************************************
 * 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.
 ***************************************************************************** */
/**
 * @license MIT
 * @see https://lab.nehonix.space
 * @description SecureObject Core Module
 *
 * Main SecureObject class
 */

/**
 * A secure object that can store sensitive data
 * T represents the initial type, but the object can be extended with additional keys
 */
declare class SecureObject<T extends Record<string, SecureValue> = Record<string, SecureValue>> {
    private data;
    private secureBuffers;
    private sensitiveKeysManager;
    private cryptoHandler;
    private metadataManager;
    private eventManager;
    private serializationHandler;
    private _isDestroyed;
    private _isReadOnly;
    private readonly _id;
    private _memoryTracking;
    private _autoCleanup;
    private _createdAt;
    private _lastAccessed;
    private secureBufferPool?;
    /**
     * Creates a new secure object
     */
    constructor(initialData?: Partial<T>, options?: SecureObjectOptions);
    /**
     * Creates a SecureObject from another SecureObject (deep copy)
     */
    static from<T extends Record<string, SecureValue>>(other: SecureObject<T>): SecureObject<T>;
    /**
     * Creates a read-only SecureObject
     */
    static readOnly<T extends Record<string, SecureValue>>(data: Partial<T>): SecureObject<T>;
    /**
     * Creates a read-only SecureObject (public usage)
     */
    /** Permanently enable read-only mode (cannot be disabled). */
    enableReadOnly(): this;
    /**
     * Gets the unique ID of this SecureObject
     */
    get id(): string;
    /**
     * Checks if the SecureObject is read-only
     */
    get isReadOnly(): boolean;
    /**
     * Checks if the SecureObject has been destroyed
     */
    get isDestroyed(): boolean;
    /**
     * Gets the number of stored values
     */
    get size(): number;
    /**
     * Checks if the object is empty
     */
    get isEmpty(): boolean;
    /**
     * Ensures the SecureObject hasn't been destroyed
     */
    private ensureNotDestroyed;
    /**
     * Ensures the SecureObject is not read-only for write operations
     */
    private ensureNotReadOnly;
    /**
     * Updates the last accessed timestamp for memory management
     */
    private updateLastAccessed;
    /**
     * Initialize secure buffer pool for efficient memory reuse
     */
    private initializeSecureBufferPool;
    /**
     * Handle memory pressure situations
     */
    private handleMemoryPressure;
    /**
     * Secure wipe of buffer memory
     */
    private secureWipe;
    /**
     * Gets enhanced memory usage statistics for this SecureObject
     */
    getMemoryUsage(): {
        allocatedMemory: number;
        bufferCount: number;
        dataSize: number;
        createdAt: number;
        lastAccessed: number;
        age: number;
        formattedMemory: string;
        poolStats?: any;
    };
    /**
     * Forces enhanced garbage collection for this SecureObject
     */
    forceGarbageCollection(): void;
    /**
     * Enables memory tracking for this SecureObject
     */
    enableMemoryTracking(): this;
    /**
     * Disables memory tracking for this SecureObject
     */
    disableMemoryTracking(): this;
    /**
     * Adds keys to the sensitive keys list
     */
    addSensitiveKeys(...keys: string[]): this;
    /**
     * Removes keys from the sensitive keys list
     */
    removeSensitiveKeys(...keys: string[]): this;
    /**
     * Sets the complete list of sensitive keys (replaces existing list)
     */
    setSensitiveKeys(keys: string[]): this;
    /**
     * Gets the current list of sensitive keys
     */
    getSensitiveKeys(): string[];
    /**
     * Checks if a key is marked as sensitive
     */
    isSensitiveKey(key: string): boolean;
    /**
     * Clears all sensitive keys
     */
    clearSensitiveKeys(): this;
    /**
     * Resets sensitive keys to default values
     */
    resetToDefaultSensitiveKeys(): this;
    /**
     * Gets the default sensitive keys that are automatically initialized
     */
    static get getDefaultSensitiveKeys(): string[];
    /**
     * Adds custom regex patterns for sensitive key detection
     * @param patterns - Regex patterns or strings to match sensitive keys
     */
    addSensitivePatterns(...patterns: (RegExp | string)[]): this;
    /**
     * Removes custom sensitive patterns
     */
    removeSensitivePatterns(...patterns: (RegExp | string)[]): this;
    /**
     * Clears all custom sensitive patterns
     */
    clearSensitivePatterns(): this;
    /**
     * Gets all custom sensitive patterns
     */
    getSensitivePatterns(): RegExp[];
    /**
     * Sets the encryption key for sensitive data encryption
     */
    setEncryptionKey(key?: string | null): this;
    /**
     * Gets the current encryption key
     */
    get getEncryptionKey(): string | null;
    /**
     * Decrypts a value using the encryption key
     */
    decryptValue(encryptedValue: string): any;
    /**
     * Decrypts all encrypted values in an object
     */
    decryptObject(obj: any): any;
    /**
     * Encrypts all values in the object using AES-256-CTR-HMAC encryption
     * with proper memory management and atomic operations
     */
    encryptAll(): this;
    /**
     * Gets the raw encrypted data without decryption (for verification)
     */
    getRawEncryptedData(): Map<string, any>;
    /**
     * Gets a specific key's raw encrypted form (for verification)
     */
    getRawEncryptedValue(key: string): any;
    /**
     * Gets encryption status from the crypto handler
     */
    getEncryptionStatus(): {
        isInitialized: boolean;
        hasEncryptionKey: boolean;
        algorithm: string;
    };
    /**
     * Adds an event listener
     */
    addEventListener(event: SecureObjectEvent, listener: EventListener): void;
    /**
     * Removes an event listener
     */
    removeEventListener(event: SecureObjectEvent, listener: EventListener): void;
    /**
     * Creates a one-time event listener
     */
    once(event: SecureObjectEvent, listener: EventListener): void;
    /**
     * Waits for a specific event to be emitted
     */
    waitFor(event: SecureObjectEvent, timeout?: number): Promise<{
        key?: string;
        value?: any;
    }>;
    /**
     * Sets a value - allows both existing keys and new dynamic keys
     */
    set<K extends string>(key: K, value: SecureValue): this;
    /**
     * Sets multiple values at once
     */
    setAll(values: Partial<T>): this;
    /**
     * Gets a value with automatic decryption
     */
    get<K extends keyof T>(key: K): T[K];
    /**
     * Gets a value safely, returning undefined if key doesn't exist
     */
    getSafe<K extends keyof T>(key: K): T[K] | undefined;
    /**
     * Gets a value with a default fallback
     */
    getWithDefault<K extends keyof T>(key: K, defaultValue: T[K]): T[K];
    /**
     * Checks if a key exists
     */
    has<K extends keyof T>(key: K): boolean;
    /**
     * Deletes a key - allows both existing keys and dynamic keys
     */
    delete<K extends string>(key: K): boolean;
    /**
     * Cleans up resources associated with a key
     */
    private cleanupKey;
    /**
     * Clears all data
     */
    clear(): void;
    /**
     * Gets all keys
     */
    keys(): Array<keyof T>;
    /**
     * Gets all values
     */
    values(): Array<T[keyof T]>;
    /**
     * Gets all entries as [key, value] pairs
     */
    entries(): Array<[keyof T, T[keyof T]]>;
    /**
     * Iterates over each key-value pair
     */
    forEach(callback: (value: T[keyof T], key: keyof T, obj: this) => void): void;
    /**
     * Maps over values and returns a new array
     */
    map<U>(callback: (value: T[keyof T], key: keyof T, obj: this) => U): U[];
    /**
     * Filters entries based on a predicate function (like Array.filter)
     * Returns a new SecureObject with only the entries that match the condition
     */
    filter(predicate: (value: T[keyof T], key: keyof T, obj: this) => boolean): SecureObject<Partial<T>>;
    /**
     * Filters entries by specific key names (type-safe for known keys)
     * Returns a new SecureObject with only the specified keys
     *
     * @example
     * const user = createSecureObject({ name: "John", password: "secret", age: 30 });
     * const credentials = user.filterByKeys("name", "password");
     */
    filterByKeys<K extends keyof T>(...keys: K[]): SecureObject<Pick<T, K>>;
    /**
     * Filters entries by value type using a type guard function
     * Returns a new SecureObject with only values of the specified type
     *
     * @example
     * const data = createSecureObject({ name: "John", age: 30, active: true });
     * const strings = data.filterByType((v): v is string => typeof v === "string");
     */
    filterByType<U>(typeGuard: (value: any) => value is U): SecureObject<Record<string, U>>;
    /**
     * Filters entries to only include sensitive keys
     * Returns a new SecureObject with only sensitive data
     *
     * @example
     * const user = createSecureObject({ name: "John", password: "secret", age: 30 });
     * user.addSensitiveKeys("password");
     * const sensitiveData = user.filterSensitive(); // Only contains password
     */
    filterSensitive(): SecureObject<Partial<T>>;
    /**
     * Filters entries to exclude sensitive keys
     * Returns a new SecureObject with only non-sensitive data
     *
     * @example
     * const user = createSecureObject({ name: "John", password: "secret", age: 30 });
     * user.addSensitiveKeys("password");
     * const publicData = user.filterNonSensitive(); // Contains name and age
     */
    filterNonSensitive(options?: {
        strictMode?: boolean;
    }): SecureObject<Partial<T>>;
    /**
     * Processes nested objects for filtering with the same strict mode
     */
    private processNestedObjectForFiltering;
    /**
     * Gets metadata for a specific key
     */
    getMetadata<K extends keyof T>(key: K): ValueMetadata | undefined;
    /**
     * Gets metadata for all keys
     */
    getAllMetadata(): Map<string, ValueMetadata>;
    /**
     * Converts to a regular object with security-focused serialization
     *
     * BEHAVIOR: This is the security-focused method that handles sensitive key filtering.
     * Use this method when you need controlled access to data with security considerations.
     * For simple object conversion without filtering, use toObject().
     *
     *  @example
     * const user = fObject({
        id: "1",
        email: "test@test.com",
        password: "test123",
        isVerified: true,
        userName: "test",
        firstName: "test",
        lastName: "test",
        bio: "test",
        });

        const getAllResult = user.getAll();
        console.log("getAllResult.email:", getAllResult.email);
        console.log("getAllResult.password:", getAllResult.password);
        console.log("Has password?", "password" in getAllResult);
        
        // Purpose: Security-conscious data access
        // Behavior: Filters out sensitive keys by default
        // Result:  password: undefined (filtered for security)
        // With encryptSensitive: true: ✔ password: "[ENCRYPTED:...]" (encrypted but included)
     */
    getAll(options?: SerializationOptions$1): T & {
        _metadata?: Record<string, ValueMetadata>;
    };
    /**
     * Gets the full object as a regular JavaScript object
     *
     * BEHAVIOR: Returns ALL data including sensitive keys (like standard JS object conversion).
     * This method does NOT filter sensitive keys by default - use getAll() for security-focused serialization.
     *
     * @example
     * const user = fObject({
        id: "1",
        email: "test@test.com",
        password: "test123",
        isVerified: true,
        userName: "test",
        firstName: "test",
        lastName: "test",
        bio: "test",
        });

        const toObjectResult = user.toObject();
        console.log("toObjectResult.email:", toObjectResult.email);
        console.log("toObjectResult.password:", toObjectResult.password);
        console.log("Has password?", "password" in toObjectResult);

        // Purpose: Standard JavaScript object conversion
        // Behavior: Returns ALL data including sensitive keys (like password)
        // Result: ✔ password: "test123" (included)

        Sensitive keys can be handled using .add/removeSensitiveKeys()
     */
    toObject(options?: SerializationOptions$1): T & {
        _metadata?: Record<string, ValueMetadata>;
    };
    /**
     * Converts to JSON string
     */
    toJSON(options?: SerializationOptions$1 & {
        strictSensitiveKeys?: boolean;
    }): string;
    /**
     * Creates a hash of the entire object content
     */
    hash(algorithm?: HashAlgorithm$1, format?: HashOutputFormat): Promise<string | Uint8Array>;
    /**
     * Executes a function with the object data and optionally clears it afterward
     */
    use<U>(fn: (obj: this) => U, autoClear?: boolean): U;
    /**
     * Creates a shallow copy of the SecureObject
     */
    clone(): SecureObject<T>;
    /**
     * Merges another object into this one
     */
    merge(other: Partial<T> | SecureObject<Partial<T>>, overwrite?: boolean): this;
    /**
     * Transform values with a mapper function (like Array.map but returns SecureObject)
     * Returns a new SecureObject with transformed values
     */
    transform<U>(mapper: (value: T[keyof T], key: keyof T, obj: this) => U): SecureObject<Record<string, U>>;
    /**
     * Group entries by a classifier function
     * Returns a Map where keys are group identifiers and values are SecureObjects
     */
    groupBy<K extends string | number>(classifier: (value: T[keyof T], key: keyof T) => K): Map<K, SecureObject<Partial<T>>>;
    /**
     * Partition entries into two groups based on a predicate
     * Returns [matching, notMatching] SecureObjects
     */
    partition(predicate: (value: T[keyof T], key: keyof T) => boolean): [SecureObject<Partial<T>>, SecureObject<Partial<T>>];
    /**
     * Pick specific keys (like Lodash pick but type-safe)
     * Returns a new SecureObject with only the specified keys
     */
    pick<K extends keyof T>(...keys: K[]): SecureObject<Pick<T, K>>;
    /**
     * Omit specific keys (opposite of pick)
     * Returns a new SecureObject without the specified keys
     */
    omit<K extends keyof T>(...keys: K[]): SecureObject<Omit<T, K>>;
    /**
     * Flatten nested objects (one level deep)
     * Converts { user: { name: "John" } } to { "user.name": "John" }
     */
    flatten(separator?: string): SecureObject<Record<string, any>>;
    /**
     * Compact - removes null, undefined, and empty values
     * Returns a new SecureObject with only truthy values
     */
    compact(): SecureObject<Partial<T>>;
    /**
     * Invert - swap keys and values
     * Returns a new SecureObject with keys and values swapped
     */
    invert(): SecureObject<Record<string, string>>;
    /**
     * Defaults - merge with default values (only for missing keys)
     * Returns a new SecureObject with defaults applied
     */
    defaults(defaultValues: Partial<T>): SecureObject<T>;
    /**
     * Tap - execute a function with the object and return the object (for chaining)
     * Useful for debugging or side effects in method chains
     */
    tap(fn: (obj: this) => void): this;
    /**
     * Pipe - transform the object through a series of functions
     * Each function receives the result of the previous function
     */
    pipe<U>(fn: (obj: this) => U): U;
    pipe<U, V>(fn1: (obj: this) => U, fn2: (obj: U) => V): V;
    pipe<U, V, W>(fn1: (obj: this) => U, fn2: (obj: U) => V, fn3: (obj: V) => W): W;
    /**
     * Sample - get random entries from the object
     * Returns a new SecureObject with randomly selected entries
     */
    sample(count?: number): SecureObject<Partial<T>>;
    /**
     * Shuffle - return a new SecureObject with keys in random order
     * Returns a new SecureObject with the same data but shuffled key order
     */
    shuffle(): SecureObject<T>;
    /**
     * Chunk - split object into chunks of specified size
     * Returns an array of SecureObjects, each containing up to 'size' entries
     */
    chunk(size: number): SecureObject<Partial<T>>[];
    /**
     * Serializes the SecureObject to a secure format
     */
    serialize(options?: SerializationOptions$1): string;
    /**
     * Exports the SecureObject data in various formats
     */
    exportData(format?: "json" | "csv" | "xml" | "yaml"): string;
    /**
     * Gets serialization metadata
     */
    private getSerializationMetadata;
    /**
     * Exports to CSV format
     */
    private exportToCSV;
    /**
     * Exports to XML format
     */
    private exportToXML;
    /**
     * Exports to YAML format
     */
    private exportToYAML;
    /**
     * Escapes XML special characters
     */
    private escapeXML;
    /**
     * Destroys the SecureObject and clears all data
     */
    destroy(): void;
}

/**
 * Sensitive Keys Management Module
 * Handles the management of sensitive keys for encryption/masking
 */
/**
 * Default sensitive keys that are commonly used in applications
 */
declare const DEFAULT_SENSITIVE_KEYS: readonly ["password", "passwd", "pwd", "secret", "token", "key", "apikey", "api_key", "accesskey", "access_key", "accesstoken", "access_token", "refreshtoken", "refresh_token", "sessionid", "session_id", "auth", "authorization", "bearer", "credential", "credentials", "pin", "ssn", "social_security", "credit_card", "creditcard", "cvv", "cvc", "private_key", "privatekey", "signature", "hash", "salt", "nonce", "otp", "passcode", "passphrase", "masterkey", "master_key", "encryption_key", "decryption_key", "jwt", "cookie", "session", "csrf", "xsrf"];
/**
 * Manages sensitive keys for a SecureObject instance
 */
declare class SensitiveKeysManager {
    private sensitiveKeys;
    private customPatterns;
    constructor(initialKeys?: string[]);
    /**
     * Adds keys to the sensitive keys list
     */
    add(...keys: string[]): this;
    /**
     * Removes keys from the sensitive keys list
     */
    remove(...keys: string[]): this;
    /**
     * Sets the complete list of sensitive keys (replaces existing)
     */
    set(keys: string[]): this;
    /**
     * Gets the current list of sensitive keys
     */
    getAll(): string[];
    /**
     * Adds custom regex patterns for sensitive key detection
     */
    addCustomPatterns(...patterns: (RegExp | string)[]): this;
    /**
     * Removes custom patterns
     */
    removeCustomPatterns(...patterns: (RegExp | string)[]): this;
    /**
     * Clears all custom patterns
     */
    clearCustomPatterns(): this;
    /**
     * Gets all custom patterns
     */
    getCustomPatterns(): RegExp[];
    /**
     * Checks if a key is marked as sensitive
     * Simple approach: exact matches + custom patterns + strict mode patterns
     */
    isSensitive(key: string, strictMode?: boolean): boolean;
    /**
     * Simple strict mode pattern matching
     * Only applies additional patterns when in strict mode
     */
    private isStrictModePattern;
    /**
     * Clears all sensitive keys
     */
    clear(): this;
    /**
     * Resets to default sensitive keys
     */
    resetToDefault(): this;
    /**
     * Gets the default sensitive keys
     */
    static getDefaultKeys(): string[];
}

/**
 * Cryptographic Handler Module
 * Handles encryption and decryption of sensitive data
 */

/**
 * Handles encryption and decryption operations for SecureObject
 */
declare class CryptoHandler {
    private objectId;
    private encryptionKey;
    private derivedKey;
    private isInitialized;
    constructor(objectId: string);
    /**
     * Initialize cryptographic components
     */
    private initializeCrypto;
    /**
     * Sets the encryption key for sensitive data encryption
     */
    setEncryptionKey(key?: string | null): this;
    /**
     * Gets the current encryption key
     */
    getEncryptionKey(): string | null;
    /**
     * Encrypts a value using real AES-256-CTR-HMAC encryption
     */
    encryptValue(value: any): string;
    /**
     * Decrypts a value using real AES-256-CTR-HMAC decryption
     */
    decryptValue(encryptedValue: string): any;
    /**
     * Decrypts all encrypted values in an object recursively
     */
    decryptObject(obj: any): any;
    /**
     * Recursively processes nested objects to check for sensitive keys
     */
    processNestedObject(obj: any, options: SerializationOptions$1, sensitiveKeys: Set<string> | ((key: string) => boolean)): any;
    /**
     * Checks if a value is encrypted
     */
    isEncrypted(value: any): boolean;
    /**
     * Performs the actual encryption using a secure stream cipher
     */
    private performEncryption;
    /**
     * Performs the actual decryption
     */
    private performDecryption;
    /**
     * Generates a secure keystream for encryption/decryption
     */
    private generateKeystream;
    /**
     * Generates HMAC for authentication
     */
    private generateHMAC;
    /**
     * Constant-time comparison to prevent timing attacks
     */
    private constantTimeEqual;
    /**
     * Gets the current encryption status
     */
    getEncryptionStatus(): {
        isInitialized: boolean;
        hasEncryptionKey: boolean;
        algorithm: string;
    };
    /**
     * Securely destroys the crypto handler
     */
    destroy(): void;
}

/**
 * Metadata Manager Module
 * Handles metadata tracking for SecureObject values
 */

/**
 * Manages metadata for SecureObject values
 */
declare class MetadataManager {
    private metadata;
    /**
     * Updates metadata for a key
     */
    update(key: string, type: string, isSecure: boolean, isAccess?: boolean): void;
    /**
     * Gets metadata for a specific key
     */
    get(key: string): ValueMetadata | undefined;
    /**
     * Gets all metadata
     */
    getAll(): Map<string, ValueMetadata>;
    /**
     * Checks if metadata exists for a key
     */
    has(key: string): boolean;
    /**
     * Deletes metadata for a key
     */
    delete(key: string): boolean;
    /**
     * Clears all metadata
     */
    clear(): void;
    /**
     * Gets the number of metadata entries
     */
    get size(): number;
    /**
     * Gets all keys that have metadata
     */
    keys(): string[];
    /**
     * Gets all metadata values
     */
    values(): ValueMetadata[];
    /**
     * Gets all metadata entries as [key, metadata] pairs
     */
    entries(): [string, ValueMetadata][];
    /**
     * Gets statistics about the metadata
     */
    getStats(): {
        totalEntries: number;
        secureEntries: number;
        totalAccesses: number;
        averageAccesses: number;
        oldestEntry: Date | null;
        newestEntry: Date | null;
    };
    /**
     * Filters metadata by criteria
     */
    filter(predicate: (key: string, metadata: ValueMetadata) => boolean): Map<string, ValueMetadata>;
    /**
     * Gets metadata for secure values only
     */
    getSecureMetadata(): Map<string, ValueMetadata>;
    /**
     * Gets metadata for non-secure values only
     */
    getNonSecureMetadata(): Map<string, ValueMetadata>;
    /**
     * Gets the most accessed keys
     */
    getMostAccessed(limit?: number): [string, ValueMetadata][];
    /**
     * Gets the least accessed keys
     */
    getLeastAccessed(limit?: number): [string, ValueMetadata][];
    /**
     * Converts metadata to a plain object for serialization
     */
    toObject(): Record<string, ValueMetadata>;
    /**
     * Creates a MetadataManager from a plain object
     */
    static fromObject(obj: Record<string, ValueMetadata>): MetadataManager;
}

/**
 * Event Manager Module
 * Handles event system for SecureObject
 */

/**
 * Manages events for SecureObject instances
 */
declare class EventManager {
    private eventListeners;
    /**
     * Adds an event listener
     */
    addEventListener(event: SecureObjectEvent, listener: EventListener): void;
    /**
     * Removes an event listener
     */
    removeEventListener(event: SecureObjectEvent, listener: EventListener): void;
    /**
     * Removes all listeners for a specific event
     */
    removeAllListeners(event?: SecureObjectEvent): void;
    /**
     * Emits an event to all registered listeners
     */
    emit(event: SecureObjectEvent, key?: string, value?: any): void;
    /**
     * Gets the number of listeners for an event
     */
    getListenerCount(event: SecureObjectEvent): number;
    /**
     * Gets all registered event types
     */
    getRegisteredEvents(): SecureObjectEvent[];
    /**
     * Gets total number of listeners across all events
     */
    getTotalListenerCount(): number;
    /**
     * Checks if there are any listeners for an event
     */
    hasListeners(event: SecureObjectEvent): boolean;
    /**
     * Checks if there are any listeners at all
     */
    hasAnyListeners(): boolean;
    /**
     * Gets a copy of all listeners for an event
     */
    getListeners(event: SecureObjectEvent): EventListener[];
    /**
     * Creates a one-time event listener that removes itself after first execution
     */
    once(event: SecureObjectEvent, listener: EventListener): void;
    /**
     * Creates a promise that resolves when a specific event is emitted
     */
    waitFor(event: SecureObjectEvent, timeout?: number): Promise<{
        key?: string;
        value?: any;
    }>;
    /**
     * Emits an event and waits for all listeners to complete (if they return promises)
     */
    emitAsync(event: SecureObjectEvent, key?: string, value?: any): Promise<void>;
    /**
     * Creates a filtered event listener that only triggers for specific keys
     */
    addKeyFilteredListener(event: SecureObjectEvent, keys: string[], listener: EventListener): void;
    /**
     * Clears all event listeners (used during destruction)
     */
    clear(): void;
    /**
     * Gets debug information about the event system
     */
    getDebugInfo(): {
        totalEvents: number;
        totalListeners: number;
        eventBreakdown: Record<SecureObjectEvent, number>;
    };
}

/**
 * Serialization Handler Module
 * Handles object serialization and format conversion
 */

/**
 * Handles serialization operations for SecureObject
 */
declare class SerializationHandler {
    private cryptoHandler;
    private metadataManager;
    constructor(cryptoHandler: CryptoHandler, metadataManager: MetadataManager);
    /**
     * Converts SecureObject data to a regular object
     */
    toObject<T>(data: Map<string, any>, sensitiveKeys: Set<string> | ((key: string) => boolean), options?: SerializationOptions$1): T & {
        _metadata?: Record<string, ValueMetadata>;
    };
    /**
     * Processes a single value for serialization
     */
    private processValue;
    /**
     * Applies format transformation to the result
     */
    private applyFormat;
    /**
     * Converts to JSON string
     */
    toJSON<T>(data: Map<string, any>, sensitiveKeys: Set<string> | ((key: string) => boolean), options?: SerializationOptions$1): string;
    /**
     * Creates a deterministic representation for hashing
     */
    createHashableRepresentation(entries: Array<[any, any]>): string;
    /**
     * Processes nested objects recursively for sensitive key detection
     */
    processNestedObject(obj: any, options: SerializationOptions$1, sensitiveKeys: Set<string> | ((key: string) => boolean)): any;
    /**
     * Validates serialization options
     */
    validateOptions(options: SerializationOptions$1): void;
    /**
     * Gets serialization statistics
     */
    getSerializationStats(data: Map<string, any>): {
        totalKeys: number;
        secureBufferCount: number;
        secureStringCount: number;
        nestedObjectCount: number;
        primitiveCount: number;
    };
    /**
     * Estimates serialized size
     */
    estimateSerializedSize(data: Map<string, any>, options?: SerializationOptions$1): number;
}

/**
 * ID Generator Utility
 * Generates unique IDs for SecureObject instances
 */
/**
 * Generates unique IDs for SecureObject instances
 */
declare class IdGenerator {
    /**
     * Generates a unique ID for a SecureObject instance
     */
    static generate(): string;
    /**
     * Generates a unique ID with custom prefix
     */
    static generateWithPrefix(prefix: string): string;
    /**
     * Generates a unique ID with custom size
     */
    static generateWithSize(size: number): string;
    /**
     * Generates a unique ID with custom prefix and size
     */
    static generateCustom(prefix: string, size: number): string;
    /**
     * Validates if a string looks like a valid SecureObject ID
     */
    static isValidId(id: string): boolean;
    /**
     * Extracts the prefix from an ID
     */
    static extractPrefix(id: string): string | null;
    /**
     * Extracts the unique part from an ID (without prefix)
     */
    static extractUniquePart(id: string): string | null;
}

/**
 * Validation Utilities
 * Common validation functions for SecureObject
 */

/**
 * Validation utilities for SecureObject
 */
declare class ValidationUtils {
    /**
     * Validates if a value is a valid SecureValue type
     */
    static isValidSecureValue(value: any): value is SecureValue;
    /**
     * Checks if a value is a SecureString instance
     */
    static isSecureString(value: any): boolean;
    /**
     * Checks if a value is a SecureObject instance
     */
    static isSecureObject(value: any): boolean;
    /**
     * Validates serialization options
     */
    static validateSerializationOptions(options: SerializationOptions$1): void;
    /**
     * Validates a key for SecureObject operations
     */
    static validateKey(key: any): void;
    /**
     * Validates an array of keys
     */
    static validateKeys(keys: any[]): void;
    /**
     * Validates an encryption key
     */
    static validateEncryptionKey(key: any): void;
    /**
     * Validates a timeout value
     */
    static validateTimeout(timeout: any): void;
    /**
     * Validates a limit value for pagination/filtering
     */
    static validateLimit(limit: any): void;
    /**
     * Validates a callback function
     */
    static validateCallback(callback: any, name?: string): void;
    /**
     * Validates an event listener
     */
    static validateEventListener(listener: any): void;
    /**
     * Validates an event type
     */
    static validateEventType(event: any): void;
    /**
     * Validates a predicate function
     */
    static validatePredicate(predicate: any): void;
    /**
     * Validates a mapping function
     */
    static validateMapper(mapper: any): void;
    /**
     * Sanitizes a key to ensure it's a string
     */
    static sanitizeKey(key: any): string;
    /**
     * Checks if an object is empty (null, undefined, or has no properties)
     */
    static isEmpty(obj: any): boolean;
    /**
     * Deep clones a value (for non-secure values only)
     */
    static deepClone<T>(value: T): T;
    /**
     * Checks if a value is a primitive type
     */
    static isPrimitive(value: any): boolean;
    /**
     * Gets the type name of a value
     */
    static getTypeName(value: any): 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.
 ***************************************************************************** */
/**
 * Main export file for SecureObject
 */

/**
 * Factory functions for common use cases
 */
/**
 * Creates a new SecureObject with default settings
 */
declare function createSecureObject<T extends Record<string, any>>(...args: ConstructorParameters<typeof SecureObject<T>>): SecureObject<T>;
/**
 * Creates a read-only SecureObject
 */
declare function createReadOnlySecureObject<T extends Record<string, any>>(data: Partial<T>): SecureObject<T>;
/**
 * Creates a SecureObject with custom sensitive keys
 */
declare function createSecureObjectWithSensitiveKeys<T extends Record<string, any>>(initialData: Partial<T>, sensitiveKeys: string[], options?: {
    readOnly?: boolean;
    encryptionKey?: string;
}): SecureObject<T>;
/**
 * Creates a SecureObject from another SecureObject (deep copy)
 */
declare function cloneSecureObject<T extends Record<string, any>>(source: SecureObject<T>): SecureObject<T>;
/**
 * Version information
 */
declare const SECURE_OBJECT_VERSION = "2.0.0-modular";
/**
 * Module information for debugging
 */
declare const MODULE_INFO: {
    readonly version: "2.0.0-modular";
    readonly architecture: "modular";
    readonly components: readonly ["core/secure-object-core", "encryption/sensitive-keys", "encryption/crypto-handler", "metadata/metadata-manager", "events/event-manager", "serialization/serialization-handler", "utils/id-generator", "utils/validation"];
    readonly features: readonly ["Modular architecture", "Type-safe operations", "Event system", "Metadata tracking", "Encryption support", "Serialization options", "Memory management", "Validation utilities"];
};

/***************************************************************************
 * 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.
 ***************************************************************************** */

/**
 * Main class for the FortifyJS library
 */
declare class FortifyJS {
    /**
     * Generate a secure token with customizable options
     * @param options - Token generation options
     * @returns Secure random token
     */
    static generateSecureToken(options?: SecureTokenOptions): string;
    /**
     * Generate secure PIN
     * @param length - PIN length
     * @param options - Generation options
     * @returns Secure numeric PIN
     */
    static generateSecurePIN(...args: Parameters<(typeof RandomTokens)["generateSecurePIN"]>): string;
    /**
     * Generate recovery codes
     * @param count - Number of codes to generate
     * @param codeLength - Length of each code
     * @param options - Generation options
     * @returns Array of recovery codes
     */
    static generateRecoveryCodes(...args: Parameters<(typeof RandomTokens)["generateRecoveryCodes"]>): string[];
    /**
     * Generate an API key with prefix and timestamp
     * @param options - API key generation options
     * @returns API key
     */
    static generateAPIKey(options?: APIKeyOptions | string): string;
    /**
     * Generate a JWT secret with high entropy
     * @param length - Length of the secret
     * @returns High-entropy JWT secret
     */
    static generateJWTSecret(length?: number, encoding?: EncodingHashType$1): string;
    /**
     * Generate a session token with built-in signature
     * @param options - Session token options
     * @returns Session token
     */
    static generateSessionToken(options?: SessionTokenOptions): string;
    /**
     * Generate a TOTP secret for two-factor authentication
     * @returns Base32 encoded TOTP secret
     */
    static generateTOTPSecret(): string;
    /**
     * Create a secure hash with configurable options
     * @param input - The input to hash
     * @param options - Hashing options
     * @returns The hash in the specified format
     */
    static secureHash(...p: Parameters<typeof Hash.createSecureHash>): string;
    /**
     * Verify that a hash matches the expected input
     * @param input - The input to verify
     * @param hash - The hash to verify against
     * @param options - Hashing options (must match those used to create the hash)
     * @returns True if the hash matches the input
     */
    static verifyHash(...p: Parameters<typeof Hash.verifyHash>): boolean;
    /**
     * Derive a key from a password or other input
     * @param input - The input to derive a key from
     * @param options - Key derivation options
     * @returns The derived key as a hex string
     */
    static deriveKey(input: string | Uint8Array, options?: KeyDerivationOptions): string;
    /**
     * Calculate password strength with detailed analysis
     * @param password - The password to analyze
     * @returns Password strength analysis
     */
    static calculatePasswordStrength(password: string): PasswordStrengthResult;
    /**
     * Run security tests to validate the library's functionality
     * @returns Security test results
     */
    /**
     * Get cryptographic operation statistics
     * @returns Current statistics
     */
    static getStats(): CryptoStats;
    /**
     * Reset statistics
     */
    static resetStats(): void;
    /**
     * Perform a constant-time comparison of two strings or arrays
     * This prevents timing attacks by ensuring the comparison takes the same
     * amount of time regardless of how many characters match
     *
     * @param a - First string or array to compare
     * @param b - Second string or array to compare
     * @returns True if the inputs are equal, false otherwise
     */
    static constantTimeEqual(a: string | Uint8Array, b: string | Uint8Array): boolean;
    /**
     * Derive a key using memory-hard Argon2 algorithm
     * This is more resistant to hardware-based attacks than standard PBKDF2
     *
     * @param password - Password to derive key from
     * @param options - Derivation options
     * @returns Derived key and metadata
     */
    static deriveKeyMemoryHard(password: string | Uint8Array, options?: any): any;
    /**
     * Derive a key using memory-hard Balloon algorithm
     * An alternative memory-hard algorithm with different security properties
     *
     * @param password - Password to derive key from
     * @param options - Derivation options
     * @returns Derived key and metadata
     */
    static deriveKeyBalloon(password: string | Uint8Array, options?: any): any;
    /**
     * Generate a post-quantum secure key pair using Lamport one-time signatures
     * This is resistant to attacks by quantum computers
     *
     * @returns Public and private key pair
     */
    static generateQuantumResistantKeypair(): any;
    /**
     * Sign a message using quantum-resistant Lamport signatures
     *
     * @param message - Message to sign
     * @param privateKey - Private key
     * @returns Signature
     */
    static quantumResistantSign(message: string | Uint8Array, privateKey: string): string;
    /**
     * Verify a quantum-resistant signature
     *
     * @param message - Message that was signed
     * @param signature - Signature to verify
     * @param publicKey - Public key
     * @returns True if the signature is valid
     */
    static quantumResistantVerify(message: string | Uint8Array, signature: string, publicKey: string): boolean;
    /**
     * Create a secure buffer that automatically zeros its contents when destroyed
     *
     * @param size - Size of the buffer in bytes
     * @param fill - Optional value to fill the buffer with
     * @returns Secure buffer
     */
    static createSecureBuffer(size: number, fill?: number): SecureBuffer;
    /**
     * Create a secure string that can be explicitly cleared from memory
     *
     * @param value - Initial string value
     * @returns Secure string
     */
    static createSecureString(value?: string): SecureString;
    /**
     * Create a secure object that can store sensitive data and be explicitly cleared
     *
     * @param initialData - Initial data
     * @returns Secure object
     */
    static createSecureObject<T extends Record<string, any>>(initialData?: T): SecureObject<T>;
    /**
     * Securely wipe a section of memory
     *
     * @param buffer - Buffer to wipe
     * @param start - Start position
     * @param end - End position
     */
    static secureWipe(buffer: Uint8Array, start?: number, end?: number): void;
    /**
     * Get an enhanced entropy source that collects entropy from multiple sources
     *
     * @param poolSize - Size of the entropy pool in bytes
     * @param options - Entropy collection options
     * @returns Entropy pool instance
     */
    static getEnhancedEntropySource(poolSize?: number, options?: any): EntropyPool;
    /**
     * Create a canary token that can detect unauthorized access
     *
     * @param options - Canary options
     * @returns Canary token
     */
    static createCanaryToken(options?: any): string;
    /**
     * Create a canary object that triggers when accessed
     *
     * @param target - Object to wrap with a canary
     * @param options - Canary options
     * @returns Proxy object that triggers the canary when accessed
     */
    static createCanaryObject<T extends object>(target: T, options?: any): T;
    /**
     * Create a canary function that triggers when called
     *
     * @param fn - Function to wrap with a canary
     * @param options - Canary options
     * @returns Function that triggers the canary when called
     */
    static createCanaryFunction<T extends Function>(fn: T, options?: any): T;
    /**
     * Create a cryptographic attestation for data
     *
     * @param data - Data to attest
     * @param options - Attestation options
     * @returns Attestation string
     */
    static createAttestation(data: string | Uint8Array | Record<string, any>, options?: any): string;
    /**
     * Verify a cryptographic attestation
     *
     * @param attestation - Attestation to verify
     * @param options - Verification options
     * @returns Verification result
     */
    static verifyAttestation(attestation: string, options: any): any;
    /**
     * Create an attestation for the library itself
     *
     * @param options - Attestation options
     * @returns Attestation string
     */
    static createLibraryAttestation(options?: any): string;
    /**
     * Verify a library attestation
     *
     * @param attestation - Attestation to verify
     * @param options - Verification options
     * @returns Verification result
     */
    static verifyLibraryAttestation(attestation: string, options: any): any;
    /**
     * Verify the security of the runtime environment
     *
     * @param options - Verification options
     * @returns Verification result
     */
    static verifyRuntimeSecurity(options?: any): any;
    /**
     * Securely serialize data with protection against various attacks
     *
     * @param data - Data to serialize
     * @param options - Serialization options
     * @returns Serialization result
     */
    static secureSerialize<T>(data: T, options?: any): any;
    /**
     * Securely deserialize data
     *
     * @param serialized - Serialized data
     * @param options - Deserialization options
     * @returns Deserialization result
     */
    static secureDeserialize<T>(serialized: any, options?: any): any;
    /**
     * Create a tamper-evident logger
     *
     * @param key - Secret key for hashing
     * @param storageKey - Key for storing logs in localStorage
     * @returns Tamper-evident logger
     */
    static createTamperEvidentLogger(key?: string, storageKey?: string): TamperEvidentLogger;
    /**
     * Get log level enum for tamper-evident logging
     * @returns Log level enum
     */
    static getLogLevel(): typeof LogLevel;
    /**
     * Perform secure modular exponentiation resistant to timing attacks
     *
     * @param base - Base value
     * @param exponent - Exponent value
     * @param modulus - Modulus value
     * @returns (base^exponent) mod modulus
     */
    static secureModPow(base: bigint, exponent: bigint, modulus: bigint): bigint;
    /**
     * Perform a fault-resistant comparison of two buffers
     * This is resistant to fault injection attacks
     *
     * @param a - First buffer to compare
     * @param b - Second buffer to compare
     * @returns True if the buffers are equal
     */
    static faultResistantEqual(a: Uint8Array, b: Uint8Array): boolean;
    /**
     * Generate a Ring-LWE key pair for post-quantum encryption
     *
     * @returns Public and private key pair
     */
    static generateRingLweKeypair(): any;
    /**
     * Encrypt data using Ring-LWE post-quantum encryption
     *
     * @param message - Message to encrypt
     * @param publicKey - Public key
     * @returns Encrypted message
     */
    static ringLweEncrypt(message: string | Uint8Array, publicKey: string): string;
    /**
     * Decrypt data using Ring-LWE post-quantum encryption
     *
     * @param ciphertext - Encrypted message
     * @param privateKey - Private key
     * @returns Decrypted message
     */
    static ringLweDecrypt(ciphertext: string, privateKey: string): Uint8Array;
    /**
     * Trigger a canary token
     *
     * @param token - Canary token to trigger
     * @param triggerContext - Additional context for the trigger
     * @returns True if the canary was triggered
     */
    static triggerCanaryToken(token: string, triggerContext?: any): boolean;
}

/**
 * Key derivation functionality
 */
declare class Keys {
    /**
     * Derive a key from a password or other input
     * @param input - The input to derive a key from
     * @param options - Key derivation options
     * @returns The derived key as a hex string
     */
    static deriveKey(input: string | Uint8Array, options?: KeyDerivationOptions): string;
    /**
     * PBKDF2 key derivation
     * @param password - Password input
     * @param salt - Salt value
     * @param iterations - Number of iterations
     * @param keyLength - Desired key length in bytes
     * @param hashFunction - Hash function to use
     * @returns Derived key
     */
    private static pbkdf2;
    /**
     * PBKDF2 using Node.js crypto
     * @param password - Password input
     * @param salt - Salt value
     * @param iterations - Number of iterations
     * @param keyLength - Desired key length in bytes
     * @param hashFunction - Hash function to use
     * @returns Derived key
     */
    private static nodePbkdf2;
    /**
     * Pure JavaScript implementation of PBKDF2
     * @param password - Password input
     * @param salt - Salt value
     * @param iterations - Number of iterations
     * @param keyLength - Desired key length in bytes
     * @param hashFunction - Hash function to use
     * @returns Derived key
     */
    private static purePbkdf2;
    /**
     * Scrypt key derivation
     * @param password - Password input
     * @param salt - Salt value
     * @param cost - CPU/memory cost parameter
     * @param keyLength - Desired key length in bytes
     * @returns Derived key
     */
    private static scrypt;
    /**
     * Argon2 key derivation
     * @param password - Password input
     * @param salt - Salt value
     * @param iterations - Time cost parameter
     * @param keyLength - Desired key length in bytes
     * @returns Derived key
     */
    private static argon2;
}

/**
 * Validation utilities for security-related inputs
 */
declare class Validators {
    /**
     * Validate a token length
     * @param length - The length to validate
     * @param minLength - Minimum allowed length
     * @param maxLength - Maximum allowed length
     * @throws Error if the length is invalid
     */
    static validateLength(length: number, minLength?: number, maxLength?: number): void;
    /**
     * Validate a hash algorithm
     * @param algorithm - The algorithm to validate
     * @param allowedAlgorithms - List of allowed algorithms
     * @throws Error if the algorithm is invalid
     */
    static validateAlgorithm(algorithm: string, allowedAlgorithms?: string[]): void;
    /**
     * Validate iteration count
     * @param iterations - The iteration count to validate
     * @param minIterations - Minimum allowed iterations
     * @param maxIterations - Maximum allowed iterations
     * @throws Error if the iteration count is invalid
     */
    static validateIterations(iterations: number, minIterations?: number, maxIterations?: number): void;
    /**
     * Validate a salt
     * @param salt - The salt to validate
     * @throws Error if the salt is invalid
     */
    static validateSalt(salt: string | Uint8Array): void;
    /**
     * Validate an output format
     * @param format - The format to validate
     * @param allowedFormats - List of allowed formats
     * @throws Error if the format is invalid
     */
    static validateOutputFormat(format: string, allowedFormats?: string[]): void;
    /**
     * Validate an entropy level
     * @param entropy - The entropy level to validate
     * @param allowedLevels - List of allowed entropy levels
     * @throws Error if the entropy level is invalid
     */
    static validateEntropyLevel(entropy: string, allowedLevels?: string[]): void;
    /**
     * Validate an API key format
     * @param apiKey - The API key to validate
     * @param expectedPrefix - Optional expected prefix
     * @throws Error if the API key format is invalid
     */
    static validateAPIKey(apiKey: string, expectedPrefix?: string): void;
    /**
     * Validate a session token format
     * @param token - The session token to validate
     * @throws Error if the session token format is invalid
     */
    static validateSessionToken(token: string): void;
    /**
     * Validate a password strength
     * @param password - The password to validate
     * @param minLength - Minimum required length
     * @param requireUppercase - Whether uppercase letters are required
     * @param requireLowercase - Whether lowercase letters are required
     * @param requireNumbers - Whether numbers are required
     * @param requireSymbols - Whether symbols are required
     * @throws Error if the password is too weak
     */
    static validatePasswordStrength(password: string, minLength?: number, requireUppercase?: boolean, requireLowercase?: boolean, requireNumbers?: boolean, requireSymbols?: boolean): void;
}

/**
 * 🔐 Password Management Types & Interfaces
 *
 * Type definitions for the modular password management system
 */
/**
 * Password encryption algorithms supported
 */
declare enum PasswordAlgorithm {
    ARGON2ID = "argon2id",// Recommended for new applications
    ARGON2I = "argon2i",// Memory-hard, side-channel resistant
    ARGON2D = "argon2d",// Memory-hard, faster
    SCRYPT = "scrypt",// Alternative memory-hard function
    PBKDF2_SHA512 = "pbkdf2-sha512",// Traditional but secure
    BCRYPT_PLUS = "bcrypt-plus",// Enhanced bcrypt with additional layers
    MILITARY = "military"
}
/**
 * Password security levels
 */
declare enum PasswordSecurityLevel {
    STANDARD = "standard",// Good for most applications
    HIGH = "high",// Enhanced security
    MAXIMUM = "maximum",// Maximum security
    MILITARY = "military",// Military-grade security
    QUANTUM_RESISTANT = "quantum-resistant"
}
/**
 * Password hashing options
 */
interface PasswordHashOptions {
    algorithm?: PasswordAlgorithm;
    securityLevel?: PasswordSecurityLevel;
    iterations?: number;
    memorySize?: number;
    parallelism?: number;
    saltLength?: number;
    pepper?: string;
    encryptionKey?: string;
    quantumResistant?: boolean;
    timingSafe?: boolean;
    secureWipe?: boolean;
}
/**
 * Password verification result
 */
interface PasswordVerificationResult {
    isValid: boolean;
    needsRehash?: boolean;
    securityLevel: PasswordSecurityLevel;
    algorithm: PasswordAlgorithm;
    timeTaken: number;
    recommendations?: string[];
}
/**
 * Password strength analysis result
 */
interface PasswordStrengthAnalysis {
    score: number;
    feedback: string[];
    entropy: number;
    estimatedCrackTime: string;
    vulnerabilities: string[];
    details: {
        length: number;
        hasUppercase: boolean;
        hasLowercase: boolean;
        hasNumbers: boolean;
        hasSymbols: boolean;
        hasRepeated: boolean;
        hasSequential: boolean;
        hasCommonPatterns: boolean;
    };
}
/**
 * Password generation options
 */
interface PasswordGenerationOptions {
    length?: number;
    includeUppercase?: boolean;
    includeLowercase?: boolean;
    includeNumbers?: boolean;
    includeSymbols?: boolean;
    excludeSimilar?: boolean;
    minStrengthScore?: number;
    customCharset?: string;
    excludeChars?: string;
    requireAll?: boolean;
}
/**
 * Password generation result
 */
interface PasswordGenerationResult {
    password: string;
    strength: PasswordStrengthAnalysis;
    metadata: {
        generatedAt: number;
        algorithm: string;
        entropy: number;
    };
}
/**
 * Migration result from other password systems
 */
interface PasswordMigrationResult {
    newHash: string;
    migrated: boolean;
    originalAlgorithm?: string;
    newAlgorithm: PasswordAlgorithm;
    securityImprovement: number;
    recommendations?: string[];
}
/**
 * Password policy configuration
 */
interface PasswordPolicy {
    minLength: number;
    maxLength: number;
    requireUppercase: boolean;
    requireLowercase: boolean;
    requireNumbers: boolean;
    requireSymbols: boolean;
    minStrengthScore: number;
    forbiddenPatterns: RegExp[];
    forbiddenWords: string[];
    maxAge?: number;
    preventReuse?: number;
}
/**
 * Password validation result
 */
interface PasswordValidationResult {
    isValid: boolean;
    violations: string[];
    score: number;
    suggestions: string[];
}
/**
 * Password manager configuration
 */
interface PasswordManagerConfig {
    defaultAlgorithm: PasswordAlgorithm;
    defaultSecurityLevel: PasswordSecurityLevel;
    globalPepper?: string;
    encryptionKey?: string;
    policy?: PasswordPolicy;
    timingSafeVerification: boolean;
    secureMemoryWipe: boolean;
    enableMigration: boolean;
}
/**
 * Password audit result
 */
interface PasswordAuditResult {
    totalPasswords: number;
    weakPasswords: number;
    outdatedHashes: number;
    needsRehash: number;
    securityScore: number;
    recommendations: string[];
    details: {
        algorithmDistribution: Record<PasswordAlgorithm, number>;
        securityLevelDistribution: Record<PasswordSecurityLevel, number>;
        averageStrength: number;
        oldestHash: number;
    };
}

/**
 * @author Supper Coder
 *  PasswordManager
 *
 * Main class for secure password management with modular architecture
 */
declare class PasswordManager {
    private static instance;
    private config;
    private algorithms;
    private security;
    private migration;
    private generator;
    private utils;
    private constructor();
    /**
     * Get singleton instance
     */
    static getInstance(config?: Partial<PasswordManagerConfig>): PasswordManager;
    /**
     * Create a new instance (for multiple configurations)
     */
    static create(config?: Partial<PasswordManagerConfig>): PasswordManager;
    /**
     * Hash a password with advanced security
     */
    hash(password: string, options?: PasswordHashOptions): Promise<string>;
    /**
     * Verify a password against a hash
     */
    verify(password: string, hash: string): Promise<PasswordVerificationResult>;
    /**
     * Generate a secure password
     */
    generatePassword(options?: any): PasswordGenerationResult;
    /**
     * Analyze password strength
     */
    analyzeStrength(password: string): PasswordStrengthAnalysis;
    /**
     * Migrate from bcrypt or other systems
     */
    migrate(password: string, oldHash: string, options?: any): Promise<PasswordMigrationResult>;
    /**
     * Validate password against policy
     */
    validatePolicy(password: string): PasswordValidationResult;
    /**
     * Rehash password with updated security
     */
    rehash(password: string, oldHash: string, newOptions?: PasswordHashOptions): Promise<{
        newHash: string;
        upgraded: boolean;
    }>;
    /**
     * Audit password security
     */
    auditSecurity(hashes: string[]): Promise<PasswordAuditResult>;
    /**
     * Configure global settings
     */
    configure(config: Partial<PasswordManagerConfig>): void;
    /**
     * Get current configuration
     */
    getConfig(): PasswordManagerConfig;
    private mergeOptions;
    private applyPepper;
    private createMetadata;
    private shouldRehash;
    private generateRecommendations;
    private constantTimeDelay;
}

/***************************************************************************
 * 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.
 ***************************************************************************** */
/**
 * Type definitions for SecureArray modular architecture
 */

/**
 * Types that can be stored securely in arrays
 */
type SecureArrayValue = string | number | boolean | Uint8Array | SecureString | SecureObject<any> | null | undefined | object;
/**
 * Serialization options for SecureArray
 */
interface SecureArraySerializationOptions {
    includeMetadata?: boolean;
    encryptSensitive?: boolean;
    format?: "json" | "binary" | "compact" | "base64";
    preserveOrder?: boolean;
    compression?: boolean;
    includeChecksum?: boolean;
}
/**
 * Metadata for tracking secure array elements
 */
interface ElementMetadata {
    type: string;
    isSecure: boolean;
    created: Date;
    lastAccessed: Date;
    accessCount: number;
    index: number;
}
/**
 * Event types for SecureArray
 */
type SecureArrayEvent = "created" | "push" | "pop" | "shift" | "unshift" | "splice" | "sort" | "reverse" | "get" | "set" | "clear" | "destroy" | "filtered" | "mapped" | "reduced" | "gc" | "encrypt_all" | "slice" | "snapshot_created" | "snapshot_restored" | "freeze" | "unfreeze" | "readonly" | "writable" | "destroyed" | "compact" | "unique" | "shuffle";
/**
 * Event listener callback for SecureArray
 */
type SecureArrayEventListener = (event: SecureArrayEvent, index?: number, value?: any, metadata?: any) => void | Promise<void>;
/**
 * Configuration options for SecureArray
 */
interface SecureArrayOptions {
    readOnly?: boolean;
    autoDestroy?: boolean;
    encryptionKey?: string;
    maxMemory?: number;
    gcThreshold?: number;
    enableMemoryTracking?: boolean;
    autoCleanup?: boolean;
    maxLength?: number;
    maxSize?: number;
    enableIndexValidation?: boolean;
    enableTypeValidation?: boolean;
}
/**
 * Statistics for SecureArray performance monitoring
 */
interface SecureArrayStats {
    length: number;
    secureElements: number;
    totalAccesses: number;
    memoryUsage: number;
    lastModified: number;
    version: number;
    createdAt: number;
    isReadOnly: boolean;
    isFrozen: boolean;
    typeDistribution: Record<string, number>;
    secureElementCount: number;
    estimatedMemoryUsage: number;
    snapshotCount: number;
    encryptionEnabled: boolean;
}
/**
 * Helper type for creating flexible SecureArray instances
 */
type FlexibleSecureArray<T = SecureArrayValue> = T[] & {
    [key: string]: any;
};
/**
 * Predicate function type for filtering and searching
 */
type PredicateFn<T extends SecureArrayValue> = (value: T, index: number, array: SecureArray<T>) => boolean;
/**
 * Comparator function type for sorting
 */
type ComparatorFn<T extends SecureArrayValue> = (a: T, b: T) => number;
/**
 * Mapper function type for transformations
 */
type MapperFn<T extends SecureArrayValue, U> = (value: T, index: number, array: SecureArray<T>) => U;
/**
 * Reducer function type for aggregations
 */
type ReducerFn<T extends SecureArrayValue, U> = (accumulator: U, currentValue: T, currentIndex: number, array: SecureArray<T>) => U;

/***************************************************************************
 * FortifyJS - Enhanced Secure Array Core Implementation
 *
 *  security features and array methods
 *
 * @author Nehonix & Community
 *
 * @license MIT
 ***************************************************************************** */

/**
 * A secure array that can store sensitive data with enhanced security features
 * T represents the type of elements stored in the array
 */
declare class SecureArray<T extends SecureArrayValue = SecureArrayValue> implements Iterable<T> {
    private elements;
    private secureBuffers;
    private metadataManager;
    private eventManager;
    private cryptoHandler;
    private serializationHandler;
    private _isDestroyed;
    private _isReadOnly;
    private _isFrozen;
    private readonly _id;
    private _version;
    private _lastModified;
    private _createdAt;
    private _memoryTracking;
    private secureBufferPool?;
    private _maxSize?;
    private options;
    private snapshots;
    /**
     * Creates a new secure array
     */
    constructor(initialData?: T[], options?: SecureArrayOptions);
    /**
     * Initialize secure buffer pool for efficient memory reuse
     */
    private initializeSecureBufferPool;
    /**
     * Handle memory pressure by cleaning up unused resources
     */
    private handleMemoryPressure;
    /**
     * Secure wipe of buffer contents
     */
    private secureWipe;
    /**
     * Ensures the array is not destroyed
     */
    private ensureNotDestroyed;
    /**
     * Ensures the array is not read-only
     */
    private ensureNotReadOnly;
    /**
     * Ensures the array is not frozen
     */
    private ensureNotFrozen;
    /**
     * Check if adding elements would exceed max size
     */
    private checkSizeLimit;
    /**
     * Updates the last modified timestamp and version
     */
    private updateLastModified;
    /**
     * Validates an index
     */
    private validateIndex;
    /**
     * Validates a value
     */
    private validateValue;
    /**
     * Gets the length of the array
     */
    get length(): number;
    /**
     * Gets the unique identifier of this array
     */
    get id(): string;
    /**
     * Gets the version number (increments on each mutation)
     */
    get version(): number;
    /**
     * Gets when the array was last modified
     */
    get lastModified(): number;
    /**
     * Gets when the array was created
     */
    get createdAt(): number;
    /**
     * Check if the array is empty
     */
    get isEmpty(): boolean;
    /**
     * Check if the array is read-only
     */
    get isReadOnly(): boolean;
    /**
     * Check if the array is frozen
     */
    get isFrozen(): boolean;
    /**
     * Check if the array is destroyed
     */
    get isDestroyed(): boolean;
    /**
     * Gets an element at the specified index with automatic decryption
     */
    get(index: number): T | undefined;
    /**
     * Gets element at index with bounds checking
     */
    at(index: number): T | undefined;
    /**
     * Sets an element at the specified index
     */
    set(index: number, value: T): this;
    /**
     * Cleans up resources associated with an index
     */
    private cleanupIndex;
    /**
     * Adds an element to the end of the array
     */
    push(value: T): number;
    /**
     * Removes and returns the last element
     */
    pop(): T | undefined;
    /**
     * Removes and returns the first element
     */
    shift(): T | undefined;
    /**
     * Adds elements to the beginning of the array
     */
    unshift(...values: T[]): number;
    /**
     * Adds multiple elements to the array
     */
    pushAll(values: T[]): number;
    /**
     * Removes elements from array and optionally inserts new elements
     */
    splice(start: number, deleteCount?: number, ...items: T[]): SecureArray<T>;
    /**
     * Returns a shallow copy of a portion of the array
     */
    slice(start?: number, end?: number): SecureArray<T>;
    /**
     * Concatenates arrays and returns a new SecureArray
     */
    concat(...arrays: (T[] | SecureArray<T>)[]): SecureArray<T>;
    /**
     * Joins all elements into a string
     */
    join(separator?: string): string;
    /**
     * Reverses the array in place
     */
    reverse(): this;
    /**
     * Sorts the array in place
     */
    sort(compareFn?: ComparatorFn<T>): this;
    /**
     * Calls a function for each element
     */
    forEach(callback: (value: T, index: number, array: SecureArray<T>) => void, thisArg?: any): void;
    /**
     * Creates a new array with results of calling a function for every element
     */
    map<U extends SecureArrayValue>(callback: MapperFn<T, U>, thisArg?: any): SecureArray<U>;
    /**
     * Creates a new array with elements that pass a test
     */
    filter(predicate: PredicateFn<T>, thisArg?: any): SecureArray<T>;
    /**
     * Reduces the array to a single value
     */
    reduce<U>(callback: ReducerFn<T, U>, initialValue?: U): U;
    /**
     * Tests whether at least one element passes the test
     */
    some(predicate: PredicateFn<T>, thisArg?: any): boolean;
    /**
     * Tests whether all elements pass the test
     */
    every(predicate: PredicateFn<T>, thisArg?: any): boolean;
    /**
     * Finds the first element that satisfies the predicate
     */
    find(predicate: PredicateFn<T>, thisArg?: any): T | undefined;
    /**
     * Finds the index of the first element that satisfies the predicate
     */
    findIndex(predicate: PredicateFn<T>, thisArg?: any): number;
    /**
     * Finds the last element that satisfies the predicate
     */
    findLast(predicate: PredicateFn<T>, thisArg?: any): T | undefined;
    /**
     * Finds the index of the last element that satisfies the predicate
     */
    findLastIndex(predicate: PredicateFn<T>, thisArg?: any): number;
    /**
     * Returns the first index of an element
     */
    indexOf(searchElement: T, fromIndex?: number): number;
    /**
     * Returns the last index of an element
     */
    lastIndexOf(searchElement: T, fromIndex?: number): number;
    /**
     * Checks if an element exists in the array
     */
    includes(searchElement: T, fromIndex?: number): boolean;
    /**
     * Creates a snapshot of the current array state
     */
    createSnapshot(name?: string): string;
    /**
     * Restores the array from a snapshot
     */
    restoreFromSnapshot(snapshotId: string): boolean;
    /**
     * Lists available snapshots
     */
    listSnapshots(): Array<{
        id: string;
        timestamp: number;
    }>;
    /**
     * Deletes a snapshot
     */
    deleteSnapshot(snapshotId: string): boolean;
    /**
     * Clears all elements from the array
     */
    clear(): this;
    /**
     * Freezes the array to prevent modifications
     */
    freeze(): this;
    /**
     * Unfreezes the array to allow modifications
     */
    unfreeze(): this;
    /**
     * Makes the array read-only
     */
    makeReadOnly(): this;
    /**
     * Removes read-only restriction
     */
    makeWritable(): this;
    /**
     * Securely wipes all data and destroys the array
     */
    destroy(): void;
    /**
     * Gets comprehensive statistics about the array
     */
    getStats(): SecureArrayStats;
    /**
     * Validates the integrity of the array
     */
    validateIntegrity(): {
        isValid: boolean;
        errors: string[];
    };
    /**
     * Compacts the array by removing undefined/null elements
     */
    compact(): this;
    /**
     * Removes duplicate elements
     */
    unique(): this;
    /**
     * Groups elements by a key function
     */
    groupBy<K extends string | number>(keyFn: (value: T, index: number) => K): Map<K, SecureArray<T>>;
    /**
     * Returns the minimum value
     */
    min(compareFn?: ComparatorFn<T>): T | undefined;
    /**
     * Returns the maximum value
     */
    max(compareFn?: ComparatorFn<T>): T | undefined;
    /**
     * Shuffles the array in place using Fisher-Yates algorithm
     */
    shuffle(): this;
    /**
     * Returns a random sample of elements
     */
    sample(count?: number): SecureArray<T>;
    /**
     * Returns an iterator for the array
     */
    [Symbol.iterator](): Iterator<T>;
    /**
     * Returns an iterator for array entries [index, value]
     */
    entries(): Iterator<[number, T]>;
    /**
     * Returns an iterator for array indices
     */
    keys(): Iterator<number>;
    /**
     * Returns an iterator for array values
     */
    values(): Iterator<T>;
    /**
     * Adds an event listener
     */
    on(event: SecureArrayEvent, listener: SecureArrayEventListener): this;
    /**
     * Removes an event listener
     */
    off(event: SecureArrayEvent, listener: SecureArrayEventListener): this;
    /**
     * Adds a one-time event listener
     */
    once(event: SecureArrayEvent, listener: SecureArrayEventListener): this;
    /**
     * Serializes the SecureArray to a secure format
     */
    serialize(options?: SecureArraySerializationOptions): string;
    /**
     * Exports the SecureArray data in various formats
     */
    exportData(format?: "json" | "csv" | "xml" | "yaml"): string;
    /**
     * Converts to a regular JavaScript array (loses security features)
     */
    toArray(): T[];
    /**
     * Creates a SecureArray from a regular array
     */
    static from<T extends SecureArrayValue>(arrayLike: ArrayLike<T> | Iterable<T>, options?: SecureArrayOptions): SecureArray<T>;
    /**
     * Creates a SecureArray with specified length and fill value
     */
    static of<T extends SecureArrayValue>(...elements: T[]): SecureArray<T>;
    /**
     * Gets encryption status from the crypto handler
     */
    getEncryptionStatus(): {
        isInitialized: boolean;
        hasEncryptionKey: boolean;
        algorithm: string;
    };
    /**
     * Sets an encryption key for the array
     */
    setEncryptionKey(key: string): void;
    /**
     * Gets the raw encrypted data without decryption (for verification)
     */
    getRawEncryptedData(): any[];
    /**
     * Gets a specific element's raw encrypted form (for verification)
     */
    getRawEncryptedElement(index: number): any;
    /**
     * Encrypts all elements in the array using AES-256-CTR-HMAC encryption
     * with proper memory management and atomic operations
     */
    encryptAll(): this;
}

/***************************************************************************
 * FortifyJS - Secure Array Main Export
 *
 * This file contains the main exports for the SecureArray module
 *
 * @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.
 ***************************************************************************** */
/**
 * Main export file for SecureArray
 */

type WidenLiterals<T> = T extends string ? string : T extends number ? number : T extends boolean ? boolean : T;
/**
 * Creates a SecureArray with initial data
 */
declare function createSecureArray<T extends SecureArrayValue = SecureArrayValue>(initialData?: WidenLiterals<T>[], options?: SecureArrayOptions): SecureArray<WidenLiterals<T>>;

/**
 * Side-Channel Attack Protection Module
 *
 * This module provides protection against various side-channel attacks:
 * - Timing attacks: Ensures operations take constant time regardless of input
 * - Cache attacks: Implements cache-resistant operations
 * - Power analysis: Reduces power analysis vectors through balanced operations
 * - Fault injection: Detects and mitigates fault injection attempts
 */
/**
 * Performs a constant-time comparison of two strings or arrays
 * Prevents timing attacks by ensuring the comparison takes the same amount of time
 * regardless of how many characters match
 *
 * @param a - First string or array to compare
 * @param b - Second string or array to compare
 * @returns True if the inputs are equal, false otherwise
 */
declare function constantTimeEqual(a: string | Uint8Array, b: string | Uint8Array): boolean;
/**
 * Performs a masked memory access to prevent cache-timing attacks
 * This technique helps mitigate cache-based side-channel attacks by
 * accessing all elements of an array regardless of which one is needed
 *
 * @param array - Array to access
 * @param index - Index to retrieve
 * @returns The value at the specified index
 */
declare function maskedAccess<T>(array: T[], index: number): T;
/**
 * Implements a secure modular exponentiation algorithm resistant to timing attacks
 * Used for cryptographic operations like RSA and Diffie-Hellman
 *
 * @param base - Base value
 * @param exponent - Exponent value
 * @param modulus - Modulus value
 * @returns (base^exponent) mod modulus
 */
declare function secureModPow(base: bigint, exponent: bigint, modulus: bigint): bigint;
/**
 * Implements a secure memory comparison that's resistant to fault injection attacks
 * This performs multiple comparisons and verifies the results match to detect glitches
 *
 * @param a - First buffer to compare
 * @param b - Second buffer to compare
 * @returns True if the buffers are equal, false otherwise
 */
declare function faultResistantEqual(a: Uint8Array, b: Uint8Array): boolean;
/**
 * Creates a secure random delay to mitigate timing attacks
 * This adds unpredictable timing variations to make it harder
 * to extract information through precise timing measurements
 *
 * @param minMs - Minimum delay in milliseconds
 * @param maxMs - Maximum delay in milliseconds
 * @returns Promise that resolves after the random delay
 */
declare function randomDelay(minMs?: number, maxMs?: number): Promise<void>;
/**
 * Applies cache-hardening to a function to protect against cache-timing attacks
 * This technique ensures the function accesses the same memory regions
 * regardless of input, making cache-timing attacks more difficult
 *
 * @param fn - Function to protect
 * @returns Cache-hardened version of the function
 */
declare function cacheHarden<T extends (...args: any[]) => any>(fn: T): T;

/**
 * Options for memory-hard key derivation
 */
interface MemoryHardOptions {
    /**
     * Memory cost parameter (higher = more memory usage)
     * @default 16384 (16 MB)
     */
    memoryCost?: number;
    /**
     * Time cost parameter (higher = more iterations)
     * @default 4
     */
    timeCost?: number;
    /**
     * Parallelism parameter (higher = more threads if available)
     * @default 1
     */
    parallelism?: number;
    /**
     * Output key length in bytes
     * @default 32
     */
    keyLength?: number;
    /**
     * Salt for the derivation
     * If not provided, a random salt will be generated
     */
    salt?: Uint8Array;
    /**
     * Salt length in bytes (if generating a new salt)
     * @default 16
     */
    saltLength?: number;
}
/**
 * Result of memory-hard key derivation
 */
interface MemoryHardResult {
    /**
     * Derived key as a hex string
     */
    derivedKey: string;
    /**
     * Salt used for the derivation (hex encoded)
     */
    salt: string;
    /**
     * Parameters used for the derivation
     */
    params: {
        memoryCost: number;
        timeCost: number;
        parallelism: number;
        keyLength: number;
    };
    /**
     * Performance metrics
     */
    metrics: {
        /**
         * Time taken in milliseconds
         */
        timeTakenMs: number;
        /**
         * Estimated memory used in bytes
         */
        memoryUsedBytes: number;
    };
}
/**
 * Implements the Argon2 memory-hard key derivation function using the argon2 library
 *
 * Argon2 is designed to be resistant to GPU, ASIC, and FPGA attacks by
 * requiring large amounts of memory to compute.
 *
 * This implementation uses the official argon2 library for Node.js.
 *
 * @param password - Password to derive key from
 * @param options - Derivation options
 * @returns Derived key and metadata
 */
declare function argon2Derive(password: string | Uint8Array, options?: MemoryHardOptions): Promise<MemoryHardResult>;
/**
 * Implements a real version of the Balloon memory-hard hashing algorithm
 *
 * Balloon is designed to be a simple memory-hard algorithm with provable
 * memory-hardness properties. This implementation follows the paper:
 * "Balloon: A Forward-Secure Password-Hashing Algorithm with Memory-Hard Functions"
 * by Dan Boneh, Henry Corrigan-Gibbs, and Stuart Schechter.
 *
 * @param password - Password to derive key from
 * @param options - Derivation options
 * @returns Derived key and metadata
 */
declare function balloonDerive(password: string | Uint8Array, options?: MemoryHardOptions): MemoryHardResult;

/**
 * Post-Quantum Cryptography Module
 *
 * This module provides cryptographic primitives that are believed to be
 * resistant to attacks by quantum computers. It implements versions
 * of lattice-based, hash-based, and code-based cryptography.
 *
 * Where possible, it uses standardized libraries for  implementations.
 * Fallback simplified implementations are provided for educational purposes and
 * environments where the libraries are not available.
 */
/**
 * Options for hash-based signatures
 */
interface HashBasedSignatureOptions {
    /**
     * Number of hash chains to use (higher = more secure but larger signatures)
     * @default 256
     */
    chainCount?: number;
    /**
     * Depth of each hash chain (higher = more secure but slower)
     * @default 16
     */
    chainDepth?: number;
}
/**
 * Result of key generation
 */
interface KeyPair {
    /**
     * Public key (hex encoded)
     */
    publicKey: string;
    /**
     * Private key (hex encoded)
     */
    privateKey: string;
}
/**
 * Parameters for post-quantum algorithms
 */
interface PostQuantumParams {
    /**
     * Security level (1, 3, or 5)
     * Higher levels provide more security but are slower and use more memory
     * @default 3
     */
    securityLevel?: number;
    /**
     * Additional algorithm-specific parameters
     */
    [key: string]: any;
}
/**
 * Post-quantum key pair with algorithm information
 */
interface PostQuantumKeyPair extends KeyPair {
    /**
     * Algorithm identifier
     */
    algorithm: string;
    /**
     * Algorithm parameters
     */
    params: Record<string, any>;
}
/**
 * Result of key encapsulation
 */
interface PostQuantumEncapsulation {
    /**
     * Ciphertext (hex encoded)
     */
    ciphertext: string;
    /**
     * Shared secret (hex encoded)
     */
    sharedSecret: string;
    /**
     * Algorithm identifier
     */
    algorithm: string;
    /**
     * Algorithm parameters
     */
    params: Record<string, any>;
}
/**
 * Result of key decapsulation
 */
interface PostQuantumDecapsulation {
    /**
     * Shared secret (hex encoded)
     */
    sharedSecret: string;
    /**
     * Algorithm identifier
     */
    algorithm: string;
    /**
     * Algorithm parameters
     */
    params: Record<string, any>;
}
/**
 * Implements a simplified Lamport one-time signature scheme
 * This is a hash-based signature scheme resistant to quantum attacks
 *
 * @param message - Message to sign
 * @param privateKey - Private key (hex encoded)
 * @returns Signature (hex encoded)
 */
declare function lamportSign(message: string | Uint8Array, privateKey: string): string;
/**
 * Verifies a Lamport signature
 *
 * @param message - Message that was signed
 * @param signature - Signature to verify (hex encoded)
 * @param publicKey - Public key (hex encoded)
 * @returns True if the signature is valid, false otherwise
 */
declare function lamportVerify(message: string | Uint8Array, signature: string, publicKey: string): boolean;
/**
 * Generates a Lamport key pair
 *
 * @returns Public and private key pair (hex encoded)
 */
declare function lamportGenerateKeypair(): KeyPair;
/**
 * Implements a simplified Ring-LWE encryption scheme
 * This is a lattice-based encryption scheme resistant to quantum attacks
 *
 * Note: This is a very simplified version for educational purposes
 *
 * @param message - Message to encrypt (must be 32 bytes or less)
 * @param publicKey - Public key (hex encoded)
 * @returns Encrypted message (hex encoded)
 */
declare function ringLweEncrypt(message: string | Uint8Array, publicKey: string): string;
/**
 * Decrypts a message encrypted with Ring-LWE
 *
 * @param ciphertext - Encrypted message (hex encoded)
 * @param privateKey - Private key (hex encoded)
 * @returns Decrypted message
 */
declare function ringLweDecrypt(ciphertext: string, privateKey: string): Uint8Array;
/**
 * Generates a Ring-LWE key pair
 *
 * @returns Public and private key pair (hex encoded)
 */
declare function ringLweGenerateKeypair(): KeyPair;
/**
 * Implements the Kyber key encapsulation mechanism (KEM)
 *
 * Kyber is a lattice-based key encapsulation mechanism that is believed to be
 * secure against quantum computer attacks.
 *
 * This implementation uses the crystals-kyber library, which provides a
 *  implementation of the Kyber algorithm.
 *
 * @param params - Parameters for the key generation
 * @returns Key pair with public and private keys
 */
declare function generateKyberKeyPair(params?: PostQuantumParams): PostQuantumKeyPair;
/**
 * Encapsulates a shared secret using a Kyber public key
 *
 * @param publicKey - Recipient's public key (hex encoded)
 * @param params - Optional parameters
 * @returns Encapsulated shared secret and ciphertext
 */
declare function kyberEncapsulate(publicKey: string, params?: PostQuantumParams): PostQuantumEncapsulation;
/**
 * Decapsulates a shared secret using a Kyber private key and ciphertext
 *
 * @param privateKey - Recipient's private key (hex encoded)
 * @param ciphertext - Ciphertext from encapsulation (hex encoded)
 * @param params - Optional parameters
 * @returns Decapsulated shared secret
 */
declare function kyberDecapsulate(privateKey: string, ciphertext: string, params?: PostQuantumParams): PostQuantumDecapsulation;

/**
 * Canary Tokens Module
 *
 * This module provides functionality for creating and managing canary tokens,
 * which are special tokens that can detect unauthorized access or data breaches.
 *
 * Canary tokens can be embedded in sensitive data or systems, and when accessed,
 * they trigger alerts or other actions to notify of potential security breaches.
 */
/**
 * Canary token options
 */
interface CanaryOptions {
    /**
     * Callback function to execute when the canary is triggered
     */
    callback?: (context: any) => void;
    /**
     * URL to notify when the canary is triggered
     */
    notifyUrl?: string;
    /**
     * Context information to include with the canary
     */
    context?: any;
    /**
     * Secret key for the canary
     * If not provided, a random key will be generated
     */
    key?: string;
    /**
     * Expiration time in milliseconds
     * If not provided, the canary will not expire
     */
    expiresIn?: number;
}
/**
 * Creates a canary token
 *
 * @param options - Canary options
 * @returns Canary token
 */
declare function createCanary(options?: CanaryOptions): string;
/**
 * Triggers a canary token
 *
 * @param token - Canary token to trigger
 * @param context - Additional context for the trigger
 * @returns True if the canary was triggered successfully
 */
declare function triggerCanary(token: string, context?: any): boolean;
/**
 * Creates a canary object that triggers when accessed
 *
 * @param target - Object to wrap with a canary
 * @param options - Canary options
 * @returns Proxy object that triggers the canary when accessed
 */
declare function createCanaryObject<T extends object>(target: T, options?: CanaryOptions): T;
/**
 * Creates a canary function that triggers when called
 *
 * @param fn - Function to wrap with a canary
 * @param options - Canary options
 * @returns Function that triggers the canary when called
 */
declare function createCanaryFunction<T extends Function>(fn: T, options?: CanaryOptions): T;

/**
 * Attestation options
 */
interface AttestationOptions {
    /**
     * Key to use for signing
     * If not provided, a random key will be generated
     */
    key?: string;
    /**
     * Expiration time in milliseconds
     * If not provided, the attestation will not expire
     */
    expiresIn?: number;
    /**
     * Additional claims to include in the attestation
     */
    claims?: Record<string, any>;
    /**
     * Whether to include environment information
     * @default true
     */
    includeEnvironment?: boolean;
}
/**
 * Attestation verification options
 */
interface VerificationOptions {
    /**
     * Key to use for verification
     */
    key: string;
    /**
     * Whether to verify the expiration
     * @default true
     */
    verifyExpiration?: boolean;
    /**
     * Whether to verify the environment
     * @default false
     */
    verifyEnvironment?: boolean;
    /**
     * Required claims that must be present and match
     */
    requiredClaims?: Record<string, any>;
}
/**
 * Attestation result
 */
interface AttestationResult {
    /**
     * Whether the attestation is valid
     */
    valid: boolean;
    /**
     * Reason for invalidity, if any
     */
    reason?: string;
    /**
     * Claims from the attestation
     */
    claims?: Record<string, any>;
    /**
     * Environment information from the attestation
     */
    environment?: Record<string, any>;
    /**
     * Expiration time of the attestation
     */
    expiresAt?: number;
}
/**
 * Generates a key pair for attestation using asymmetric cryptography
 *
 * @returns Object containing public and private keys
 */
declare function generateAttestationKey(): {
    publicKey: string;
    privateKey: string;
};
/**
 * Creates an attestation for the given data
 *
 * @param data - Data to attest
 * @param options - Attestation options
 * @returns Attestation string
 */
declare function createAttestation(data: string | Uint8Array | Record<string, any>, options?: AttestationOptions): string;
/**
 * Verifies an attestation
 *
 * @param attestation - Attestation to verify
 * @param options - Verification options
 * @returns Verification result
 */
declare function verifyAttestation(attestation: string, options: VerificationOptions): AttestationResult;
/**
 * Creates an attestation for the library itself
 * This can be used to verify the integrity of the library
 *
 * @param options - Attestation options
 * @returns Attestation string
 */
declare function createLibraryAttestation(options?: AttestationOptions): string;
/**
 * Verifies a library attestation
 *
 * @param attestation - Attestation to verify
 * @param options - Verification options
 * @returns Verification result
 */
declare function verifyLibraryAttestation(attestation: string, options: VerificationOptions): AttestationResult;

/**
 * Runtime Security Verification Module
 *
 * This module provides functionality for verifying the security of the runtime
 * environment and detecting potential security issues or tampering attempts.
 *
 * It can detect debuggers, browser extensions that might intercept crypto operations,
 * compromised JavaScript environments, and other security threats.
 */
/**
 * Security verification result
 */
interface SecurityVerificationResult {
    /**
     * Whether the environment is secure
     */
    secure: boolean;
    /**
     * List of detected issues
     */
    issues: SecurityIssue[];
    /**
     * Overall security score (0-100)
     */
    score: number;
    /**
     * Detailed results for each check
     */
    checks: SecurityCheck[];
}
/**
 * Security issue
 */
interface SecurityIssue {
    /**
     * Issue type
     */
    type: SecurityIssueType;
    /**
     * Issue description
     */
    description: string;
    /**
     * Issue severity (0-100)
     */
    severity: number;
    /**
     * Potential mitigations
     */
    mitigations?: string[];
}
/**
 * Security issue type
 */
declare enum SecurityIssueType {
    DEBUGGER = "debugger",
    EXTENSION_INTERFERENCE = "extension_interference",
    COMPROMISED_ENVIRONMENT = "compromised_environment",
    WEAK_RANDOM = "weak_random",
    PROTOTYPE_POLLUTION = "prototype_pollution",
    FUNCTION_HIJACKING = "function_hijacking",
    INSECURE_CONTEXT = "insecure_context",
    BROWSER_EXTENSION = "browser_extension",
    IFRAME_EMBEDDING = "iframe_embedding",
    DEVTOOLS_OPEN = "devtools_open"
}
/**
 * Security check
 */
interface SecurityCheck {
    /**
     * Check name
     */
    name: string;
    /**
     * Check description
     */
    description: string;
    /**
     * Whether the check passed
     */
    passed: boolean;
    /**
     * Check result details
     */
    details?: any;
}
/**
 * Security verification options
 */
interface SecurityVerificationOptions {
    /**
     * Whether to check for debuggers
     * @default true
     */
    checkDebugger?: boolean;
    /**
     * Whether to check for extension interference
     * @default true
     */
    checkExtensions?: boolean;
    /**
     * Whether to check for compromised environment
     * @default true
     */
    checkEnvironment?: boolean;
    /**
     * Whether to check for weak random number generation
     * @default true
     */
    checkRandom?: boolean;
    /**
     * Whether to check for prototype pollution
     * @default true
     */
    checkPrototypePollution?: boolean;
    /**
     * Whether to check for function hijacking
     * @default true
     */
    checkFunctionHijacking?: boolean;
    /**
     * Whether to check for secure context
     * @default true
     */
    checkSecureContext?: boolean;
    /**
     * Whether to check for iframe embedding
     * @default true
     */
    checkIframeEmbedding?: boolean;
    /**
     * Whether to check for open DevTools
     * @default true
     */
    checkDevTools?: boolean;
    /**
     * Custom checks to run
     */
    customChecks?: Array<() => SecurityCheck>;
}
/**
 * Verifies the security of the runtime environment
 *
 * @param options - Verification options
 * @returns Verification result
 */
declare function verifyRuntimeSecurity(options?: SecurityVerificationOptions): SecurityVerificationResult;

/**
 * Secure Serialization Module
 *
 * This module provides secure methods for serializing and deserializing data,
 * protecting against prototype pollution, object injection, and other
 * serialization-related vulnerabilities.
 */
/**
 * Serialization options
 */
interface SerializationOptions {
    /**
     * Whether to sign the serialized data
     * @default true
     */
    sign?: boolean;
    /**
     * Secret key for signing
     * If not provided, a random key will be generated
     */
    signKey?: string;
    /**
     * Whether to encrypt the serialized data
     * @default false
     */
    encrypt?: boolean;
    /**
     * Encryption key
     * Required if encrypt is true
     */
    encryptKey?: string;
    /**
     * Whether to include a timestamp
     * @default true
     */
    includeTimestamp?: boolean;
    /**
     * Whether to include a nonce
     * @default true
     */
    includeNonce?: boolean;
    /**
     * Whether to validate object types during deserialization
     * @default true
     */
    validateTypes?: boolean;
    /**
     * Allowed classes for deserialization
     * If provided, only these classes will be instantiated during deserialization
     */
    allowedClasses?: string[];
}
/**
 * Deserialization options
 */
interface DeserializationOptions {
    /**
     * Whether to verify the signature
     * @default true
     */
    verifySignature?: boolean;
    /**
     * Secret key for signature verification
     * Required if verifySignature is true
     */
    signKey?: string;
    /**
     * Whether to decrypt the data
     * @default false
     */
    decrypt?: boolean;
    /**
     * Decryption key
     * Required if decrypt is true
     */
    decryptKey?: string;
    /**
     * Whether to validate the timestamp
     * @default true
     */
    validateTimestamp?: boolean;
    /**
     * Maximum age of the data in milliseconds
     * @default 3600000 (1 hour)
     */
    maxAge?: number;
    /**
     * Whether to validate object types during deserialization
     * @default true
     */
    validateTypes?: boolean;
    /**
     * Allowed classes for deserialization
     * If provided, only these classes will be instantiated during deserialization
     */
    allowedClasses?: string[];
}
/**
 * Serialization result
 */
interface SerializationResult {
    /**
     * Serialized data
     */
    data: string;
    /**
     * Signature of the data
     */
    signature?: string;
    /**
     * Timestamp when the data was serialized
     */
    timestamp?: number;
    /**
     * Nonce used for encryption
     */
    nonce?: string;
}
/**
 * Deserialization result
 */
interface DeserializationResult<T> {
    /**
     * Deserialized data
     */
    data: T;
    /**
     * Whether the signature is valid
     */
    validSignature?: boolean;
    /**
     * Whether the timestamp is valid
     */
    validTimestamp?: boolean;
    /**
     * Timestamp when the data was serialized
     */
    timestamp?: number;
    /**
     * Age of the data in milliseconds
     */
    age?: number;
}
/**
 * Securely serializes data
 *
 * @param data - Data to serialize
 * @param options - Serialization options
 * @returns Serialization result
 */
declare function secureSerialize<T>(data: T, options?: SerializationOptions): SerializationResult;
/**
 * Securely deserializes data
 *
 * @param serialized - Serialized data
 * @param options - Deserialization options
 * @returns Deserialization result
 */
declare function secureDeserialize<T>(serialized: SerializationResult, options?: DeserializationOptions): DeserializationResult<T>;

/**
 * FortifyJS - Fortified Function Types
 * Type definitions for the fortified function system
 */

interface FortifiedFunctionOptions {
    ultraFast?: boolean | "minimal" | "standard" | "maximum" | undefined;
    autoEncrypt?: boolean;
    secureParameters?: (string | number)[];
    parameterValidation?: boolean;
    memoryWipeDelay?: number;
    stackTraceProtection?: boolean;
    smartSecurity?: boolean;
    threatDetection?: boolean;
    memoize?: boolean;
    /**
     * Timeout in milliseconds. Default is 14 seconds.
     */
    timeout?: number;
    retries?: number;
    maxRetryDelay?: number;
    smartCaching?: boolean;
    cacheStrategy?: "lru" | "lfu" | "adaptive";
    cacheTTL?: number;
    maxCacheSize?: number;
    errorHandling?: "graceful";
    precompile?: boolean;
    optimizeExecution?: boolean;
    autoTuning?: boolean;
    predictiveAnalytics?: boolean;
    adaptiveTimeout?: boolean;
    intelligentRetry?: boolean;
    anomalyDetection?: boolean;
    performanceRegression?: boolean;
    auditLog?: boolean;
    performanceTracking?: boolean;
    debugMode?: boolean;
    detailedMetrics?: boolean;
    memoryPool?: boolean;
    maxMemoryUsage?: number;
    autoCleanup?: boolean;
    smartMemoryManagement?: boolean;
    memoryPressureHandling?: boolean;
}
interface FunctionStats {
    executionCount: number;
    totalExecutionTime: number;
    averageExecutionTime: number;
    memoryUsage: number;
    cacheHits: number;
    cacheMisses: number;
    errorCount: number;
    lastExecuted: Date;
    securityEvents: number;
    timingStats?: TimingStats;
}
interface TimingMeasurement {
    label: string;
    startTime: number;
    endTime?: number;
    duration?: number;
    metadata?: Record<string, any>;
}
interface TimingStats {
    totalMeasurements: number;
    completedMeasurements: number;
    activeMeasurements: number;
    measurements: TimingMeasurement[];
    summary: {
        totalDuration: number;
        averageDuration: number;
        minDuration: number;
        maxDuration: number;
        slowestOperation: string;
        fastestOperation: string;
    };
}
interface AuditEntry {
    timestamp: Date;
    executionId: string;
    parametersHash: string;
    executionTime: number;
    memoryUsage: number;
    success: boolean;
    errorMessage?: string;
    securityFlags: string[];
}
interface SecureExecutionContext {
    executionId: string;
    encryptedParameters: Map<string, string>;
    secureBuffers: Map<string, SecureBuffer>;
    startTime: number;
    memorySnapshot: number;
    auditEntry: AuditEntry;
}
interface ExecutionEvent {
    executionId: string;
    timestamp: Date;
    type: "start" | "success" | "error" | "timeout" | "retry";
    data?: any;
}
interface CacheEntry<R> {
    result: R;
    timestamp: number;
    accessCount: number;
    lastAccessed: Date;
    ttl?: number;
    priority?: number;
    size?: number;
    frequency?: number;
}
interface SecurityFlags {
    encrypted: boolean;
    audited: boolean;
    memoryManaged: boolean;
    stackProtected: boolean;
}
interface PerformanceMetrics {
    executionTime: number;
    memoryUsage: number;
    cpuUsage: number;
    cacheHitRate: number;
    errorRate: number;
    throughput: number;
    latency: number;
}
interface ExecutionPattern {
    parametersHash: string;
    frequency: number;
    averageExecutionTime: number;
    lastExecuted: Date;
    predictedNextExecution?: Date;
    cacheWorthiness: number;
}
interface OptimizationSuggestion {
    type: "cache" | "timeout" | "retry" | "memory" | "security";
    priority: "low" | "medium" | "high" | "critical";
    description: string;
    expectedImprovement: number;
    implementation: string;
}
interface AnalyticsData {
    patterns: ExecutionPattern[];
    trends: PerformanceMetrics[];
    anomalies: AnomalyDetection[];
    predictions: PredictiveAnalysis[];
}
interface AnomalyDetection {
    type: "performance" | "memory" | "security" | "error";
    severity: "low" | "medium" | "high";
    description: string;
    timestamp: Date;
    metrics: Record<string, number>;
}
interface PredictiveAnalysis {
    metric: string;
    currentValue: number;
    predictedValue: number;
    confidence: number;
    timeframe: number;
    trend: "increasing" | "decreasing" | "stable";
}
/**
 * Enhanced function type that provides access to FortifiedFunction methods
 * while maintaining the original function signature
 */
interface EnhancedFortifiedFunction<T extends any[], R> {
    (...args: T): Promise<R>;
    getStats(): FunctionStats;
    getAnalyticsData(): AnalyticsData;
    getOptimizationSuggestions(): OptimizationSuggestion[];
    getPerformanceTrends(): PerformanceMetrics[];
    detectAnomalies(): AnomalyDetection[];
    getDetailedMetrics(): Record<string, any>;
    clearCache(): void;
    getCacheStats(): {
        hits: number;
        misses: number;
        size: number;
    };
    warmCache(args: T[]): Promise<void>;
    handleMemoryPressure(level: "low" | "medium" | "high"): void;
    optimizePerformance(): void;
    updateOptions(options: Partial<FortifiedFunctionOptions>): void;
    getConfiguration(): FortifiedFunctionOptions;
    startTimer(label: string, metadata?: Record<string, any>): void;
    endTimer(label: string, additionalMetadata?: Record<string, any>): number;
    measureDelay(startPoint: string, endPoint: string): number;
    timeFunction<U>(label: string, fn: () => U | Promise<U>, metadata?: Record<string, any>): Promise<{
        result: U;
        duration: number;
    }>;
    getTimingStats(): TimingStats;
    clearTimings(): void;
    destroy(): void;
    readonly _fortified: any;
}

/**
 * Fortified Function - Secure function wrapper using existing FortifyJS components
 */
declare class FortifiedFunction<T extends any[], R> extends EventEmitter {
    private readonly originalFunction;
    private readonly options;
    private readonly securityHandler;
    private readonly performanceMonitor;
    private readonly executionEngine;
    private performanceTimer;
    private isDestroyed;
    private cleanupInterval?;
    constructor(fn: (...args: T) => R | Promise<R>, options?: FortifiedFunctionOptions);
    /**
     * Execute the fortified function with full security and memory management
     */
    execute(...args: T): Promise<R>;
    /**
     * **ULTRA-FAST EXECUTION: Bypass all overhead for maximum performance**
     */
    private executeUltraFast;
    /**
     * Set up automatic cleanup of old cache entries
     */
    private setupAutoCleanup;
    /**
     * Get current memory usage
     */
    private getCurrentMemoryUsage;
    /**
     * 🤖 Automatically apply optimization suggestions
     */
    private autoApplyOptimizations;
    /**
     * 🔧 Apply a specific optimization suggestion automatically
     */
    private applySuggestionAutomatically;
    /**
     * Public API methods
     */
    getStats(): FunctionStats;
    getAuditLog(): AuditEntry[];
    getCacheStats(): {
        totalHits: number;
        totalMisses: number;
        hitRate: number;
        size: number;
        maxSize: number;
        strategy: "lru" | "lfu" | "adaptive";
        averageAccessCount: number;
        memoryUsage: number;
        hits: number;
        misses: number;
        evictions: number;
        totalSize: number;
        compressionRatio: number;
    };
    clearCache(): void;
    clearAuditLog(): void;
    getActiveExecutionsCount(): number;
    /**
     * Smart Actions and Analytics Methods
     */
    getAnalyticsData(): AnalyticsData;
    getOptimizationSuggestions(): OptimizationSuggestion[];
    getPerformanceTrends(): PerformanceMetrics[];
    warmCache(): void;
    handleMemoryPressure(level: "low" | "medium" | "high"): void;
    detectAnomalies(): AnomalyDetection[];
    getDetailedMetrics(): {
        stats: FunctionStats;
        cacheStats: {
            totalHits: number;
            totalMisses: number;
            hitRate: number;
            size: number;
            maxSize: number;
            strategy: "lru" | "lfu" | "adaptive";
            averageAccessCount: number;
            memoryUsage: number;
            hits: number;
            misses: number;
            evictions: number;
            totalSize: number;
            compressionRatio: number;
        };
        analytics: AnalyticsData;
        suggestions: OptimizationSuggestion[];
        trends: PerformanceMetrics[];
        anomalies: AnomalyDetection[];
    } | null;
    /**
     * Destroy the fortified function and clean up resources
     */
    destroy(): void;
    /**
     * Update function options dynamically
     * @param newOptions - Partial options to update
     */
    updateOptions(newOptions: Partial<FortifiedFunctionOptions>): void;
    /**
     * Optimize performance by applying recommended settings
     */
    optimizePerformance(): void;
    /**
     * **PERFORMANCE TIMING METHODS**
     */
    /**
     * Initialize performance timer for current execution
     */
    private initializePerformanceTimer;
    /**
     * Start timing a specific operation
     */
    startTimer(label: string, metadata?: Record<string, any>): void;
    /**
     * End timing for a specific operation
     */
    endTimer(label: string, additionalMetadata?: Record<string, any>): number;
    /**
     * Measure delay between two points
     */
    measureDelay(startPoint: string, endPoint: string): number;
    /**
     * Time a function execution
     */
    timeFunction<U>(label: string, fn: () => U | Promise<U>, metadata?: Record<string, any>): Promise<{
        result: U;
        duration: number;
    }>;
    /**
     * Get timing statistics
     */
    getTimingStats(): TimingStats;
    /**
     * Clear all timing measurements
     */
    clearTimings(): void;
    /**
     * Get measurements by pattern
     */
    getMeasurementsByPattern(pattern: RegExp): any[];
    /**
     * Check if a timer is active
     */
    isTimerActive(label: string): boolean;
    /**
     * Get active timers
     */
    getActiveTimers(): string[];
}

/***************************************************************************
 * FortifyJS - Secure Array Types
 *
 * This file contains type definitions for the SecureArrayarchitecture
 *
 * @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.
 ***************************************************************************** */
/**
 * FortifyJS - Fortified Functions (Modular Architecture)
 * Main entry point for the fortified function system
 */

/**
 * Zero-Configuration Smart Function Factory
 *
 * Creates  fortified functions with enterprise-grade security,
 * performance optimization, and intelligent caching enabled by default.
 * No manual configuration required for optimal performance.
 *
 * @param fn - The function to be fortified with smart capabilities
 * @param options - Optional configuration overrides (all features enabled by default)
 * @returns A fortified function with enhanced security and performance features
 *
 * @example
 * ```typescript
 * import { func } from 'fortify2-js';
 *
 * // Zero configuration needed - all smart features enabled by default
 * const smartFunction = func(async (data: string) => {
 *     return processData(data);
 * });
 *
 * // Execute with automatic optimization
 * const result = await smartFunction('sensitive data');
 *
 * // Optional: Override specific settings if needed
 * const customFunction = func(myFunction, {
 *     maxCacheSize: 5000,
 *     debugMode: true
 * });
 * ```
 */
declare function func<T extends any[], R>(fn: (...args: T) => R | Promise<R>, options?: Partial<FortifiedFunctionOptions>): EnhancedFortifiedFunction<T, R>;
/**
 * Create a fortified function with full access to smart analytics and optimization
 * Provides complete access to performance metrics, analytics, and optimization features
 *
 * @example
 * ```typescript
 * import { createFortifiedFunction } from 'fortify2-js';
 *
 * const fortified = createFortifiedFunction(myFunction, {
 *     autoEncrypt: true,
 *     smartCaching: true,
 *     predictiveAnalytics: true,
 *     detailedMetrics: true
 * });
 *
 * // Execute
 * const result = await fortified.execute('data');
 *
 * // Access enhanced analytics
 * const analytics = fortified.getAnalyticsData();
 * const suggestions = fortified.getOptimizationSuggestions();
 * const trends = fortified.getPerformanceTrends();
 * const anomalies = fortified.detectAnomalies();
 *
 * // Smart actions
 * fortified.warmCache();
 * fortified.handleMemoryPressure('medium');
 *
 * // Get comprehensive metrics
 * const detailedMetrics = fortified.getDetailedMetrics();
 *
 * // Clean up when done
 * fortified.destroy();
 * ```
 */
declare function createFortifiedFunction<T extends any[], R>(fn: (...args: T) => R | Promise<R>, options?: Partial<FortifiedFunctionOptions>): FortifiedFunction<T, R>;

/**
 * @author iDevo
 * Enhanced RSA Key Size Calculator
 * Calculates appropriate RSA key size based on data size with improved security and performance
 */
declare const HASH_SIZES: {
    readonly sha1: 20;
    readonly sha224: 28;
    readonly sha256: 32;
    readonly sha384: 48;
    readonly sha512: 64;
    readonly sha3_256: 32;
    readonly sha3_384: 48;
    readonly sha3_512: 64;
};
declare const SECURITY_LEVELS: {
    readonly minimal: {
        readonly bits: 80;
        readonly description: "Legacy compatibility only";
        readonly minKeySize: 1024;
    };
    readonly standard: {
        readonly bits: 112;
        readonly description: "Current standard security";
        readonly minKeySize: 2048;
    };
    readonly high: {
        readonly bits: 128;
        readonly description: "High security applications";
        readonly minKeySize: 3072;
    };
    readonly maximum: {
        readonly bits: 256;
        readonly description: "Maximum security";
        readonly minKeySize: 15360;
    };
};
type HashAlgorithm = keyof typeof HASH_SIZES;
type SecurityLevel = keyof typeof SECURITY_LEVELS;
interface RSAKeyPair {
    publicKey: string;
    privateKey: string;
    keySize: number;
    maxDataSize: number;
    hashAlgorithm: HashAlgorithm;
}
interface RSATestResult {
    success: boolean;
    error?: string;
    encryptedSize?: number;
    decryptedMatches?: boolean;
    performanceMs?: number;
}
interface RSARecommendation {
    keySize: number;
    maxDataSize: number;
    securityLevel: "minimal" | "standard" | "high" | "maximum";
    recommendation: string;
}
interface KeyValidationResult {
    isValid: boolean;
    errors: string[];
    warnings: string[];
    securityScore: number;
    recommendations: string[];
}
/**
 * Calculate the minimum RSA key size needed for the given data size
 * @param dataSize - Size of data to encrypt in bytes
 * @param hashAlgorithm - Hash algorithm for OAEP padding (default: sha256)
 * @param allowCustomSize - Allow non-standard key sizes (default: false)
 * @returns Recommended RSA key size in bits
 */
declare function calculateRSAKeySize(dataSize: number, hashAlgorithm?: HashAlgorithm, allowCustomSize?: boolean): number;
/**
 * Generate RSA key pair with appropriate size for the given data
 * @param dataSize - Size of data to encrypt in bytes
 * @param hashAlgorithm - Hash algorithm for OAEP padding
 * @param allowCustomSize - Allow non-standard key sizes
 * @returns RSA key pair with metadata
 */
declare function generateRSAKeyPairForData(dataSize: number, hashAlgorithm?: HashAlgorithm, allowCustomSize?: boolean): RSAKeyPair;
/**
 * Generate password-protected RSA key pair
 * @param dataSize - Size of data to encrypt in bytes
 * @param passphrase - Password to protect the private key
 * @param hashAlgorithm - Hash algorithm for OAEP padding
 * @returns Protected RSA key pair
 */
declare function generateProtectedRSAKeyPairForData(dataSize: number, passphrase: string, hashAlgorithm?: HashAlgorithm): RSAKeyPair;
/**
 * Get maximum data size that can be encrypted with a given RSA key size
 * @param rsaKeySize - RSA key size in bits
 * @param hashAlgorithm - Hash algorithm used for OAEP
 * @returns Maximum data size in bytes
 */
declare function getMaxDataSizeForRSAKey(rsaKeySize: number, hashAlgorithm?: HashAlgorithm): number;
/**
 * Validate if data can be encrypted with the given RSA key
 * @param dataSize - Size of data in bytes
 * @param rsaKeySize - RSA key size in bits
 * @param hashAlgorithm - Hash algorithm used for OAEP
 * @returns Validation result with details
 */
declare function validateDataSizeForRSAKey(dataSize: number, rsaKeySize: number, hashAlgorithm?: HashAlgorithm): {
    valid: boolean;
    maxDataSize: number;
    recommendation?: string;
};
/**
 * Get RSA key size recommendations for different security levels
 * @param dataSize - Size of data to encrypt in bytes
 * @param hashAlgorithm - Hash algorithm for OAEP padding
 * @returns Array of recommendations
 */
declare function getRSARecommendations(dataSize: number, hashAlgorithm?: HashAlgorithm): RSARecommendation[];
/**
 * Test RSA encryption/decryption with performance monitoring
 * @param dataSize - Size of test data in bytes
 * @param rsaKeySize - RSA key size in bits
 * @param hashAlgorithm - Hash algorithm for OAEP padding
 * @param iterations - Number of test iterations for performance measurement
 * @returns Comprehensive test result
 */
declare function testRSAWithDataSize(dataSize: number, rsaKeySize: number, hashAlgorithm?: HashAlgorithm, iterations?: number): Promise<RSATestResult>;
/**
 * Benchmark RSA performance across different key sizes
 * @param dataSize - Size of test data in bytes
 * @param keySizes - Array of key sizes to test
 * @param iterations - Number of iterations per key size
 * @returns Performance comparison results
 */
declare function benchmarkRSAPerformance(dataSize: number, keySizes?: number[], iterations?: number): Promise<Array<{
    keySize: number;
    avgTimeMs: number;
    success: boolean;
    error?: string;
}>>;
/**
 * Utility to suggest hybrid encryption when RSA alone is inefficient
 * @param dataSize - Size of data to encrypt in bytes
 * @returns Suggestion for encryption approach
 */
declare function getEncryptionSuggestion(dataSize: number): {
    approach: "rsa" | "hybrid";
    reason: string;
    details?: {
        aesKeySize: number;
        rsaKeySize: number;
        estimatedPerformanceGain?: string;
    };
};
/**
 * Enhanced key validation with security assessment
 * @param publicKey - RSA public key in PEM format
 * @param privateKey - RSA private key in PEM format (optional)
 * @returns Comprehensive validation result
 */
declare function validateRSAKeyPair(publicKey: string, privateKey?: string): KeyValidationResult;
/**
 * Enhanced security assessment for RSA configuration
 * @param keySize - RSA key size in bits
 * @param hashAlgorithm - Hash algorithm used
 * @param dataSize - Size of data to encrypt
 * @returns Security assessment with recommendations
 */
declare function assessRSASecurity(keySize: number, hashAlgorithm: HashAlgorithm, dataSize: number): {
    level: SecurityLevel;
    score: number;
    vulnerabilities: string[];
    recommendations: string[];
    compliance: {
        nist: boolean;
        fips: boolean;
        commonCriteria: boolean;
    };
};

/**
 * Enhanced encoding utilities for various formats
 */
/**
 * Convert a buffer to a hexadecimal string
 * @param buffer - The buffer to convert
 * @param uppercase - Whether to use uppercase letters (default: false)
 * @param separator - Optional separator between bytes (e.g., ':', ' ', '-')
 * @returns Hexadecimal string representation
 */
declare function bufferToHex(buffer: Uint8Array, uppercase?: boolean, separator?: string): string;
/**
 * Convert a hexadecimal string to a buffer
 * @param hex - The hexadecimal string to convert
 * @returns Uint8Array representation
 */
declare function hexToBuffer(hex: string): Uint8Array;
/**
 * Convert a buffer to a binary string
 * @param buffer - The buffer to convert
 * @param separator - Optional separator between bytes (e.g., ' ', '-')
 * @returns Binary string representation
 */
declare function bufferToBinary(buffer: Uint8Array, separator?: string): string;
/**
 * Convert a binary string to a buffer
 * @param binary - The binary string to convert
 * @returns Uint8Array representation
 */
declare function binaryToBuffer(binary: string): Uint8Array;
/**
 * Convert a number to binary string with specified bit width
 * @param num - The number to convert
 * @param bits - The number of bits (default: 8)
 * @returns Binary string representation
 */
declare function numberToBinary(num: number, bits?: number): string;
/**
 * Convert a binary string to a number
 * @param binary - The binary string to convert
 * @returns Number representation
 */
declare function binaryToNumber(binary: string): number;
/**
 * Convert a buffer to a Base64 string
 * @param buffer - The buffer to convert
 * @param urlSafe - Whether to use URL-safe Base64 (default: false)
 * @returns Base64 string representation
 */
declare function bufferToBase64(buffer: Uint8Array, urlSafe?: boolean): string;
/**
 * Convert a Base64 string to a buffer
 * @param base64 - The Base64 string to convert
 * @param urlSafe - Whether the input is URL-safe Base64 (default: false)
 * @returns Uint8Array representation
 */
declare function base64ToBuffer(base64: string, urlSafe?: boolean): Uint8Array;
/**
 * Convert a buffer to a Base58 string (Bitcoin style)
 * @param buffer - The buffer to convert
 * @returns Base58 string representation
 */
declare function bufferToBase58(buffer: Uint8Array): string;
/**
 * Convert a Base58 string to a buffer
 * @param base58 - The Base58 string to convert
 * @returns Uint8Array representation
 */
declare function base58ToBuffer(base58: string): Uint8Array;
/**
 * Convert a buffer to a Base32 string (RFC 4648)
 * @param buffer - The buffer to convert
 * @param padding - Whether to include padding (default: true)
 * @returns Base32 string representation
 */
declare function bufferToBase32(buffer: Uint8Array, padding?: boolean): string;
/**
 * Convert a Base32 string to a buffer
 * @param base32 - The Base32 string to convert
 * @returns Uint8Array representation
 */
declare function base32ToBuffer(base32: string): Uint8Array;
/**
 * Convert a buffer to an octal string
 * @param buffer - The buffer to convert
 * @param separator - Optional separator between bytes
 * @returns Octal string representation
 */
declare function bufferToOctal(buffer: Uint8Array, separator?: string): string;
/**
 * Convert an octal string to a buffer
 * @param octal - The octal string to convert
 * @returns Uint8Array representation
 */
declare function octalToBuffer(octal: string): Uint8Array;
/**
 * Convert a number to octal string
 * @param num - The number to convert
 * @returns Octal string representation
 */
declare function numberToOctal(num: number): string;
/**
 * Convert an octal string to a number
 * @param octal - The octal string to convert
 * @returns Number representation
 */
declare function octalToNumber(octal: string): number;
/**
 * Convert a string to a buffer using UTF-8 encoding
 * @param str - The string to convert
 * @returns Uint8Array representation
 */
declare function stringToBuffer(str: string): Uint8Array;
/**
 * Convert a string directly to hexadecimal representation
 * @param str - The string to convert
 * @param uppercase - Whether to use uppercase letters (default: false)
 * @param separator - Optional separator between bytes
 * @returns Hexadecimal string representation
 */
declare function stringToHex(str: string, uppercase?: boolean, separator?: string): string;
/**
 * Convert a hexadecimal string back to a string
 * @param hex - The hexadecimal string to convert
 * @returns String representation
 */
declare function hexToString(hex: string): string;
/**
 * Convert a string directly to Base64 encoding
 * @param str - The string to encode
 * @param urlSafe - Whether to use URL-safe Base64 (default: false)
 * @returns Base64 encoded string
 */
declare function stringToBase64(str: string, urlSafe?: boolean): string;
/**
 * Convert a Base64 encoded string back to string
 * @param base64 - The Base64 encoded string
 * @param urlSafe - Whether the input is URL-safe Base64 (default: false)
 * @returns Decoded string
 */
declare function base64ToString(base64: string, urlSafe?: boolean): string;
/**
 * Convert a buffer to a string using UTF-8 decoding
 * @param buffer - The buffer to convert
 * @returns String representation
 */
declare function bufferToString(buffer: Uint8Array): string;
/**
 * Convert a string to ASCII bytes
 * @param str - The string to convert
 * @returns Uint8Array with ASCII codes
 */
declare function stringToAscii(str: string): Uint8Array;
/**
 * Convert ASCII bytes to a string
 * @param buffer - The buffer with ASCII codes
 * @returns String representation
 */
declare function asciiToString(buffer: Uint8Array): string;
/**
 * Convert a string to Base64URL encoding
 * @param str - The string to encode
 * @returns Base64URL encoded string
 */
declare function stringToBase64Url(str: string): string;
/**
 * Convert a Base64URL encoded string back to string
 * @param base64url - The Base64URL encoded string
 * @returns Decoded string
 */
declare function base64UrlToString(base64url: string): string;
/**
 * Convert regular Base64 to Base64URL
 * @param base64 - The regular Base64 string
 * @returns Base64URL string
 */
declare function base64ToBase64Url(base64: string): string;
/**
 * Convert Base64URL to regular Base64
 * @param base64url - The Base64URL string
 * @returns Regular Base64 string
 */
declare function base64UrlToBase64(base64url: string): string;
/**
 * Convert a buffer to Base64URL encoding
 * @param buffer - The buffer to convert
 * @returns Base64URL encoded string
 */
declare function bufferToBase64Url(buffer: Uint8Array): string;
/**
 * Convert a Base64URL string to a buffer
 * @param base64url - The Base64URL string to convert
 * @returns Uint8Array representation
 */
declare function base64UrlToBuffer(base64url: string): Uint8Array;
/**
 * URL encode a string
 * @param str - The string to encode
 * @returns URL encoded string
 */
declare function urlEncode(str: string): string;
/**
 * URL decode a string
 * @param str - The URL encoded string to decode
 * @returns Decoded string
 */
declare function urlDecode(str: string): string;
/**
 * Convert a buffer to URL encoded string
 * @param buffer - The buffer to convert
 * @returns URL encoded string
 */
declare function bufferToUrlEncoded(buffer: Uint8Array): string;
/**
 * Convert a number to any base (2-36)
 * @param num - The number to convert
 * @param base - The target base (2-36)
 * @returns String representation in the specified base
 */
declare function numberToBase(num: number, base: number): string;
/**
 * Convert a string from any base (2-36) to a number
 * @param str - The string to convert
 * @param base - The base of the input string (2-36)
 * @returns Number representation
 */
declare function baseToNumber(str: string, base: number): number;
/**
 * Convert between different number bases
 * @param str - The input string
 * @param fromBase - The base of the input string
 * @param toBase - The target base
 * @returns String representation in the target base
 */
declare function convertBase(str: string, fromBase: number, toBase: number): string;
/**
 * Convert a 16-bit number to bytes (little-endian)
 * @param num - The 16-bit number
 * @returns Uint8Array with 2 bytes
 */
declare function uint16ToBytes(num: number): Uint8Array;
/**
 * Convert bytes to a 16-bit number (little-endian)
 * @param buffer - The buffer with 2 bytes
 * @returns 16-bit number
 */
declare function bytesToUint16(buffer: Uint8Array): number;
/**
 * Convert a 32-bit number to bytes (little-endian)
 * @param num - The 32-bit number
 * @returns Uint8Array with 4 bytes
 */
declare function uint32ToBytes(num: number): Uint8Array;
/**
 * Convert bytes to a 32-bit number (little-endian)
 * @param buffer - The buffer with 4 bytes
 * @returns 32-bit number
 */
declare function bytesToUint32(buffer: Uint8Array): number;
/**
 * Reverse byte order (swap endianness)
 * @param buffer - The buffer to reverse
 * @returns New buffer with reversed byte order
 */
declare function reverseBytes(buffer: Uint8Array): Uint8Array;
/**
 * Compare two buffers for equality
 * @param a - First buffer
 * @param b - Second buffer
 * @returns True if buffers are equal
 */
declare function buffersEqual(a: Uint8Array, b: Uint8Array): boolean;
/**
 * Concatenate multiple buffers
 * @param buffers - Array of buffers to concatenate
 * @returns New buffer containing all input buffers
 */
declare function concatBuffers(...buffers: Uint8Array[]): Uint8Array;
/**
 * XOR two buffers
 * @param a - First buffer
 * @param b - Second buffer
 * @returns New buffer with XOR result
 */
declare function xorBuffers(a: Uint8Array, b: Uint8Array): Uint8Array;
/**
 * Generate a random buffer
 * @param length - The length of the buffer
 * @returns Random buffer
 */
declare function randomBuffer(length: number): Uint8Array;
/**
 * Pad a buffer to a specific length
 * @param buffer - The buffer to pad
 * @param length - The target length
 * @param value - The padding value (default: 0)
 * @param left - Whether to pad on the left (default: false)
 * @returns Padded buffer
 */
declare function padBuffer(buffer: Uint8Array, length: number, value?: number, left?: boolean): Uint8Array;
/**
 * Calculate checksum of a buffer (simple XOR checksum)
 * @param buffer - The buffer to checksum
 * @returns Checksum value
 */
declare function simpleChecksum(buffer: Uint8Array): number;
/**
 * Split a buffer into chunks
 * @param buffer - The buffer to split
 * @param chunkSize - The size of each chunk
 * @returns Array of buffer chunks
 */
declare function chunkBuffer(buffer: Uint8Array, chunkSize: number): Uint8Array[];
/**
 * Format bytes as human-readable string
 * @param bytes - The number of bytes
 * @param decimals - Number of decimal places (default: 2)
 * @returns Formatted string (e.g., "1.23 KB")
 */
declare function formatBytes(bytes: number, decimals?: number): string;
/**
 * Auto-detect encoding format of a string
 * @param str - The string to analyze
 * @returns Detected format or 'unknown'
 */
declare function detectEncoding(str: string): string;

declare const sqlPatterns: RegExp[];
declare const xssPatterns: RegExp[];
declare const contexts: {
    ldap: RegExp[];
    xml: RegExp[];
    command: RegExp[];
    pathTraversal: RegExp[];
    nosql: RegExp[];
};

/**
 *  Function to test input against all patterns
 *  @example
 *  const testInput = "'; DROP TABLE users; --";
    const result = detectInjection(testInput);
    console.log(result);
    // Output: { sql: true, xss: false, type: 'sql', matches: [...] }
 */
declare function detectInjection(input: string, patternType?: string): {
    sql: boolean;
    xss: boolean;
    type: "sql" | "xss" | "mixed" | null;
    matches: {
        type: string;
        pattern: string;
        match: RegExpMatchArray | null;
    }[];
};

/**
 * Ultra-Fast Plugin System Types
 *
 * Comprehensive type definitions for the FortifyJS plugin architecture
 * designed to achieve <1ms execution overhead while maintaining security.
 */

/**
 * Plugin execution phases for optimal performance routing
 */
declare enum PluginType {
    PRE_REQUEST = "pre-request",// <0.5ms - Request preprocessing, parsing optimization
    SECURITY = "security",// <2ms - Authentication, authorization, validation
    CACHE = "cache",// <0.5ms - Cache operations, hit/miss handling
    PERFORMANCE = "performance",// <0.3ms - Metrics collection, monitoring
    POST_RESPONSE = "post-response",// <0.2ms - Cleanup, logging, analytics
    MIDDLEWARE = "middleware",// <1ms - Custom Express middleware integration
    NATIVE = "native"
}

/**
 * Centralized Logger for FastApi.ts Server
 * Provides granular control over logging output
 */

declare class Logger {
    private config;
    private static instance;
    constructor(config?: ServerOptions["logging"]);
    /**
     * Get or create singleton instance
     */
    static getInstance(config?: ServerOptions["logging"]): Logger;
    /**
     * Update logger configuration
     */
    updateConfig(config: ServerOptions["logging"]): void;
    /**
     * Check if logging is enabled for a specific component and type
     */
    private shouldLog;
    /**
     * Format log message
     */
    private formatMessage;
    /**
     * Log a message
     */
    private log;
    error(component: LogComponent, message: string, ...args: any[]): void;
    warn(component: LogComponent, message: string, ...args: any[]): void;
    info(component: LogComponent, message: string, ...args: any[]): void;
    debug(component: LogComponent, message: string, ...args: any[]): void;
    startup(component: LogComponent, message: string, ...args: any[]): void;
    performance(component: LogComponent, message: string, ...args: any[]): void;
    hotReload(component: LogComponent, message: string, ...args: any[]): void;
    portSwitching(component: LogComponent, message: string, ...args: any[]): void;
    securityWarning(message: string, ...args: any[]): void;
    isEnabled(): boolean;
    getLevel(): LogLevel$1;
    isComponentEnabled(component: LogComponent): boolean;
    isTypeEnabled(type: LogType): boolean;
}

/***************************************************************************
 * FortifyJS - Secure Array Types
 *
 * This file contains type definitions for the SecureArray 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.
 ***************************************************************************** */
/**
 * Console Interception System for FastServer
 * Intercepts and manages all console output through the unified logging system
 */

declare class ConsoleInterceptor {
    private logger;
    private config;
    private originalConsole;
    private isIntercepting;
    private stats;
    private errorCount;
    private lastSecondInterceptions;
    private lastSecondTimestamp;
    private performanceBuffer;
    private rateLimitCounter;
    private rateLimitWindow;
    private isProcessing;
    private processingDepth;
    private maxProcessingDepth;
    private encryptionHandler;
    private preserveOption;
    constructor(logger: Logger, config?: ServerOptions["logging"]);
    /**
     * Parse preserve option configuration
     * Supports both boolean (backward compatibility) and object configuration
     */
    private parsePreserveOption;
    /**
     * Initialize encryption handler
     */
    private initializeEncryptionHandler;
    /**
     * Start console interception
     */
    start(): void;
    /**
     * Stop console interception and restore original console
     */
    stop(): void;
    /**
     * Get current interception statistics
     */
    getStats(): ConsoleInterceptionStats;
    /**
     * Update configuration at runtime
     */
    updateConfig(newConfig: Partial<ConsoleInterceptionConfig>): void;
    /**
     * Backup original console methods
     */
    private backupOriginalConsole;
    /**
     * Restore original console methods
     */
    private restoreOriginalConsole;
    /**
     * Intercept console methods
     */
    private interceptConsoleMethods;
    /**
     * Handle intercepted console call
     */
    private handleInterceptedCall;
    /**
     * Handle preserve display based on preserve option configuration
     */
    private handlePreserveDisplay;
    /**
     * Determine if logs should be routed to logger system
     */
    private shouldRouteToLogger;
    /**
     * Check rate limiting
     */
    private checkRateLimit;
    /**
     * Map console method to log level
     */
    private mapMethodToLogLevel;
    /**
     * Add source information to intercepted call
     */
    private addSourceInformation;
    /**
     * Check if call should be intercepted based on filters
     */
    private shouldInterceptCall;
    /**
     * Process intercepted console call through logging system
     */
    private processInterceptedCall;
    /**
     * Update statistics
     */
    private updateStats;
    /**
     * Handle errors in the interception system
     */
    private handleError;
    /**
     * Check if interception is currently active
     */
    isActive(): boolean;
    /**
     * Reset statistics
     */
    resetStats(): void;
    /**
     * Enable console encryption with a key
     * @param key - Encryption key (if not provided, will use environment variable)
     */
    enableEncryption(key?: string): void;
    /**
     * Disable console encryption
     */
    disableEncryption(): void;
    /**
     * Set encryption key for console output
     * @param key - The encryption key to use
     */
    setEncryptionKey(key: string): void;
    /**
     * Simple encrypt method - enables encryption with key
     * Works independently from preserveOriginal setting
     * @param key - Encryption key
     */
    encrypt(key: string): void;
    /**
     * Update encryption display mode
     * @param displayMode - How to display encrypted logs
     * @param showEncryptionStatus - Whether to show encryption indicators
     */
    setEncryptionDisplayMode(displayMode: "readable" | "encrypted" | "both", showEncryptionStatus?: boolean): void;
    /**
     * Get encrypted console logs (for external transmission)
     * @returns Array of encrypted log entries
     */
    getEncryptedLogs(): string[];
    /**
     * Restore console logs from encrypted data
     * @param encryptedData - Array of encrypted log entries
     * @param key - Decryption key
     * @returns Array of decrypted log entries
     */
    restoreFromEncrypted(encryptedData: string[], key: string): Promise<string[]>;
    /**
     * Generate a temporary encryption key (for development)
     */
    private generateTemporaryKey;
    /**
     * Extract encrypted hash from the full encrypted JSON structure
     */
    private extractEncryptedHash;
    /**
     * Check if encryption is currently enabled
     */
    isEncryptionEnabled(): boolean;
    /**
     * Get encryption status and configuration
     */
    getEncryptionStatus(): {
        enabled: boolean;
        algorithm?: string;
        hasKey: boolean;
        externalLogging?: boolean;
    };
}

/**
 * Ultra-Fast Express Server with Advanced Performance Optimization
 */
declare class UltraFastServer {
    private app;
    private options;
    private ready;
    private initPromise;
    private httpServer?;
    private logger;
    private currentPort;
    private cacheManager;
    private middlewareManager;
    private middlewareMethodsManager;
    private requestProcessor;
    private routeManager;
    private performanceManager;
    private monitoringManager;
    private pluginManager;
    private clusterManager;
    private fileWatcherManager;
    private redirectManager;
    private consoleInterceptor;
    constructor(userOptions?: ServerOptions);
    /**
     * Initialize all component instances with proper dependencies
     */
    private initializeComponents;
    /**
     * Get the Express app instance (ready to use immediately)
     */
    getApp(): UltraFastApp;
    /**
     * Wait for full initialization (cache, console interceptor, and all components)
     */
    waitForReady(): Promise<void>;
    /**
     * Get the RequestPreCompiler instance for configuration
     */
    getRequestPreCompiler(): RequestPreCompiler;
    /**
     * Get the ConsoleInterceptor instance for configuration
     */
    getConsoleInterceptor(): ConsoleInterceptor;
    /**
     * Merge user options with defaults and file config
     */
    private mergeWithDefaults;
    /**
     * Handle automatic port switching when port is in use
     */
    private handlePortSwitching;
    /**
     * Start server with error handling and port switching
     */
    private startServerWithPortHandling;
    /**
     * Add start method to app with cluster support
     */
    private addStartMethod;
    /**
     * Stop file watcher
     */
    stopFileWatcher(): Promise<void>;
    /**
     * Get file watcher status
     */
    getFileWatcherStatus(): any;
    /**
     * Get file watcher restart stats
     */
    getFileWatcherStats(): any;
    /**
     * Register a plugin with the server
     */
    registerPlugin(plugin: any): Promise<void>;
    /**
     * Unregister a plugin from the server
     */
    unregisterPlugin(pluginId: string): Promise<void>;
    /**
     * Get plugin by ID
     */
    getPlugin(pluginId: string): any;
    /**
     * Get all registered plugins
     */
    getAllPlugins(): any[];
    /**
     * Get plugins by type
     */
    getPluginsByType(type: PluginType): any[];
    /**
     * Get plugin execution statistics
     */
    getPluginStats(pluginId?: string): any;
    /**
     * Get plugin registry statistics
     */
    getPluginRegistryStats(): any;
    /**
     * Get plugin engine statistics
     */
    getPluginEngineStats(): any;
    /**
     * Initialize built-in plugins
     */
    initializeBuiltinPlugins(): Promise<void>;
    /**
     * Get comprehensive server statistics including plugins
     */
    getServerStats(): Promise<any>;
    /**
     * Add console interception methods to the Express app
     */
    private addConsoleInterceptionMethods;
    /**
     * Get the actual running port number
     * @returns The current port the server is running on
     */
    getPort(): number;
    /**
     * Attempt to forcefully close/free up the specified port
     * @param port - The port number to force close
     * @returns Promise<boolean> - true if successful, false if failed
     */
    forceClosePort(port: number): Promise<boolean>;
}

/***************************************************************************
 * 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.
 ***************************************************************************** */
/**
 * Ultra-Fast Express (UFE) Server Factory
 *  Express applications with intelligent caching integration
 * Zero-async initialization for immediate use
 */

/**
 * Create ultra-fast Express server (zero-async)
 * Returns app instance ready to use immediately
 */
declare function createServer(options?: ServerOptions): UltraFastApp;
/**
 * Create ultra-fast Express server class instance
 */
declare function createServerInstance(options?: ServerOptions): UltraFastServer;
/**
 * Create cache middleware for routes
 */
declare function createCacheMiddleware(cache: SecureCacheAdapter, options?: RouteOptions): RequestHandler;
/**
 * Configure Express middleware
 */
declare function UFSMiddleware(app: UltraFastApp, options: ServerOptions): Promise<void>;

declare const createSecureCipheriv: typeof RandomCrypto.createSecureCipheriv;
declare const createSecureDecipheriv: typeof RandomCrypto.createSecureDecipheriv;
declare const generateSecureIV: typeof RandomCrypto.generateSecureIV;
declare const generateSecureIVBatch: typeof RandomCrypto.generateSecureIVBatch;
declare const generateSecureIVForAlgorithm: typeof RandomCrypto.generateSecureIVForAlgorithm;
declare const generateSecureIVBatchForAlgorithm: typeof RandomCrypto.generateSecureIVBatchForAlgorithm;
declare const validateIV: typeof RandomCrypto.validateIV;
declare const getRandomBytes: typeof SecureRandom.getRandomBytes;
declare const generateSessionToken: typeof RandomTokens.generateSessionToken;
declare const generateSecureUUID: typeof SecureRandom.generateSecureUUID;
declare const createSecureHash: typeof Hash.createSecureHash;
declare const createSecureHMAC: typeof HashAlgorithms.createSecureHMAC;
declare const verifyHash: typeof Hash.verifyHash;

/**
 * Fast password manager access but use default configuration
 * for custom config, use PasswordManager.create() or PasswordManager.getInstance()
 */
declare const pm: PasswordManager;
/**
 * @author iDevo
 * @description Creates a secure string that can be explicitly cleared from memory
 * @param str - The string to be converted to a secure string
 * @returns A new SecureString instance
 */
declare function fString(...args: Parameters<typeof createSecureString>): SecureString;
/**
 * @author iDevo
 * @description Creates a secure object that can be explicitly cleared from memory
 * @param initialData - The initial data to be stored in the secure object
 * @returns A new SecureObject instance
 */
declare function fObject<T extends Record<string, any>>(...args: Parameters<typeof createSecureObject<T>>): SecureObject<T>;
/**
 * @author Nehonix
 * @description Creates a secure array that can store sensitive data with enhanced security features
 * @param initialData - The initial data to be stored in the secure array
 * @returns A new SecureArray instance
 */
declare function fArray<T extends SecureArrayValue = SecureArrayValue>(...args: Parameters<typeof createSecureArray<T>>): SecureArray<T extends string ? string : T extends number ? number : T extends boolean ? boolean : T>;

/**
 * Encrypt a password with pepper and military-grade hashing
 *
 * This function provides an additional layer of security by applying a pepper (secret)
 * before hashing the password with Argon2ID. This protects against rainbow table attacks
 * even if the database is compromised.
 *
 * @author suppercodercodelover
 * @param password - The plain text password to encrypt
 * @param PEPPER - A secret pepper value (should be stored securely, not in database)
 * @returns Promise<string> - The peppered and hashed password ready for database storage
 * @throws Error if PEPPER is not provided
 *
 * @example
 * ```typescript
 * // Create pepper using Random
 * console.log("PASSWORD_PEPPER: ", Random.getRandomBytes(16))  // replace "16" with desired length then store securely (example in a .env file)
 * const pepper = process.env.PASSWORD_PEPPER; // Store securely!
 * const hashedPassword = await encryptSecurePass("userPassword123", pepper);
 * // Store hashedPassword in database
 * ```
 *
 * @security
 * - Uses HMAC-SHA256 for pepper application
 * - Uses Argon2ID for final password hashing
 * - Timing-safe operations prevent side-channel attacks
 */
declare function encryptSecurePass(password: string, PEPPER: string, options?: PasswordHashOptions): Promise<string>;
/**
 * Verify a password against a peppered hash with timing-safe comparison
 *
 * This function verifies a plain text password against a hash that was created
 * using encryptSecurePass(). It applies the same pepper and uses constant-time
 * verification to prevent timing attacks.
 *
 * @author suppercodercodelover
 * @param password - The plain text password to verify
 * @param hashedPassword - The peppered hash from database (created with encryptSecurePass)
 * @param PEPPER - The same secret pepper value used during encryption
 * @returns Promise<boolean> - true if password is valid, false otherwise
 * @throws Error if PEPPER is not provided
 *
 * @example
 * ```typescript
 * const pepper = process.env.PASSWORD_PEPPER; // Same pepper as encryption
 * const isValid = await verifyEncryptedPassword(
 *     "userPassword123",
 *     storedHashFromDB,
 *     pepper
 * );
 *
 * if (isValid) {
 *     console.log("Login successful!");
 * } else {
 *     console.log("Invalid credentials");
 * }
 * ```
 *
 * @security
 * - Uses timing-safe verification (constant-time comparison)
 * - Applies same HMAC-SHA256 pepper as encryption
 * - Resistant to timing attacks and side-channel analysis
 * - Returns boolean only (no additional timing information leaked)
 */
declare function verifyEncryptedPassword(password: string, hashedPassword: string, PEPPER: string): Promise<boolean>;

export { SecureBuffer as Buffer, CACHE_BUILD_DATE, CACHE_VERSION, Cache, CryptoHandler, CONFIG as DEFAULT_CACHE_CONFIG, DEFAULT_FILE_CACHE_CONFIG, DEFAULT_SENSITIVE_KEYS, EnhancedUint8Array, EntropyPool, EntropySource, EventManager, FileCache, FortifiedFunction, FortifyJS as Fortify, Hash, HashAlgorithm$2 as HashAlgorithm, HashStrength, IdGenerator, KeyDerivationAlgorithm, Keys, LogLevel, MODULE_INFO, MetadataManager, PasswordAlgorithm, PasswordManager, PasswordSecurityLevel, SecureRandom as Random, SECURE_OBJECT_VERSION, SecureArray, SecureBuffer, SIMC as SecureInMemoryCache, SecureObject, SecureString, SecurityIssueType, SecurityLevel$1 as SecurityLevel, SensitiveKeysManager, SerializationHandler, TamperEvidentLogger, TokenType, UFSMiddleware, UFSIMC as UltraFastSecureInMemoryCache, ValidationUtils, Validators, argon2Derive, asciiToString, assessRSASecurity, balloonDerive, base32ToBuffer, base58ToBuffer, base64ToBase64Url, base64ToBuffer, base64ToString, base64UrlToBase64, base64UrlToBuffer, base64UrlToString, baseToNumber, benchmarkRSAPerformance, binaryToBuffer, binaryToNumber, bufferToBase32, bufferToBase58, bufferToBase64, bufferToBase64Url, bufferToBinary, bufferToHex, bufferToOctal, bufferToString, bufferToUrlEncoded, buffersEqual, bytesToUint16, bytesToUint32, cacheHarden, calculateRSAKeySize, chunkBuffer, cleanupFileCache, clearAllCache, clearFileCache, cloneSecureObject, concatBuffers, constantTimeEqual, contexts, convertBase, createAttestation, createCacheMiddleware, createCanary, createCanaryFunction, createCanaryObject, createFortifiedFunction, createLibraryAttestation, createOptimalCache, createReadOnlySecureObject, createSecureCipheriv, createSecureDecipheriv, createSecureHMAC, createSecureHash, createSecureObject, createSecureObjectWithSensitiveKeys, createServer, createServerInstance, defaultFileCache, deleteFileCache, detectEncoding, detectInjection, encryptSecurePass, expireCache, fArray, fObject, fString, faultResistantEqual, filepath, formatBytes, FortifyJS as ftfy, func, generateAttestationKey, generateFilePath, generateKyberKeyPair, generateProtectedRSAKeyPairForData, generateRSAKeyPairForData, generateSecureIV, generateSecureIVBatch, generateSecureIVBatchForAlgorithm, generateSecureIVForAlgorithm, generateSecureUUID, generateSessionToken, getCacheStats, getEncryptionSuggestion, getFileCacheStats, getMaxDataSizeForRSAKey, getRSARecommendations, getRandomBytes, hasFileCache, hexToBuffer, hexToString, kyberDecapsulate, kyberEncapsulate, lamportGenerateKeypair, lamportSign, lamportVerify, maskedAccess, numberToBase, numberToBinary, numberToOctal, octalToBuffer, octalToNumber, padBuffer, pm, randomBuffer, randomDelay, readCache, readFileCache, removeFileCache, reverseBytes, ringLweDecrypt, ringLweEncrypt, ringLweGenerateKeypair, secureDeserialize, secureModPow, secureSerialize, secureWipe, simpleChecksum, sqlPatterns, stringToAscii, stringToBase64, stringToBase64Url, stringToBuffer, stringToHex, testRSAWithDataSize, triggerCanary, uint16ToBytes, uint32ToBytes, urlDecode, urlEncode, validateDataSizeForRSAKey, validateIV, validateRSAKeyPair, verifyAttestation, verifyEncryptedPassword, verifyHash, verifyLibraryAttestation, verifyRuntimeSecurity, writeCache, writeFileCache, xorBuffers, xssPatterns };
export type { APIKeyOptions, AttestationOptions, AttestationResult, AuditEntry, CacheBackendStrategy, CacheConfig, CacheEntry, CacheMetrics, CacheMonitoringConfig, CacheOptions, CachePerformanceConfig, CacheResilienceConfig, CacheSecurityConfig, CacheStats, CachedData, CanaryOptions, ComparisonResult, CryptoStats, DeserializationOptions, DeserializationResult, ElementMetadata, EncodingType, EntropyOptions, EventListener, ExecutionEvent, FileCacheCleanupOptions, FileCacheMetadata, FileCacheOptions, FileCacheStats, FileCacheStrategy, FlexibleSecureArray, FortifiedFunctionOptions, FunctionStats, HashBasedSignatureOptions, HashOptions, KeyDerivationOptions, KeyPair, LogEntry, LogVerificationResult, MemoryConfig, MemoryHardOptions, MemoryHardResult, MemoryUsage, MiddlewareOptions, PasswordGenerationOptions, PasswordHashOptions, PasswordMigrationResult, PasswordPolicy, PasswordStrengthAnalysis, PasswordStrengthResult, PasswordValidationResult, PasswordVerificationResult, PostQuantumDecapsulation, PostQuantumEncapsulation, PostQuantumKeyPair, PostQuantumParams, RedisConfig, RouteOptions, SearchOptions, SecureArrayEvent, SecureArrayEventListener, SecureArrayOptions, SecureArraySerializationOptions, SecureArrayStats, SecureArrayValue, SecureExecutionContext, SecureObjectData, SecureObjectEvent, SecureObjectOptions, SecureStringEvent, SecureStringEventListener, SecureStringOptions, SecureTokenOptions, SecureValue, SecurityCheck, SecurityFlags, SecurityIssue, SecurityTestResult, SecurityVerificationOptions, SecurityVerificationResult, SerializationOptions$1 as SerializationOptions, SerializationResult, ServerConfig, ServerOptions, SessionTokenOptions, SplitOptions, StringStatistics, UltraCacheOptions, UltraFastApp, UltraMemoryCacheEntry, UltraStats, ValidationResult, ValueMetadata, VerificationOptions };
