import { Server, IncomingMessage, ServerResponse } from 'http';
import { SecureCacheAdapter } from 'xypriss-security';
import { __strl__ } from 'strulink';
import * as reliant_type from 'reliant-type';
import { Readable, Writable } from 'node:stream';

declare const LOG_LEVELS: readonly ["silent", "error", "warn", "info", "debug", "verbose"];
type LogLevel$1 = (typeof LOG_LEVELS)[number];
declare const LOG_COMPONENTS: readonly ["middleware", "server", "cache", "cluster", "performance", "plugins", "security", "routes", "userApp", "typescript", "console", "other", "router", "acpes", "ipc", "memory", "lifecycle", "routing", "xems"];
type LogComponent = (typeof LOG_COMPONENTS)[number];
declare const LOG_TYPES: readonly ["startup", "warnings", "errors", "performance", "debug", "hotReload", "portSwitching", "lifecycle"];
type LogType = (typeof LOG_TYPES)[number];
/**
 * Component-specific logging configuration
 */
interface ComponentLogConfig {
    /** Enable/disable logging for this component */
    enabled?: boolean;
    /** Override log level for this component */
    level?: LogLevel$1;
    /** Component-specific type filtering */
    types?: Partial<Record<LogType, boolean>>;
    /** Custom formatter for this component */
    formatter?: (level: LogLevel$1, message: string, ...args: any[]) => string;
    /** Rate limiting for this component */
    rateLimit?: {
        /** Maximum logs per time window */
        maxLogs?: number;
        /** Time window in milliseconds */
        window?: number;
    };
    /** Pattern-based message filtering */
    suppressPatterns?: (string | RegExp)[];
}

type LoggerConfig = NonNullable<ServerOptions["logging"]>;

/**
 * Logger.ts
 * Centralized logger for FastApi.ts — structured, typed, and console-friendly.
 *
 * Output format:  {gray timestamp} {color}[COMPONENT]{/} {color}message{/}
 *
 * Color logic:
 *  - error   → bright red   (level always wins)
 *  - warn    → yellow       (level always wins)
 *  - debug   → magenta      (level always wins)
 *  - verbose → gray         (level always wins)
 *  - info / startup / perf / etc. → component identity color
 */

declare class Logger {
    private static instance;
    static getInstance(config?: LoggerConfig): Logger;
    private config;
    private buffer;
    private flushTimer?;
    private isDisposed;
    private palette;
    private compColors;
    private levelColors;
    private logQueue;
    private isProcessingQueue;
    private errorCount;
    private lastErrorTime;
    private suppressedComponents;
    constructor(config?: LoggerConfig);
    private applyColors;
    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;
    verbose(component: LogComponent, message: string, ...args: any[]): void;
    startup(component: LogComponent, message: string, ...args: any[]): void;
    success(component: LogComponent, message: string, ...args: any[]): void;
    /** @internal Bypass methods used by LogProcessor to avoid recursion */
    _internal_error(component: LogComponent, message: string, ...args: any[]): void;
    _internal_warn(component: LogComponent, message: string, ...args: any[]): void;
    _internal_info(component: LogComponent, message: string, ...args: any[]): void;
    _internal_debug(component: LogComponent, message: string, ...args: any[]): void;
    updateConfig(config: LoggerConfig): void;
    getConfig(): LoggerConfig;
    getLevel(): LogLevel$1;
    isEnabled(): boolean;
    getStats(): {
        errorCount: number;
        lastErrorTime: number;
        suppressedComponents: ("middleware" | "server" | "cache" | "cluster" | "performance" | "plugins" | "security" | "routes" | "userApp" | "typescript" | "console" | "other" | "router" | "acpes" | "ipc" | "memory" | "lifecycle" | "routing" | "xems")[];
        bufferSize: number;
        queueSize: number;
    };
    clearSuppression(): void;
    flush(): void;
    dispose(): void;
    /** Create a scoped child logger inheriting (and optionally overriding) config. */
    child(_component: LogComponent, config?: Partial<LoggerConfig>): Logger;
    private log;
    private drainQueue;
    private shouldLog;
    private shouldSuppressError;
    private writeEntry;
    /**
     * Produces a log line:
     *
     *   {gray}HH:MM:SS.mmm{/} {color}[COMPONENT]{/} {color}message{/}
     *
     * Color priority:
     *   1. Level color  — error=brightRed, warn=yellow, debug=magenta, verbose=gray
     *   2. Component color — each component has its own identity color (for info-class)
     *
     * Tag and message always share the same color so they read as one visual unit.
     */
    private formatEntry;
    /** Human-readable uppercase label for a component. */
    private componentLabel;
    private truncate;
    private readMemoryMB;
    private readProcessId;
    /** Bypass all filters — used only for logger-internal failures. */
    private emergencyLog;
    private initBuffer;
    private initErrorHandling;
    private deepMerge;
}

interface FileUploadConfig {
    /** Enable file upload handling */
    enabled?: boolean;
    /** Maximum file size in bytes */
    maxFileSize?: number;
    /** Maximum number of files per request */
    maxFiles?: number;
    /** Allowed MIME types */
    allowedMimeTypes?: string[];
    /** Allowed file extensions */
    allowedExtensions?: string[];
    /** Upload destination directory */
    destination?: string;
    /** Detailed limits configuration */
    limits?: {
        /** Max field name size in bytes */
        fieldNameSize?: number;
        /** Max field value size in bytes */
        fieldSize?: number;
        /** Max number of non-file fields */
        fields?: number;
        /** Max file size in bytes */
        fileSize?: number;
        /** Max number of file fields */
        files?: number;
        /** Max number of header key=>value pairs */
        headerPairs?: number;
    };
    /** Preserve full paths instead of just filenames */
    preservePath?: boolean;
    /** Storage type */
    storage?: "disk" | "memory" | "custom";
    /** Create parent directories if they don't exist */
    createParentPath?: boolean;
    /** Abort request on limit reached */
    abortOnLimit?: boolean;
    /** Response message when limit is reached */
    responseOnLimit?: string;
    /** Use temporary files for large uploads */
    useTempFiles?: boolean;
    /** Temporary file directory */
    tempFileDir?: string;
    /** Parse nested objects in multipart data */
    parseNested?: boolean;
    /** Use subdirectories based on field name or date */
    useSubDir?: boolean;
    /** Enable debug logging */
    debug?: boolean;
}

/**
 * @fileoverview Core type definitions for XyPriss integration
 *
 * This module contains fundamental types and utilities used throughout
 * the XyPriss integration system.
 *
 * @version 4.5.11
 * @author XyPrissJS Team
 * @since 2025-01-06
 */

/**
 * Deep partial utility type that makes all properties optional recursively.
 *
 * This utility type is used throughout the configuration system to allow
 * partial configuration objects while maintaining type safety.
 *
 * @template T - The type to make deeply partial
 *
 * @example
 * ```typescript
 * interface Config {
 *   server: {
 *     port: number;
 *     host: string;
 *   };
 * }
 *
 * type PartialConfig = DeepPartial<Config>;
 * // Result: { server?: { port?: number; host?: string; } }
 * ```
 */
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;
};
/**
 * Validation result interface for request validation operations.
 *
 * Used by validation middleware and request handlers to provide
 * structured validation feedback.
 *
 * @interface ValidationResult
 *
 * @example
 * ```typescript
 * const result: ValidationResult = {
 *   valid: false,
 *   errors: ['Email is required', 'Password too short'],
 *   data: { email: '', password: '123' }
 * };
 * ```
 */
interface ValidationResult {
    /** Whether the validation passed */
    valid: boolean;
    /** Array of validation error messages */
    errors: string[];
    /** The validated/sanitized data */
    data: any;
}
/**
 * User context information for authenticated requests.
 *
 * Contains user identity, permissions, and metadata for
 * authorization and audit purposes.
 *
 * @interface UserContext
 *
 * @example
 * ```typescript
 * const user: UserContext = {
 *   id: 'user-123',
 *   roles: ['admin', 'user'],
 *   permissions: ['read:users', 'write:posts'],
 *   metadata: { department: 'engineering', level: 'senior' }
 * };
 * ```
 */
interface UserContext {
    /** Unique user identifier */
    id: string;
    /** Array of user roles */
    roles: string[];
    /** Array of specific permissions */
    permissions: string[];
    /** Additional user metadata */
    metadata: Record<string, any>;
}
/**
 * Session data structure for user sessions.
 *
 * Contains session information including expiration and
 * custom session data.
 *
 * @interface SessionData
 *
 * @example
 * ```typescript
 * const session: SessionData = {
 *   id: 'session-abc123',
 *   userId: 'user-123',
 *   data: { theme: 'dark', language: 'en' },
 *   expires: new Date(Date.now() + 3600000) // 1 hour
 * };
 * ```
 */
interface SessionData {
    /** Unique session identifier */
    id: string;
    /** Associated user ID (optional) */
    userId?: string;
    /** Custom session data */
    data: Record<string, any>;
    /** Session expiration date */
    expires: Date;
}
/**
 * Pagination information for paginated responses.
 *
 * Used by API endpoints that return paginated data to provide
 * navigation information to clients.
 *
 * @interface PaginationInfo
 *
 * @example
 * ```typescript
 * const pagination: PaginationInfo = {
 *   page: 2,
 *   limit: 20,
 *   total: 150,
 *   pages: 8
 * };
 * ```
 */
interface PaginationInfo {
    /** Current page number (1-based) */
    page: number;
    /** Number of items per page */
    limit: number;
    /** Total number of items */
    total: number;
    /** Total number of pages */
    pages: number;
}
/**
 * Configuration for internal response manipulation.
 *
/**
 * Rules for masking or replacing fields in responses.
 *
 * @interface ResponseManipulationRule
 */
interface ResponseManipulationRule {
    /** Field name (dot notation) or RegExp pattern for matching keys */
    field?: string | RegExp;
    /** RegExp pattern for matching field values */
    valuePattern?: RegExp;
    /** Mask string (e.g., "****") or replacement value */
    replacement?: any;
    /** Number of characters to preserve (at the beginning) for string masking */
    preserve?: number;
}
/**
 * Configuration for internal response manipulation.
 *
 * Allows masking or replacing specific fields in JSON responses
 * before they are sent to the client.
 *
 * @interface ResponseManipulationConfig
 */
interface ResponseManipulationConfig {
    /** Enable response manipulation */
    enabled?: boolean;
    /** Rules for masking or replacing fields */
    rules?: ResponseManipulationRule[];
    /** Maximum recursion depth for nested objects (default: 10) */
    maxDepth?: number;
}
/**
 * Enhanced XyPriss request interface with additional utilities.
 *
 * Extends the standard XyPriss Request with caching, security,
 * performance, and validation utilities.
 *
 * @interface EnhancedRequest
 * @extends Request
 *
 * @example
 * ```typescript
 * app.get('/api/users', async (req: EnhancedRequest, res: EnhancedResponse) => {
 *   // Use enhanced features
 *   const cached = await req.cache.get('users');
 *   const encrypted = await req.security.encrypt(sensitiveData);
 *   req.performance.start();
 *
 *   // Validation
 *   const validation = req.validation.query(userQuerySchema);
 *   if (!validation.valid) {
 *     return res.error('Invalid query parameters');
 *   }
 * });
 * ```
 */
interface EnhancedRequest extends XyPrisRequest {
    /** Cache utilities for request-level caching */
    cache: {
        /** Get cached value by key */
        get: (key: string) => Promise<any>;
        /** Set cached value with optional TTL */
        set: (key: string, value: any, ttl?: number) => Promise<void>;
        /** Delete cached value */
        del: (key: string) => Promise<void>;
        /** Tag cache entries for bulk invalidation */
        tags: (tags: string[]) => Promise<void>;
    };
    /** Security utilities for encryption and authentication */
    security: {
        /** Encrypt data using configured algorithm */
        encrypt: (data: any) => Promise<string>;
        /** Decrypt data using configured algorithm */
        decrypt: (data: string) => Promise<any>;
        /** Hash data using secure algorithm */
        hash: (data: string) => string;
        /** Verify data against hash */
        verify: (data: string, hash: string) => boolean;
        /** Generate secure token */
        generateToken: () => string;
        /** Session encryption key */
        sessionKey: string;
    };
    /** Performance monitoring utilities */
    performance: {
        /** Start performance timer */
        start: () => void;
        /** End performance timer and return duration */
        end: () => number;
        /** Mark a performance point */
        mark: (name: string) => void;
        /** Measure time between marks */
        measure: (name: string, start: string, end: string) => number;
    };
    /** Request validation utilities */
    validation: {
        /** Validate request body against schema */
        body: (schema: any) => ValidationResult;
        /** Validate query parameters against schema */
        query: (schema: any) => ValidationResult;
        /** Validate route parameters against schema */
        params: (schema: any) => ValidationResult;
    };
    /** User context (available after authentication) */
    user?: UserContext;
    /** Session data (available when sessions are enabled) */
    session?: SessionData;
}
/**
 * Enhanced XyPriss response interface with additional utilities.
 *
 * Extends the standard XyPriss Response with caching, security,
 * performance, and convenience methods.
 *
 * @interface EnhancedResponse
 * @extends Response
 *
 * @example
 * ```typescript
 * app.get('/api/users', async (req: EnhancedRequest, res: EnhancedResponse) => {
 *   const users = await getUsersFromDB();
 *
 *   // Use enhanced response methods
 *   res.cache.set(3600, ['users']); // Cache for 1 hour with 'users' tag
 *   res.performance.timing('db_query', 150);
 *   res.success(users, 'Users retrieved successfully');
 * });
 * ```
 */
interface EnhancedResponse extends XyPrisResponse {
    /** Cache utilities for response caching */
    cache: {
        /** Set cache headers and TTL for response */
        set: (ttl?: number, tags?: string[]) => void;
        /** Invalidate cache entries by tags */
        invalidate: (tags: string[]) => Promise<void>;
    };
    /** Security utilities for response encryption */
    security: {
        /** Encrypt response data */
        encrypt: (data: any) => EnhancedResponse;
        /** Sign response data */
        sign: (data: any) => EnhancedResponse;
    };
    /** Performance utilities for response metrics */
    performance: {
        /** Record timing metric */
        timing: (name: string, value: number) => void;
        /** Record custom metric */
        metric: (name: string, value: number) => void;
    };
    /** Send successful response with optional message */
    success: (data?: any, message?: string) => void;
    /** Send error response with message and status code */
    error: (error: string | Error, code?: number) => void;
    /** Send paginated response with pagination info */
    paginated: (data: any[], pagination: PaginationInfo) => void;
}
/**
 * Route handler function type with enhanced request/response.
 *
 * @template T - Return type of the handler
 *
 * @example
 * ```typescript
 * const getUserHandler: RouteHandler = async (req, res, next) => {
 *   try {
 *     const user = await getUserById(req.params.id);
 *     res.success(user);
 *   } catch (error) {
 *     next(error);
 *   }
 * };
 * ```
 */
type RouteHandler$1 = (req: EnhancedRequest, res: EnhancedResponse, next: NextFunction) => Promise<any> | any;
/**
 * Middleware function type with enhanced request/response.
 *
 * @example
 * ```typescript
 * const authMiddleware: MiddlewareFunction = async (req, res, next) => {
 *   const token = req.headers.authorization;
 *   if (!token) {
 *     return res.error('Authorization required', 401);
 *   }
 *
 *   try {
 *     req.user = await verifyToken(token);
 *     next();
 *   } catch (error) {
 *     res.error('Invalid token', 401);
 *   }
 * };
 * ```
 */
type MiddlewareFunction$2 = (req: EnhancedRequest, res: EnhancedResponse, next: NextFunction) => Promise<void> | void;

/**
 * @fileoverview Cache-related type definitions for XyPriss integration
 *
 * This module contains all cache-related types including configuration,
 * strategies, metrics, and backend implementations.
 *
 * @version 4.5.11
 * @author XyPrissJS Team
 * @since 2025-01-06
 */

/**
 * Cache backend strategy types.
 *
 * Defines the available cache backend implementations:
 * - memory: In-memory caching (fastest, not persistent)
 * - redis: Redis-based caching (persistent, distributed)
 * - hybrid: Combination of memory and Redis
 * - distributed: Multi-node distributed caching
 *
 * @example
 * ```typescript
 * const strategy: CacheBackendStrategy = 'hybrid';
 * ```
 */
type CacheBackendStrategy = "memory" | "redis" | "hybrid" | "distributed";
/**
 * Main cache configuration interface.
 *
 * Comprehensive configuration for the caching system including
 * backend selection, performance tuning, security, and monitoring.
 *
 * @interface CacheConfig
 *
 * @example
 * ```typescript
 * const cacheConfig: CacheConfig = {
 *   type: 'hybrid',
 *   ttl: 3600,
 *   maxSize: 1024 * 1024 * 100, // 100MB
 *   compression: true,
 *   encryption: true,
 *   strategies: [
 *     {
 *       name: 'api-cache',
 *       condition: (req) => req.path.startsWith('/api/'),
 *       ttl: 300,
 *       tags: ['api']
 *     }
 *   ]
 * };
 * ```
 */
interface CacheConfig {
    /** Cache backend type */
    type?: CacheBackendStrategy;
    /** Redis configuration (when using Redis backend) */
    redis?: RedisConfig;
    /** Memory cache configuration */
    memory?: MemoryConfig;
    /** Default TTL in seconds */
    ttl?: number;
    /** Maximum cache size in bytes */
    maxSize?: number;
    /** Maximum number of cache entries */
    maxEntries?: number;
    /** Enable compression for cached data */
    compression?: boolean;
    /** Enable encryption for cached data */
    encryption?: boolean;
    /** Serialization format for cached data */
    serialization?: "json" | "msgpack" | "protobuf";
    /** Cache strategies for different scenarios */
    strategies?: CacheStrategy[];
    /** Enable singleton pattern for cache instances */
    singleton?: boolean;
    /** Performance optimization settings */
    performance?: CachePerformanceConfig;
    /** Security settings for cache */
    security?: CacheSecurityConfig;
    /** Monitoring and metrics configuration */
    monitoring?: CacheMonitoringConfig;
    /** Resilience and fault tolerance settings */
    resilience?: CacheResilienceConfig;
}
/**
 * Redis cache configuration.
 *
 * Comprehensive Redis configuration including clustering,
 * connection pooling, and high availability options.
 *
 * @interface RedisConfig
 *
 * @example
 * ```typescript
 * const redisConfig: RedisConfig = {
 *   host: 'localhost',
 *   port: 6379,
 *   password: 'secure-password',
 *   cluster: true,
 *   nodes: [
 *     { host: 'redis-1', port: 6379 },
 *     { host: 'redis-2', port: 6379 }
 *   ],
 *   pool: {
 *     min: 5,
 *     max: 20,
 *     acquireTimeoutMillis: 5000
 *   }
 * };
 * ```
 */
interface RedisConfig {
    /** Redis server hostname */
    host?: string;
    /** Redis server port */
    port?: number;
    /** Redis authentication password */
    password?: string;
    /** Redis database number */
    db?: number;
    /** Enable Redis cluster mode */
    cluster?: boolean;
    /** Cluster nodes configuration */
    nodes?: Array<{
        host: string;
        port: number;
    }>;
    /** Sharded Redis configuration with weights */
    shards?: Array<{
        host: string;
        port: number;
        weight?: number;
    }>;
    /** Redis connection options */
    options?: {
        /** Retry delay on failover in milliseconds */
        retryDelayOnFailover?: number;
        /** Maximum retries per request */
        maxRetriesPerRequest?: number;
        /** Enable lazy connection */
        lazyConnect?: boolean;
    };
    /** Connection pool configuration */
    pool?: {
        /** Minimum connections in pool */
        min?: number;
        /** Maximum connections in pool */
        max?: number;
        /** Timeout for acquiring connection in milliseconds */
        acquireTimeoutMillis?: number;
        /** Idle timeout for connections in milliseconds */
        idleTimeoutMillis?: number;
    };
    /** Redis Sentinel configuration for high availability */
    sentinel?: {
        /** Enable Sentinel mode */
        enabled?: boolean;
        /** Master names to monitor */
        masters?: string[];
        /** Sentinel server configurations */
        sentinels?: Array<{
            host: string;
            port: number;
        }>;
    };
}
/**
 * Memory cache configuration.
 *
 * Configuration for in-memory caching including eviction
 * policies and memory management.
 *
 * @interface MemoryConfig
 *
 * @example
 * ```typescript
 * const memoryConfig: MemoryConfig = {
 *   maxSize: 1024 * 1024 * 50, // 50MB
 *   algorithm: 'lru',
 *   evictionPolicy: 'lru',
 *   checkPeriod: 60000, // 1 minute
 *   preallocation: true
 * };
 * ```
 */
interface MemoryConfig {
    /** Maximum memory size in bytes */
    maxSize?: number;
    /** Heap size allocation in bytes (alias for maxSize) */
    heapSize?: number;
    /** Cleanup interval in milliseconds (alias for checkPeriod) */
    cleanupInterval?: number;
    /** Cache algorithm */
    algorithm?: "lru" | "lfu" | "fifo";
    /** Eviction policy when cache is full */
    evictionPolicy?: "lru" | "lfu" | "fifo" | "ttl";
    /** Check period for expired entries in milliseconds */
    checkPeriod?: number;
    /** Enable memory preallocation for better performance */
    preallocation?: boolean;
}
/**
 * Cache performance optimization configuration.
 *
 * Settings for optimizing cache performance including
 * batching, compression, and connection management.
 *
 * @interface CachePerformanceConfig
 *
 * @example
 * ```typescript
 * const perfConfig: CachePerformanceConfig = {
 *   batchSize: 100,
 *   compressionThreshold: 1024,
 *   hotDataThreshold: 0.8,
 *   prefetchEnabled: true,
 *   asyncWrite: true,
 *   pipeline: true
 * };
 * ```
 */
interface CachePerformanceConfig {
    /** Batch size for bulk operations */
    batchSize?: number;
    /** Minimum size threshold for compression in bytes */
    compressionThreshold?: number;
    /** Threshold for identifying hot data (0-1) */
    hotDataThreshold?: number;
    /** Enable prefetching of related data */
    prefetchEnabled?: boolean;
    /** Enable asynchronous write operations */
    asyncWrite?: boolean;
    /** Enable Redis pipelining for better performance */
    pipeline?: boolean;
    /** Enable connection pooling */
    connectionPooling?: boolean;
}
/**
 * Cache security configuration.
 *
 * Security settings for cache including encryption,
 * access monitoring, and audit logging.
 *
 * @interface CacheSecurityConfig
 *
 * @example
 * ```typescript
 * const securityConfig: CacheSecurityConfig = {
 *   encryption: true,
 *   keyRotation: true,
 *   accessMonitoring: true,
 *   sanitization: true,
 *   auditLogging: true
 * };
 * ```
 */
interface CacheSecurityConfig {
    /** Enable data encryption */
    encryption?: boolean;
    /** Enable automatic key rotation */
    keyRotation?: boolean;
    /** Enable access monitoring and logging */
    accessMonitoring?: boolean;
    /** Enable data sanitization */
    sanitization?: boolean;
    /** Enable audit logging */
    auditLogging?: boolean;
}
/**
 * Cache monitoring configuration.
 *
 * Settings for monitoring cache performance and health
 * including metrics collection and alerting.
 *
 * @interface CacheMonitoringConfig
 *
 * @example
 * ```typescript
 * const monitoringConfig: CacheMonitoringConfig = {
 *   enabled: true,
 *   metricsInterval: 30000, // 30 seconds
 *   alertThresholds: {
 *     memoryUsage: 0.85,
 *     hitRate: 0.7,
 *     errorRate: 0.05,
 *     latency: 100
 *   },
 *   detailed: true
 * };
 * ```
 */
interface CacheMonitoringConfig {
    /** Enable monitoring */
    enabled?: boolean;
    /** Metrics collection interval in milliseconds */
    metricsInterval?: number;
    /** Alert thresholds for various metrics */
    alertThresholds?: {
        /** Memory usage threshold (0-1) */
        memoryUsage?: number;
        /** Cache hit rate threshold (0-1) */
        hitRate?: number;
        /** Error rate threshold (0-1) */
        errorRate?: number;
        /** Latency threshold in milliseconds */
        latency?: number;
    };
    /** Enable detailed metrics collection */
    detailed?: boolean;
}
/**
 * Cache resilience configuration.
 *
 * Settings for fault tolerance including retry logic,
 * circuit breakers, and fallback mechanisms.
 *
 * @interface CacheResilienceConfig
 *
 * @example
 * ```typescript
 * const resilienceConfig: CacheResilienceConfig = {
 *   retryAttempts: 3,
 *   retryDelay: 1000,
 *   circuitBreaker: true,
 *   fallback: true,
 *   healthCheck: true
 * };
 * ```
 */
interface CacheResilienceConfig {
    /** Number of retry attempts for failed operations */
    retryAttempts?: number;
    /** Delay between retry attempts in milliseconds */
    retryDelay?: number;
    /** Enable circuit breaker pattern */
    circuitBreaker?: boolean;
    /** Enable fallback to alternative cache */
    fallback?: boolean;
    /** Enable health check monitoring */
    healthCheck?: boolean;
}
/**
 * Cache strategy configuration.
 *
 * Defines conditional caching strategies based on
 * request characteristics and business logic.
 *
 * @interface CacheStrategy
 *
 * @example
 * ```typescript
 * const apiStrategy: CacheStrategy = {
 *   name: 'api-endpoints',
 *   condition: (req) => req.path.startsWith('/api/') && req.method === 'GET',
 *   ttl: 300, // 5 minutes
 *   tags: ['api', 'public']
 * };
 * ```
 */
interface CacheStrategy {
    /** Strategy name for identification */
    name: string;
    /** Condition function to determine if strategy applies */
    condition: (req: XyPrisRequest) => boolean;
    /** TTL for this strategy in seconds */
    ttl: number;
    /** Tags for cache invalidation */
    tags?: string[];
}

/**
 * Browser-Only Protection Configuration
 *
 * Blocks non-browser requests (cURL, Postman, scripts) while allowing legitimate browser access.
 * Useful for APIs that should only be accessed through web browsers.
 *
 * @example Enable with defaults:
 * ```typescript
 * browserOnly: true
 * ```
 *
 * @example Custom configuration:
 * ```typescript
 * browserOnly: {
 *   requireSecFetch: true,
 *   blockAutomationTools: true,
 *   allowOriginRequests: true,
 *   errorMessage: "Browser access required"
 * }
 * ```
 */
interface BrowserOnlyConfig {
    /** Enable browser-only protection (default: true when config provided) */
    enable?: boolean;
    /** Block requests without Sec-Fetch headers */
    requireSecFetch?: boolean;
    /** Block requests with curl/wget user agents */
    blockAutomationTools?: boolean;
    /** Require complex Accept header */
    requireComplexAccept?: boolean;
    /** Allow requests with Origin header (CORS) */
    allowOriginRequests?: boolean;
    /** Custom error message */
    errorMessage?: string;
    /** HTTP status code for blocked requests */
    statusCode?: number;
    /** Custom validation function */
    customValidator?: (req: any) => boolean;
    /** Enable debug logging */
    debug?: boolean;
}
/**
 * Terminal-Only Protection Configuration
 *
 * Blocks browser requests while allowing terminal/API tools.
 * Perfect for API-only endpoints or development tools.
 *
 * @example Enable with defaults:
 * ```typescript
 * terminalOnly: true
 * ```
 *
 * @example Custom configuration:
 * ```typescript
 * terminalOnly: {
 *   blockSecFetch: true,
 *   allowedTools: ["curl", "wget"],
 *   blockBrowserIndicators: true,
 *   debug: true
 * }
 * ```
 */
interface TerminalOnlyConfig {
    /** Enable terminal-only protection (default: true when config provided) */
    enable?: boolean;
    /** Block requests with Sec-Fetch headers (browsers) */
    blockSecFetch?: boolean;
    /** Allow specific automation tools (whitelist approach) */
    allowedTools?: string[];
    /** Block requests with complex browser headers */
    blockBrowserIndicators?: boolean;
    /** Require simple Accept header */
    requireSimpleAccept?: boolean;
    /** Custom error message */
    errorMessage?: string;
    /** HTTP status code for blocked requests */
    statusCode?: number;
    /** Custom validation function */
    customValidator?: (req: any) => boolean;
    /** Enable debug logging */
    debug?: boolean;
}

/**
 * @fileoverview Security-related type definitions for XyPriss integration
 *
 * This module contains all security-related types including authentication,
 * authorization, encryption, and security policies.
 *
 * @version 4.5.11
 * @author XyPrissJS Team
 * @since 2025-01-06
 */
/**
 * Security configuration levels.
 *
 * Predefined security levels that automatically configure
 * appropriate security measures:
 * - basic: Essential security features
 * - enhanced: Additional security layers
 * - maximum: All security features enabled
 */
type SecurityLevel = "basic" | "enhanced" | "maximum";
/**
 * CSRF Protection Configuration
 *
 * Protects against Cross-Site Request Forgery attacks by requiring tokens.
 * Can be enabled/disabled or configured with custom options.
 *
 * @example Enable with defaults:
 * ```typescript
 * csrf: true
 * ```
 *
 * @example Disable:
 * ```typescript
 * csrf: false
 * ```
 *
 * @example Custom configuration:
 * ```typescript
 * csrf: {
 *   cookieName: '__Host-csrf-token',
 *   cookieOptions: {
 *     httpOnly: true,
 *     sameSite: 'strict',
 *     secure: __sys__.__env__.get("NODE_ENV") === 'production'
 *   }
 * }
 * ```
 */
interface CSRFConfig {
    /**
     * Skip CSRF validation for specific HTTP methods.
     * @default ['GET', 'HEAD', 'OPTIONS', 'TRACE']
     */
    ignoredMethods?: string[];
    /** Enable CSRF protection */
    enabled?: boolean;
    /**
     * Secret used to sign CSRF tokens.
     * Required when CSRF protection is enabled.
     *
     * @example
     * csrf: { secret: __sys__.__env__.get("CSRF_SECRET", "MY_DEFAULT_SECRET") }
     */
    secret?: string;
    /** CSRF token cookie name */
    cookieName?: string;
    /** CSRF token cookie options */
    cookieOptions?: {
        httpOnly?: boolean;
        sameSite?: boolean | "lax" | "strict" | "none";
        secure?: boolean;
    };
}
/**
 * XyRS - XyPriss Request Signature Configuration
 *
 * Validates request signatures using the XP-Request-Sig header.
 * Provides API authentication by requiring a secret signature on all requests.
 *
 * @example Enable with secret:
 * ```typescript
 * requestSignature: {
 *   secret: "my-secret-api-key"
 * }
 * ```
 *
 * @example Custom configuration:
 * ```typescript
 * requestSignature: {
 *   secret: "my-secret-api-key",
 *   errorMessage: "API key required",
 *   statusCode: 403,
 *   caseSensitive: false
 * }
 * ```
 */
interface RequestSignatureConfig {
    /** Custom header name for the signature (default: "XP-Request-Sig") */
    headerName?: string;
    /** The secret value that must match the header */
    secret: string;
    /** Custom error message for blocked requests */
    errorMessage?: string;
    /** HTTP status code for blocked requests */
    statusCode?: number;
    /** Enable debug logging */
    debug?: boolean;
    /** Case-sensitive comparison */
    caseSensitive?: boolean;
    /** Trim whitespace from header value */
    trimValue?: boolean;
    /** Maximum allowed header length to prevent DoS (default: 512) */
    maxHeaderLength?: number;
    /** Rate limiting: max failed attempts before temporary block (default: 5) */
    maxFailedAttempts?: number;
    /** Rate limiting: block duration in milliseconds (default: 15 minutes) */
    blockDuration?: number;
    /** Disable rate limiting entirely (default: false) */
    disableRateLimiting?: boolean;
    /** Scale factor for rate limiting thresholds (default: 1.0) */
    rateLimitScaleFactor?: number;
    /** Minimum secret length requirement (default: 32) */
    minSecretLength?: number;
    /** Enable timing attack protection (default: true) */
    timingSafeComparison?: boolean;
    /** Reject requests with suspicious patterns (default: true) */
    rejectSuspiciousPatterns?: boolean;
}
/**
 * Helmet Security Headers Configuration
 *
 * Sets various HTTP headers to help protect against common attacks.
 * Can be enabled/disabled or configured with custom header options.
 *
 * @example Enable with defaults:
 * ```typescript
 * helmet: true
 * ```
 *
 * @example Custom CSP:
 * ```typescript
 * helmet: {
 *   contentSecurityPolicy: {
 *     directives: {
 *       defaultSrc: ["'self'"],
 *       scriptSrc: ["'self'", "'unsafe-inline'"]
 *     }
 *   },
 *   hsts: { maxAge: 31536000 }
 * }
 * ```
 */
interface HelmetConfig {
    /** Enable or disable Helmet headers */
    enabled?: boolean;
    /** Content Security Policy configuration */
    contentSecurityPolicy?: {
        /** CSP directives - flexible configuration allowing any CSP directive */
        directives?: Record<string, string | string[]>;
    } | boolean;
    /** HTTP Strict Transport Security configuration */
    hsts?: {
        maxAge: number;
        includeSubDomains?: boolean;
        preload?: boolean;
    };
    /** Cross-Origin Embedder Policy */
    crossOriginEmbedderPolicy?: boolean | {
        policy: "require-corp" | "credentialless";
    };
    /** Cross-Origin Opener Policy */
    crossOriginOpenerPolicy?: boolean | {
        policy: "same-origin" | "same-origin-allow-popups" | "unsafe-none";
    };
    /** Cross-Origin Resource Policy */
    crossOriginResourcePolicy?: boolean | {
        policy: "same-origin" | "same-site" | "cross-origin";
    };
    /** DNS Prefetch Control */
    dnsPrefetchControl?: boolean | {
        allow: boolean;
    };
    /** Frameguard (X-Frame-Options) */
    frameguard?: boolean | {
        action: "deny" | "sameorigin" | "allow-from";
        domain?: string;
    };
    /** Hide Powered By header */
    hidePoweredBy?: boolean | {
        setTo?: string;
    };
    /** IE No Open */
    ieNoOpen?: boolean;
    /** No Sniff */
    noSniff?: boolean;
    /** Origin Agent Cluster */
    originAgentCluster?: boolean;
    /** Permitted Cross Domain Policies */
    permittedCrossDomainPolicies?: boolean | {
        permittedPolicies: "none" | "master-only" | "by-content-type" | "all";
    };
    /** Referrer Policy */
    referrerPolicy?: boolean | {
        policy: string | string[];
    };
    /** XSS Filter */
    xssFilter?: boolean;
}
/**
 * XSS Protection Configuration
 *
 * Protects against Cross-Site Scripting attacks by sanitizing input.
 * Can be enabled/disabled or configured with custom sanitization rules.
 *
 * @example Enable with defaults:
 * ```typescript
 * xss: true
 * ```
 *
 * @example Custom configuration:
 * ```typescript
 * xss: {
 *   blockOnDetection: true,
 *   customPatterns: [/custom-pattern/g],
 *   whitelist: { a: ['href', 'title'] }
 * }
 * ```
 */
interface XSSConfig {
    /** Enable XSS protection */
    enabled?: boolean;
    /** Block requests on XSS detection */
    blockOnDetection?: boolean;
    /** Custom XSS patterns to detect */
    customPatterns?: RegExp[];
    /** Whitelist of allowed tags and attributes */
    whitelist?: {
        [tag: string]: string[];
    };
    /** Custom error message for blocked requests */
    message?: string;
    /** HTTP status code for blocked requests */
    statusCode?: number;
}
/**
 * SQL Injection Protection Configuration
 *
 * Detects and prevents SQL injection attacks in request data.
 * Can be enabled/disabled or configured with custom detection rules.
 *
 * @example Enable with defaults:
 * ```typescript
 * sqlInjection: true
 * ```
 *
 * @example Custom configuration:
 * ```typescript
 * sqlInjection: {
 *   blockOnDetection: true,
 *   riskThreshold: 'medium',
 *   customPatterns: [/custom-sql-pattern/g]
 * }
 * ```
 */
interface SQLInjectionConfig {
    /** Enable SQL injection protection */
    enabled?: boolean;
    /** Block requests on SQL injection detection */
    blockOnDetection?: boolean;
    /** Risk threshold for SQL injection detection */
    riskThreshold?: "low" | "medium" | "high";
    /** Custom SQL injection patterns to detect */
    customPatterns?: RegExp[];
    /** Enable contextual analysis to reduce false positives */
    contextualAnalysis?: boolean;
    /** Strict mode - more aggressive detection */
    strictMode?: boolean;
    /** Log detected attempts */
    logAttempts?: boolean;
    /** False positive threshold (0-1) */
    falsePositiveThreshold?: number;
    /** Maximum allowed length for input strings before triggering 'Excessive length' detection */
    maxLength?: number;
    /** Custom error message for blocked requests */
    message?: string;
    /** HTTP status code for blocked requests */
    statusCode?: number;
}
/**
 * Path Traversal Protection Configuration
 *
 * Detects and prevents directory traversal attacks while allowing legitimate file paths.
 *
 * @example Enable with defaults:
 * ```typescript
 * pathTraversal: true
 * ```
 *
 * @example Custom configuration:
 * ```typescript
 * pathTraversal: {
 *   blockOnDetection: true,
 *   allowedPaths: ['/uploads/', '/public/'],
 *   allowedExtensions: ['.jpg', '.png', '.pdf'],
 *   maxDepth: 3
 * }
 * ```
 */
interface PathTraversalConfig {
    /** Enable path traversal protection */
    enabled?: boolean;
    /** Block requests on path traversal detection */
    blockOnDetection?: boolean;
    /** Allowed base paths */
    allowedPaths?: string[];
    /** Allowed file extensions */
    allowedExtensions?: string[];
    /** Maximum allowed path depth */
    maxDepth?: number;
    /** Strict mode */
    strictMode?: boolean;
    /** Log detected attempts */
    logAttempts?: boolean;
    /** False positive threshold (0-1) */
    falsePositiveThreshold?: number;
    /** Custom error message for blocked requests */
    message?: string;
    /** HTTP status code for blocked requests */
    statusCode?: number;
}
/**
 * Command Injection Protection Configuration
 *
 * Detects and prevents OS command injection attacks with context awareness.
 *
 * @example Enable with defaults:
 * ```typescript
 * commandInjection: true
 * ```
 *
 * @example Custom configuration:
 * ```typescript
 * commandInjection: {
 *   blockOnDetection: true,
 *   contextualAnalysis: true,
 *   allowedCommands: ['git', 'npm']
 * }
 * ```
 */
interface CommandInjectionConfig {
    /** Enable command injection protection */
    enabled?: boolean;
    /** Block requests on command injection detection */
    blockOnDetection?: boolean;
    /** Enable contextual analysis */
    contextualAnalysis?: boolean;
    /** Allowed commands (whitelist) */
    allowedCommands?: string[];
    /** Strict mode */
    strictMode?: boolean;
    /** Log detected attempts */
    logAttempts?: boolean;
    /** False positive threshold (0-1) */
    falsePositiveThreshold?: number;
    /** Custom error message for blocked requests */
    message?: string;
    /** HTTP status code for blocked requests */
    statusCode?: number;
}
/**
 * XXE (XML External Entity) Protection Configuration
 *
 * Prevents XXE attacks in XML parsing.
 *
 * @example Enable with defaults:
 * ```typescript
 * xxe: true
 * ```
 *
 * @example Custom configuration:
 * ```typescript
 * xxe: {
 *   blockOnDetection: true,
 *   allowDTD: false,
 *   allowExternalEntities: false
 * }
 * ```
 */
interface XXEConfig {
    /** Enable or disable XXE protection */
    enabled?: boolean;
    /** Block requests on XXE detection */
    blockOnDetection?: boolean;
    /** Allow DTD declarations */
    allowDTD?: boolean;
    /** Allow external entities */
    allowExternalEntities?: boolean;
    /** Maximum entity expansions */
    maxEntityExpansions?: number;
    /** Strict mode */
    strictMode?: boolean;
    /** Log detected attempts */
    logAttempts?: boolean;
    /** Custom error message for blocked requests */
    message?: string;
    /** HTTP status code for blocked requests */
    statusCode?: number;
}
/**
 * LDAP Injection Protection Configuration
 *
 * Detects and prevents LDAP injection attacks.
 *
 * @example Enable with defaults:
 * ```typescript
 * ldapInjection: true
 * ```
 *
 * @example Custom configuration:
 * ```typescript
 * ldapInjection: {
 *   blockOnDetection: true,
 *   strictMode: true
 * }
 * ```
 */
interface LDAPInjectionConfig {
    /** Enable LDAP injection protection */
    enabled?: boolean;
    /** Block requests on LDAP injection detection */
    blockOnDetection?: boolean;
    /** Strict mode */
    strictMode?: boolean;
    /** Log detected attempts */
    logAttempts?: boolean;
    /** False positive threshold (0-1) */
    falsePositiveThreshold?: number;
}
/**
 * Compression Configuration
 *
 * Response compression to reduce bandwidth and improve performance.
 * Can be enabled/disabled or configured with custom compression settings.
 *
 * @example Enable with defaults:
 * ```typescript
 * compression: true
 * ```
 *
 * @example Custom compression:
 * ```typescript
 * compression: {
 *   level: 6, // compression level (1-9)
 *   threshold: 1024, // minimum response size to compress
 *   filter: (req, res) => {
 *     // custom filter logic
 *     return /json|text|javascript|css/.test(res.get('Content-Type'));
 *   }
 * }
 * ```
 */
interface CompressionConfig {
    /** Compression level (1-9) */
    level?: number;
    /** Minimum response size to compress (in bytes) */
    threshold?: number;
    /** Custom filter function for compression */
    filter?: (req: any, res: any) => boolean;
}
/**
 * HTTP Parameter Pollution Protection Configuration
 *
 * Prevents HTTP Parameter Pollution attacks by handling duplicate parameters.
 * Can be enabled/disabled or configured with custom parameter handling.
 *
 * @example Enable with defaults:
 * ```typescript
 * hpp: true
 * ```
 *
 * @example Custom configuration:
 * ```typescript
 * hpp: {
 *   whitelist: ['tags', 'categories'], // allow arrays for these params
 *   checkQuery: true,
 *   checkBody: true
 * }
 * ```
 */
interface HPPConfig {
    /** Enable or disable HTTP Parameter Pollution protection */
    enabled?: boolean;
    /** Whitelist of allowed parameters for arrays */
    whitelist?: string[];
    /** Check query parameters for duplicates */
    checkQuery?: boolean;
    /** Check body parameters for duplicates */
    checkBody?: boolean;
}
/**
 * Slow Down Configuration
 *
 * Progressive delays for rate limiting to prevent abuse.
 * Can be enabled/disabled or configured with custom delay patterns.
 *
 * @example Enable with defaults:
 * ```typescript
 * slowDown: true
 * ```
 *
 * @example Custom slow down:
 * ```typescript
 * slowDown: {
 *   windowMs: 15 * 60 * 1000, // 15 minutes
 *   delayAfter: 100, // delay after 100 requests
 *   delayMs: (used, req) => {
 *     const delayAfter = req.slowDown?.limit || 100;
 *     return (used - delayAfter) * 500; // 500ms per request over limit
 *   }
 * }
 * ```
 */
interface SlowDownConfig {
    /** Enable or disable slow down */
    enabled?: boolean;
    /** Time window for slow down (in milliseconds) */
    windowMs?: number;
    /** Number of requests before delay starts */
    delayAfter?: number;
    /** Custom delay function */
    delayMs?: (used: number, req: any) => number;
}
/**
 * Route pattern matching configuration for security rules
 */
interface RoutePattern {
    /** Route path pattern (supports wildcards like /api/*, exact paths like /login, or regex) */
    path: string | RegExp;
    /** HTTP methods to apply this rule to (if not specified, applies to all methods) */
    methods?: string[];
}
/**
 * Honeypot Tarpit Configuration
 * Allows extending the built-in bot-trap patterns with application-specific signatures.
 */
interface HoneypotTarpitConfig {
    /** Enable/Disable the honeypot tarpit (default: true) */
    enabled?: boolean;
    /**
     * High-confidence exact paths to trap (e.g. "/backup.zip").
     * Matching is case-insensitive.
     */
    exact?: string[];
    /**
     * Path prefixes whose entire subtree should be considered traps (e.g. "/.ssh/").
     */
    prefixes?: string[];
    /**
     * File extensions that indicate scanner probes (e.g. ".pem", ".key").
     */
    suffixes?: string[];
    /**
     * Discrete path segments that indicate probes (e.g. "actuator", "config").
     */
    segments?: string[];
}
type globMRConf = string | RegExp | RoutePattern;
/**
 * Security module route configuration
 * Allows selective application of security modules to specific routes
 */
interface SecurityModuleRouteConfig {
    /** Routes to exclude from this security module */
    excludeRoutes?: globMRConf[];
    /** Routes to include for this security module (if specified, only these routes will be protected) */
    includeRoutes?: globMRConf[];
}
type MaliciousPatternOptions = Parameters<typeof __strl__.scanUrl>[1];
/**
 * Malicious URL Scanner Configuration
 *
 * Scans URLs for malicious patterns like XSS, Path Traversal, and Code Injection
 * using the StruLink engine.
 */
interface MaliciousUrlScannerConfig {
    /** Enable the URL scanner */
    enabled?: boolean;
    /**
     * Mode of operation:
     * - "block": Immediately reject malicious URLs with 403 Forbidden
     * - "log": Allow the request but log a security warning
     */
    mode?: "block" | "log";
    /** Custom options passed directly to [StruLink](https://github.com/Nehonix-Team/strulink)'s `scanUrl` method */
    options?: MaliciousPatternOptions;
}
interface SecurityConfig {
    rmXBranding?: boolean;
    /**
     * Strategic route bypass configuration.
     * Routes defined here will bypass content-based security detectors (XSS, SQLi, Path Traversal, etc.).
     * This is recommended for routes handling rich text or complex payloads where false positives are likely.
     * Access control policies (CORS, Device restrictions, Signatures) remain active.
     */
    _ignore?: (string | RegExp)[];
    /**
     * Absolute route bypass configuration.
     * Routes defined here will bypass the ENTIRE security middleware stack, including device restrictions,
     * request signatures, and content detectors. Use with extreme caution.
     */
    _ignoreAll?: (string | RegExp)[];
    /** Security level preset */
    level?: SecurityLevel;
    /**
     * Route-based security configuration
     * Allows you to selectively apply security modules to specific routes
     *
     * @example
     * ```typescript
     * routeConfig: {
     *   xss: {
     *     excludeRoutes: ['/api/safe-content/*']
     *   },
     *   pathTraversal: {
     *     excludeRoutes: ['/api/templates/*', { path: '/api/content/*', methods: ['POST'] }]
     *   },
     *   sqlInjection: {
     *     includeRoutes: ['/api/db/*', '/api/query/*']
     *   }
     * }
     * ```
     */
    routeConfig?: {
        xss?: SecurityModuleRouteConfig;
        sqlInjection?: SecurityModuleRouteConfig;
        pathTraversal?: SecurityModuleRouteConfig;
        commandInjection?: SecurityModuleRouteConfig;
        xxe?: SecurityModuleRouteConfig;
        ldapInjection?: SecurityModuleRouteConfig;
    };
    /**
     * CSRF Protection Configuration
     *
     * Protects against Cross-Site Request Forgery attacks by requiring tokens.
     * Can be enabled/disabled or configured with custom options.
     *
     * @example Enable with defaults:
     * ```typescript
     * csrf: true
     * ```
     *
     * @example Disable:
     * ```typescript
     * csrf: false
     * ```
     *
     * @example Custom configuration:
     * ```typescript
     * csrf: {
     *   cookieName: '__Host-csrf-token',
     *   cookieOptions: {
     *     httpOnly: true,
     *     sameSite: 'strict',
     *     secure: __sys__.__env__.get("NODE_ENV") === 'production'
     *   }
     * }
     * ```
     */
    csrf?: boolean | CSRFConfig;
    /**
     * Helmet Security Headers Configuration
     *
     * Sets various HTTP headers to help protect against common attacks.
     * Can be enabled/disabled or configured with custom header options.
     *
     * @example Enable with defaults:
     * ```typescript
     * helmet: true
     * ```
     *
     * @example Custom CSP:
     * ```typescript
     * helmet: {
     *   contentSecurityPolicy: {
     *     directives: {
     *       defaultSrc: ["'self'"],
     *       scriptSrc: ["'self'", "'unsafe-inline'"]
     *     }
     *   },
     *   hsts: { maxAge: 31536000 }
     * }
     * ```
     */
    helmet?: boolean | HelmetConfig;
    /**
     * XSS Protection Configuration
     *
     * Protects against Cross-Site Scripting attacks by sanitizing input.
     * Can be enabled/disabled or configured with custom sanitization rules.
     *
     * @example Enable with defaults:
     * ```typescript
     * xss: true
     * ```
     *
     * @example Custom configuration:
     * ```typescript
     * xss: {
     *   blockOnDetection: true,
     *   customPatterns: [/custom-pattern/g],
     *   whitelist: { a: ['href', 'title'] }
     * }
     * ```
     */
    xss?: boolean | XSSConfig;
    /**
     * SQL Injection Protection Configuration
     *
     * Detects and prevents SQL injection attacks in request data.
     * Can be enabled/disabled or configured with custom detection rules.
     *
     * @example Enable with defaults:
     * ```typescript
     * sqlInjection: true
     * ```
     *
     * @example Custom configuration:
     * ```typescript
     * sqlInjection: {
     *   blockOnDetection: true,
     *   riskThreshold: 'medium',
     *   customPatterns: [/custom-sql-pattern/g]
     * }
     * ```
     */
    sqlInjection?: boolean | SQLInjectionConfig;
    /**
     * Path Traversal Protection Configuration
     *
     * Detects and prevents directory traversal attacks while allowing legitimate file paths.
     * Can be enabled/disabled or configured with custom detection rules.
     *
     * @example Enable with defaults:
     * ```typescript
     * pathTraversal: true
     * ```
     *
     * @example Custom configuration:
     * ```typescript
     * pathTraversal: {
     *   blockOnDetection: true,
     *   allowedPaths: ['/uploads/', '/public/'],
     *   allowedExtensions: ['.jpg', '.png', '.pdf'],
     *   maxDepth: 3
     * }
     * ```
     */
    pathTraversal?: boolean | PathTraversalConfig;
    /**
     * Command Injection Protection Configuration
     *
     * Detects and prevents OS command injection attacks with context awareness.
     * Can be enabled/disabled or configured with custom detection rules.
     *
     * @example Enable with defaults:
     * ```typescript
     * commandInjection: true
     * ```
     *
     * @example Custom configuration:
     * ```typescript
     * commandInjection: {
     *   blockOnDetection: true,
     *   contextualAnalysis: true,
     *   allowedCommands: ['git', 'npm']
     * }
     * ```
     */
    commandInjection?: boolean | CommandInjectionConfig;
    /**
     * XXE (XML External Entity) Protection Configuration
     *
     * Prevents XXE attacks in XML parsing.
     * Can be enabled/disabled or configured with custom detection rules.
     *
     * @example Enable with defaults:
     * ```typescript
     * xxe: true
     * ```
     *
     * @example Custom configuration:
     * ```typescript
     * xxe: {
     *   blockOnDetection: true,
     *   allowDTD: false,
     *   allowExternalEntities: false
     * }
     * ```
     */
    xxe?: boolean | XXEConfig;
    /**
     * LDAP Injection Protection Configuration
     *
     * Detects and prevents LDAP injection attacks.
     * Can be enabled/disabled or configured with custom detection rules.
     *
     * @example Enable with defaults:
     * ```typescript
     * ldapInjection: true
     * ```
     *
     * @example Custom configuration:
     * ```typescript
     * ldapInjection: {
     *   blockOnDetection: true,
     *   strictMode: true
     * }
     * ```
     */
    ldapInjection?: boolean | LDAPInjectionConfig;
    /**
     * Honeypot Tarpit Configuration (Bot & Scanner Neutralization)
     *
     * Instantly blocks vulnerability scanners by performing an ultra-fast O(1)
     * lookup on common malicious payload signatures (e.g., `/.env`, `/.git`).
     * Prevents wasted CPU cycles from regex ReDoS and framework routing.
     * By default, this is implicitly **TRUE**.
     *
     * @example Disable honeypot tarpit (Not recommended)
     * ```typescript
     * honeypotTarpit: false
     * ```
     *
     * @example Custom honeypot traps:
     * ```typescript
     * honeypotTarpit: {
     *   enabled: true,
     *   exact: ["/my-secret-file", "/old-admin"],
     *   prefixes: ["/wp-"],
     *   suffixes: [".bak", ".sql"],
     *   segments: ["phpmyadmin", "config"]
     * }
     * ```
     */
    honeypotTarpit?: boolean | HoneypotTarpitConfig;
    /**
     * Rate Limiting Configuration
     *
     * General rate limiting to prevent abuse and control request frequency.
     * Can be enabled/disabled or configured with custom rate limiting rules.
     *
     * @example Enable with defaults:
     * ```typescript
     * rateLimit: true
     * ```
     *
     * @example Custom rate limiting:
     * ```typescript
     * rateLimit: {
     *   windowMs: 15 * 60 * 1000, // 15 minutes
     *   max: 100, // limit each IP to 100 requests per windowMs
     *   message: 'Too many requests, please try again later.',
     *   standardHeaders: true
     * }
     * ```
     */
    rateLimit?: boolean | RateLimitConfig;
    /**
     * CORS Configuration
     *
     * Cross-Origin Resource Sharing settings for API access control.
     * Can be enabled/disabled or configured with custom CORS policies.
     *
     * @example Enable with defaults:
     * ```typescript
     * cors: true
     * ```
     *
     * @example Custom CORS policy:
     * ```typescript
     * cors: {
     *   origin: ['https://myapp.com', 'https://admin.myapp.com'],
     *   methods: ['GET', 'POST', 'PUT', 'DELETE'],
     *   allowedHeaders: ['Content-Type', 'Authorization'],
     *   credentials: true,
     *   maxAge: 86400
     * }
     * ```
     */
    cors?: boolean | CORSConfig;
    /**
     * Compression Configuration
     *
     * Response compression to reduce bandwidth and improve performance.
     * Can be enabled/disabled or configured with custom compression settings.
     *
     * @example Enable with defaults:
     * ```typescript
     * compression: true
     * ```
     *
     * @example Custom compression:
     * ```typescript
     * compression: {
     *   level: 6, // compression level (1-9)
     *   threshold: 1024, // minimum response size to compress
     *   filter: (req, res) => {
     *     // custom filter logic
     *     return /json|text|javascript|css/.test(res.get('Content-Type'));
     *   }
     * }
     * ```
     */
    compression?: boolean | CompressionConfig;
    /**
     * HTTP Parameter Pollution Protection Configuration
     *
     * Prevents HTTP Parameter Pollution attacks by handling duplicate parameters.
     * Can be enabled/disabled or configured with custom parameter handling.
     *
     * @example Enable with defaults:
     * ```typescript
     * hpp: true
     * ```
     *
     * @example Custom configuration:
     * ```typescript
     * hpp: {
     *   whitelist: ['tags', 'categories'], // allow arrays for these params
     *   checkQuery: true,
     *   checkBody: true
     * }
     * ```
     */
    hpp?: boolean | HPPConfig;
    /**
     * @deprecated Morgan is not supported in XyPriss. This field has no effect and
     * will be removed in a future version.
     *
     * Using morgan in a XyPriss application may expose your application to undocumented
     * internal behaviors, telemetry risks, and integration failures with the XHSC engine.
     *
     * Use the Xyphra plugin for secure, native request logging:
     * @see https://xypriss.nehonix.com/docs/plugins/official/xyphra
     *
     * @example Correct approach:
     * ```typescript
     * plugins: {
     *   register: [
     *     XyphraPlugin({ anonymizeIp: true })
     *   ]
     * }
     * ```
     */
    morgan?: never;
    /**
     * Slow Down Configuration
     *
     * Progressive delays for rate limiting to prevent abuse.
     * Can be enabled/disabled or configured with custom delay patterns.
     *
     * @example Enable with defaults:
     * ```typescript
     * slowDown: true
     * ```
     *
     * @example Custom slow down:
     * ```typescript
     * slowDown: {
     *   windowMs: 15 * 60 * 1000, // 15 minutes
     *   delayAfter: 100, // delay after 100 requests
     *   delayMs: (used, req) => {
     *     const delayAfter = req.slowDown?.limit || 100;
     *     return (used - delayAfter) * 500; // 500ms per request over limit
     *   }
     * }
     * ```
     */
    slowDown?: boolean | SlowDownConfig;
    /**
     * Browser-Only Protection Configuration
     *
     * Blocks non-browser requests (cURL, Postman, scripts) while allowing legitimate browser access.
     * Useful for APIs that should only be accessed through web browsers.
     *
     * @example Enable with defaults:
     * ```typescript
     * browserOnly: true
     * ```
     *
     * @example Custom configuration:
     * ```typescript
     * browserOnly: {
     *   requireSecFetch: true,
     *   blockAutomationTools: true,
     *   allowOriginRequests: true,
     *   errorMessage: "Browser access required"
     * }
     * ```
     */
    browserOnly?: boolean | BrowserOnlyConfig;
    /**
     * Terminal-Only Protection Configuration
     *
     * Blocks browser requests while allowing terminal/API tools.
     * Perfect for API-only endpoints or development tools.
     *
     * @example Enable with defaults:
     * ```typescript
     * terminalOnly: true
     * ```
     *
     * @example Custom configuration:
     * ```typescript
     * terminalOnly: {
     *   blockSecFetch: true,
     *   allowedTools: ["curl", "wget"],
     *   blockBrowserIndicators: true,
     *   debug: true
     * }
     * ```
     */
    terminalOnly?: boolean | TerminalOnlyConfig;
    /**
     * XyRS - XyPriss Request Signature Configuration
     *
     * Validates request signatures using the XP-Request-Sig header.
     * Provides API authentication by requiring a secret signature on all requests.
     *
     * @example Enable with secret:
     * ```typescript
     * requestSignature: {
     *   secret: "my-secret-api-key"
     * }
     * ```
     *
     * @example Custom configuration:
     * ```typescript
     * requestSignature: {
     *   secret: "my-secret-api-key",
     *   errorMessage: "API key required",
     *   statusCode: 403,
     *   caseSensitive: false
     * }
     * ```
     */
    requestSignature?: boolean | RequestSignatureConfig;
    /**
     * Malicious URL Scanner Configuration
     */
    maliciousUrlScanner?: boolean | MaliciousUrlScannerConfig;
}
/**
 * CORS (Cross-Origin Resource Sharing) configuration interface.
 *
 * Configuration for CORS policies including allowed origins,
 * methods, and headers.
 *
 * By default, all headers are allowed to be developer-friendly.
 * You can restrict headers by specifying the allowedHeaders array.
 *
 * @interface CORSConfig
 *
 * @example
 * ```typescript
 * // Allow all origins (default - developer-friendly)
 * const corsConfig: CORSConfig = {
 *   origin: '*',
 *   methods: ['GET', 'POST', 'PUT', 'DELETE'],
 *   credentials: true
 * };
 *
 * // Restrict specific origins (production)
 * const restrictiveCorsConfig: CORSConfig = {
 *   origin: ['https://example.com', 'https://app.example.com'],
 *   methods: ['GET', 'POST', 'PUT', 'DELETE'],
 *   allowedHeaders: ['Content-Type', 'Authorization'],
 *   credentials: true
 * };
 *
 * // Advanced patterns with RegExp (powerful and flexible)
 * const advancedCorsConfig: CORSConfig = {
 *   origin: [
 *     /^localhost:\d+$/,           // localhost:3000, localhost:8080, etc.
 *     /^127\.0\.0\.1:\d+$/,        // 127.0.0.1:3000, etc.
 *     /^::1:\d+$/,                 // IPv6 localhost
 *     /\.test\.com$/,              // *.test.com
 *     'https://production.com'     // Exact match
 *   ],
 *   methods: ['GET', 'POST'],
 *   credentials: true
 * };
 * ```
 */
interface CORSConfig {
    /** Enable or disable CORS */
    enabled?: boolean;
    /** Allowed origins - can be string, RegExp, array of mixed types, or boolean */
    origin?: string | RegExp | (string | RegExp)[] | boolean;
    /** Allowed HTTP methods */
    methods?: string[];
    /**
     * Allowed headers - if not specified, all headers are allowed by default.
     * Specify this array to restrict which headers are allowed.
     */
    allowedHeaders?: string[];
    /** Allow credentials in CORS requests */
    credentials?: boolean;
}
/**
 * Rate limiting configuration interface.
 *
 * Configuration for rate limiting including time windows,
 * request limits, and custom messages.
 *
 * @interface RateLimitConfig
 *
 * @example
 * ```typescript
 * // String message
 * const rateLimitConfig: RateLimitConfig = {
 *   windowMs: 900000, // 15 minutes
 *   max: 100, // 100 requests per window
 *   message: 'Too many requests, please try again later',
 *   standardHeaders: true,
 *   legacyHeaders: false
 * };
 *
 * // Object message (more flexible)
 * const rateLimitConfig: RateLimitConfig = {
 *   windowMs: 900000,
 *   max: 100,
 *   message: {
 *     error: 'Rate limit exceeded',
 *     message: 'Too many requests, please try again later',
 *     retryAfter: 900
 *   },
 *   standardHeaders: true,
 *   legacyHeaders: false
 * };
 * ```
 */
interface RateLimitConfig {
    /** Enable or disable rate limiting */
    enabled?: boolean;
    /** Time window in milliseconds */
    windowMs?: number;
    /** Maximum requests per window */
    max?: number;
    /** Message to send when limit is exceeded (string or object) */
    message?: string | {
        error?: string;
        message?: string;
        retryAfter?: number;
        [key: string]: any;
    };
    /** Include standard rate limit headers */
    standardHeaders?: boolean;
    /** Include legacy rate limit headers */
    legacyHeaders?: boolean;
    /**
     * Custom function to determine if a request should be skipped by the rate limiter.
     *
     * @param req The incoming request object
     * @param res The server response object
     * @returns {boolean} True if the request should bypass rate limiting, false otherwise.
     *
     * @note IMPORTANT: If this function is provided, the `excludePaths` setting is
     * ignored by default (it behaves as if `excludePaths` was empty) to prevent
     * conflicting exclusion rules.
     *
     * @example
     * ```typescript
     * skip: (req) => req.path.startsWith('/public/') || req.ip === '127.0.0.1'
     * ```
     */
    skip?: (req: any, res: any) => boolean;
    /**
     * List of paths or patterns to exclude from rate limiting.
     *
     * @type {(string | RegExp)[]}
     *
     * - Strings starting with '/' are matched exactly or as a prefix.
     * - Regular expressions are tested against the `req.path`.
     *
     * @note By default, XyPriss excludes common endpoints like `/health`, `/ping`,
     * and static asset folders (`/static/`, `/assets/`).
     *
     * @warning This property is ignored if a `skip` function is defined.
     *
     * @example
     * ```typescript
     * excludePaths: ['/api/v1/status', /^\/internal\//]
     * ```
     */
    excludePaths?: (string | RegExp)[];
}
/**
 * Route-specific security configuration interface.
 *
 * Security settings that can be applied to individual
 * routes or route groups.
 *
 * @interface RouteSecurityConfig
 *
 * @example
 * ```typescript
 * const routeSecurityConfig: RouteSecurityConfig = {
 *   auth: true,
 *   roles: ['admin', 'moderator'],
 *   permissions: ['read:users', 'write:posts'],
 *   encryption: true,
 *   sanitization: true,
 *   validation: true
 * };
 * ```
 */
interface RouteSecurityConfig {
    /** Require authentication */
    auth?: boolean;
    /** Required user roles */
    roles?: string[];
    /** Required permissions */
    permissions?: string[];
    /** Enable response encryption */
    encryption?: boolean;
    /** Enable input sanitization */
    sanitization?: boolean;
    /** Enable input validation */
    validation?: boolean;
}

/**
 * @fileoverview Performance-related type definitions for XyPriss integration
 *
 * This module contains all performance-related types including monitoring,
 * optimization, metrics, and configuration.
 *
 * @version 4.5.11
 * @author XyPrissJS Team
 * @since 2025-01-06
 */
/**
 * Performance configuration interface.
 *
 * Comprehensive configuration for performance monitoring,
 * optimization, and metrics collection.
 *
 * @interface PerformanceConfig
 *
 * @example
 * ```typescript
 * const perfConfig: PerformanceConfig = {
 *   enabled: true,
 *   metrics: ['response_time', 'memory_usage', 'cpu_usage'],
 *   interval: 30000, // 30 seconds
 *   alerts: [
 *     {
 *       metric: 'response_time',
 *       threshold: 1000, // 1 second
 *       action: 'log',
 *       cooldown: 300000 // 5 minutes
 *     }
 *   ],
 *   dashboard: true,
 *   export: {
 *     custom: (metrics) => {
 *       console.log('Custom metrics export:', metrics);
 *     }
 *   }
 * };
 * ```
 */
interface PerformanceConfig {
    /** Enable performance monitoring */
    enabled?: boolean;
    /** Metrics to collect */
    metrics?: string[];
    /** Collection interval in milliseconds */
    interval?: number;
    /** Alert configurations */
    alerts?: AlertConfig[];
    /** Enable performance dashboard */
    dashboard?: boolean;
    /** Export configuration */
    export?: {
        /** Custom export function */
        custom?: (metrics: any) => void;
    };
}
/**
 * Alert configuration interface.
 *
 * Configuration for performance alerts including thresholds,
 * actions, and cooldown periods.
 *
 * @interface AlertConfig
 *
 * @example
 * ```typescript
 * const alertConfig: AlertConfig = {
 *   metric: 'memory_usage',
 *   threshold: 0.85, // 85%
 *   action: 'webhook',
 *   target: 'https://alerts.example.com/webhook',
 *   cooldown: 600000 // 10 minutes
 * };
 * ```
 */
interface AlertConfig {
    /** Metric name to monitor */
    metric: string;
    /** Threshold value that triggers alert */
    threshold: number;
    /** Action to take when alert triggers */
    action: "log" | "email" | "webhook" | "custom";
    /** Target for the action (email, webhook URL, etc.) */
    target?: string;
    /** Cooldown period in milliseconds */
    cooldown?: number;
}

/**
 * @fileoverview Routing-related type definitions for XyPriss integration
 *
 * This module contains all routing-related types including route configuration,
 * caching, security, validation, and optimization.
 *
 * @version 4.5.11
 * @author XyPrissJS Team
 * @since 2025-01-06
 */

/**
 * HTTP methods supported by the routing system.
 */
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "ALL";
/**
 * Route configuration interface.
 *
 * Comprehensive configuration for individual routes including
 * handlers, middleware, caching, security, and validation.
 *
 * @interface RouteConfig
 *
 * @example
 * ```typescript
 * const routeConfig: RouteConfig = {
 *   path: '/api/users/:id',
 *   method: 'GET',
 *   handler: async (req, res, next) => {
 *     const user = await getUserById(req.params.id);
 *     res.success(user);
 *   },
 *   middleware: [authMiddleware, validationMiddleware],
 *   cache: {
 *     enabled: true,
 *     ttl: 300,
 *     key: (req) => `user:${req.params.id}`,
 *     tags: ['users']
 *   },
 *   security: {
 *     auth: true,
 *     roles: ['user', 'admin'],
 *     sanitization: true
 *   },
 *   rateLimit: {
 *     max: 100,
 *     windowMs: 900000
 *   },
 *   validation: {
 *     params: { id: 'string' },
 *     required: ['id']
 *   }
 * };
 * ```
 */
interface RouteConfig {
    /** Route path pattern */
    path: string;
    /** HTTP method */
    method?: HttpMethod;
    /** Route handler function */
    handler: RouteHandler$1;
    /** Middleware functions to apply */
    middleware?: MiddlewareFunction$2[];
    /** Route-specific cache configuration */
    cache?: RouteCacheConfig;
    /** Route-specific security configuration */
    security?: RouteSecurityConfig;
    /** Route-specific rate limiting */
    rateLimit?: RouteRateLimitConfig;
    /** Request validation configuration */
    validation?: RouteValidationConfig;
}
/**
 * Route cache configuration interface.
 *
 * Configuration for route-specific caching including
 * TTL, cache keys, tags, and invalidation rules.
 *
 * @interface RouteCacheConfig
 *
 * @example
 * ```typescript
 * const routeCacheConfig: RouteCacheConfig = {
 *   enabled: true,
 *   ttl: 300, // 5 minutes
 *   key: (req) => `api:users:${req.params.id}:${req.query.include}`,
 *   tags: ['users', 'api'],
 *   invalidateOn: ['user:updated', 'user:deleted'],
 *   compression: true
 * };
 * ```
 */
interface RouteCacheConfig {
    /** Enable caching for this route */
    enabled?: boolean;
    /** Cache TTL in seconds */
    ttl?: number;
    /** Cache key generator */
    key?: string | ((req: XyPrisRequest) => string);
    /** Cache tags for invalidation */
    tags?: string[];
    /** Events that should invalidate this cache */
    invalidateOn?: string[];
    /** Enable compression for cached responses */
    compression?: boolean;
}
/**
 * Route rate limiting configuration interface.
 *
 * Configuration for route-specific rate limiting extending
 * the base rate limit configuration.
 *
 * @interface RouteRateLimitConfig
 *
 * @example
 * ```typescript
 * const routeRateLimitConfig: RouteRateLimitConfig = {
 *   windowMs: 900000, // 15 minutes
 *   max: 50, // 50 requests per window
 *   message: 'Too many requests to this endpoint',
 *   keyGenerator: (req) => `${req.ip}:${req.path}`,
 *   skip: (req) => req.user?.role === 'admin'
 * };
 * ```
 */
interface RouteRateLimitConfig {
    /** Time window in milliseconds */
    windowMs?: number;
    /** Maximum requests per window */
    max?: number;
    /** Message when limit is exceeded */
    message?: string;
    /** Include standard rate limit headers */
    standardHeaders?: boolean;
    /** Include legacy rate limit headers */
    legacyHeaders?: boolean;
    /** Custom key generator for rate limiting */
    keyGenerator?: (req: XyPrisRequest) => string;
    /** Function to skip rate limiting for certain requests */
    skip?: (req: XyPrisRequest) => boolean;
}
/**
 * Route validation configuration interface.
 *
 * Configuration for request validation including
 * body, query, and parameter validation.
 *
 * @interface RouteValidationConfig
 *
 * @example
 * ```typescript
 * const routeValidationConfig: RouteValidationConfig = {
 *   body: {
 *     name: { type: 'string', minLength: 2, maxLength: 50 },
 *     email: { type: 'email' },
 *     age: { type: 'number', min: 18, max: 120 }
 *   },
 *   query: {
 *     page: { type: 'number', min: 1, default: 1 },
 *     limit: { type: 'number', min: 1, max: 100, default: 20 }
 *   },
 *   params: {
 *     id: { type: 'string', pattern: /^[0-9a-f]{24}$/ }
 *   },
 *   required: ['name', 'email']
 * };
 * ```
 */
interface RouteValidationConfig {
    /** Request body validation schema */
    body?: any;
    /** Query parameters validation schema */
    query?: any;
    /** Route parameters validation schema */
    params?: any;
    /** Required fields */
    required?: string[];
}
/**
 * Route options interface for enhanced route methods.
 *
 * Options that can be passed to enhanced route methods
 * like getWithCache, postWithCache, etc.
 *
 * @interface RouteOptions
 *
 * @example
 * ```typescript
 * const routeOptions: RouteOptions = {
 *   cache: {
 *     enabled: true,
 *     ttl: 600,
 *     strategy: 'hybrid',
 *     tags: ['products']
 *   },
 *   security: {
 *     auth: true,
 *     roles: ['user'],
 *     encryption: false,
 *     sanitization: true
 *   },
 *   performance: {
 *     compression: true,
 *     timeout: 30000
 *   }
 * };
 * ```
 */
interface RouteOptions {
    /** Cache configuration */
    cache?: {
        /** Enable caching */
        enabled?: boolean;
        /** Cache TTL in seconds */
        ttl?: number;
        /** Cache key generator */
        key?: string | ((req: XyPrisRequest) => string);
        /** Cache tags */
        tags?: string[];
        /** Cache invalidation events */
        invalidateOn?: string[];
        /** Cache strategy */
        strategy?: "memory" | "redis" | "hybrid";
    };
    /** Security configuration */
    security?: {
        /** Require authentication */
        auth?: boolean;
        /** Required user roles */
        roles?: string[];
        /** Enable response encryption */
        encryption?: boolean;
        /** Enable input sanitization */
        sanitization?: boolean;
        /** Custom security headers */
        headers?: Record<string, string>;
    };
    /** Performance configuration */
    performance?: {
        /** Enable response compression */
        compression?: boolean;
        /** Request timeout in milliseconds */
        timeout?: number;
    };
    /** Direct compression setting (for backward compatibility) */
    compression?: {
        /** Enable compression */
        enabled?: boolean;
    };
}

/**
 * **Native System Runner**
 *
 * This class serves as the core bridge between the Node.js runtime and the
 * high-performance system core. It manages process spawning, argument
 * serialization, and bidirectional streaming.
 */
declare class XyPrissRunner {
    private root;
    private binaryPath;
    constructor(root: string);
    getRoot(): string;
    getBinaryPath(): string;
    /**
     * Strategic discovery of the XyPriss System binary.
     * Prioritizes the high-performance Go implementation (XHSC-GO).
     */
    private discoverBinary;
    /**
     * Executes a command synchronously and returns the parsed JSON result.
     * Standardizes all responses into a Promise-like data structure.
     */
    runSync<T = any>(module: string, action: string, args?: string[], options?: any): T;
    /**
     * Executes a command asynchronously and returns the parsed JSON result.
     */
    runAsync<T = any>(module: string, action: string, args?: string[], options?: any): Promise<T>;
    /**
     * Run a module action and return the stdout as a Readable stream
     */
    runStream(module: string, action: string, args?: string[], options?: any): Readable;
    /**
     * Run a module action and return the stdin as a Writable stream
     */
    runWritableStream(module: string, action: string, args?: string[], options?: any): Writable;
}

/**
 * **Base API Class**
 *
 * Serves as the foundational layer for all XyPriss domain-specific APIs.
 * It encapsulates the `XyPrissRunner` instance, ensuring that all subclasses
 * have unified access to the underlying XHSC bridge for high-performance system operations.
 */
declare class BaseApi {
    protected runner: XyPrissRunner;
    /**
     * Initializes the Base API with a shared runner instance.
     * @param runner - The XyPrissRunner used to invoke native XHSC binaries.
     */
    constructor(runner: XyPrissRunner);
}
/**
 * **Professional Path Manipulation API**
 *
 * The `PathApi` class provides a comprehensive suite of robust, platform-independent
 * utilities for working with file and directory paths. By bridging directly to
 * the XHSC native binary, it ensures rigorous adherence to filesystem standards
 * across Windows, macOS, and Linux environments.
 *
 * **Key Benefits:**
 * - **Cross-Platform Consistency:** Eliminates separator issues (`/` vs `\`).
 * - **Security:** Prevents path traversal vulnerabilities via strict normalization.
 * - **Reliability:** Handles edge cases like trailing slashes and empty segments correctly.
 *
 * @class PathApi
 * @extends BaseApi
 */
declare class PathApi extends BaseApi {
    /**
     * **Resolve to Absolute Path**
     *
     * Resolves a sequence of path segments into an absolute path. The resulting path
     * is normalized, meaning all `..` (parent) and `.` (current) references are resolved.
     *
     * This method is critical for generating safe, unambiguous file paths relative to
     * the project root or the current working directory.
     *
     * @param {...string[]} paths - A sequence of path segments to resolve.
     * @returns {string} The resulting absolute path string.
     *
     * @example
     * // Resolving a configuration file relative to the project root
     * const configPath = __sys__.path.resolve("config", "settings.json");
     * console.log(configPath);
     * // Output (Linux): "/home/user/project/config/settings.json"
     * // Output (Windows): "C:\Users\user\project\config\settings.json"
     *
     * @example
     * // Handling parent directory navigation
     * const rootPath = __sys__.path.resolve("src", "utils", "../..");
     * // Output: "/home/user/project" (Back to root)
     */
    resolve: (...paths: string[]) => string;
    /**
     * **Join Path Segments**
     *
     * Joins all given path segments together using the platform-specific separator as a delimiter,
     * then normalizes the resulting path. This is the preferred way to construct paths
     * to ensure validity across different operating systems.
     *
     * @param {...string[]} paths - A sequence of path segments to join.
     * @returns {string} The constructed path string.
     *
     * @example
     * // Constructing a path for a log file
     * const logPath = __sys__.path.join("var", "logs", "app.log");
     * // Output (Linux): "var/logs/app.log"
     * // Output (Windows): "var\logs\app.log"
     */
    join: (...paths: string[]) => string;
    /**
     * **Get Directory Name**
     *
     * Returns the directory name of a `path`. Typically used to get the parent folder
     * of a file. It behavior follows the standard Unix `dirname` command.
     *
     * @param {string} p - The path to parse.
     * @returns {string} The directory portion of the path.
     *
     * @example
     * // Extracting the parent directory
     * const parentDir = __sys__.path.dirname("/usr/local/bin/node");
     * console.log(parentDir); // -> "/usr/local/bin"
     */
    dirname: (p: string) => string;
    /**
     * **Get Base Name**
     *
     * Returns the last portion of a `path`. This is commonly used to extract the
     * filename from a full path. An optional suffix can be provided to remove
     * the file extension effectively.
     *
     * @param {string} p - The path to evaluate.
     * @param {string} [suffix] - An optional suffix to remove (e.g., ".txt").
     * @returns {string} The base name (filename) of the path.
     *
     * @example
     * // Getting a filename including extension
     * const file = __sys__.path.basename("/src/models/user.ts");
     * console.log(file); // -> "user.ts"
     *
     * @example
     * // Getting a filename without extension
     * const name = __sys__.path.basename("/src/models/user.ts", ".ts");
     * console.log(name); // -> "user"
     */
    basename: (p: string, suffix?: string) => string;
    /**
     * **Get File Extension**
     *
     * Returns the extension of the path, including the leading dot (`.`).
     * The extension is determined from the last portion of the path. If there
     * is no `.` in the last portion, or if the first character is `.`, exact
     * behavior mirrors standard library definitions (returning empty string or the dotfile name).
     *
     * @param {string} p - The path to evaluate.
     * @returns {string} The extension of the file (e.g., ".ts", ".json").
     *
     * @example
     * // checking file type
     * const ext = __sys__.path.extname("data.json");
     * if (ext === ".json") {
     *   console.log("It's a JSON file!");
     * }
     */
    extname: (p: string) => string;
    /**
     * **Calculate Relative Path**
     *
     * Solves the relative path from `from` to `to`.
     * This is essential when you need to generate import paths or link two files
     * relative to each other within the filesystem.
     *
     * @param {string} from - The source path (start point).
     * @param {string} to - The destination path.
     * @returns {string} The relative path string.
     *
     * @example
     * // Finding relationship between two directories
     * const relative = __sys__.path.relative("/project/src/views", "/project/src/components");
     * console.log(relative); // -> "../components"
     */
    relative: (from: string, to: string) => string;
    /**
     * **Normalize Path**
     *
     * Normalizes a given path string, resolving `..` and `.` segments.
     * It also collapses multiple sequential separators (e.g., `//` -> `/`)
     * and ensures the path is in its simplest standard form.
     *
     * @param {string} p - The path to normalize.
     * @returns {string} The clean, normalized path.
     *
     * @example
     * // Cleaning up a messy path
     * const clean = __sys__.path.normalize("/users//john/./docs/../images");
     * console.log(clean); // -> "/users/john/images"
     */
    normalize: (p: string) => string;
    /**
     * **Check Child Path Relationship**
     *
     * Determines if a given `child` path is strictly contained within a `parent` directory.
     * This is a critical security utility for verifying that file operations remain
     * within authorized boundaries.
     *
     * @param {string} parent - The expected parent directory.
     * @param {string} child - The path to check.
     * @returns {boolean} True if child is inside parent.
     */
    isChild: (parent: string, child: string) => boolean;
    /**
     * **Secure Path Join**
     *
     * Joins path segments and ensures the result is strictly within the `base` path.
     * If the resulting path attempts to escape via traversal (e.g., `../`), it
     * throws a security error or returns a safe path.
     *
     * @param {string} base - The root/base directory.
     * @param {...string[]} segments - The segments to join.
     * @returns {string} The joined, safe path.
     */
    secureJoin: (base: string, ...segments: string[]) => string;
    /**
     * **Get Comprehensive Path Metadata**
     *
     * Returns a structured object containing directory, base name, extension,
     * filename without extension, and absolute status - all in a single high-speed call.
     *
     * @param {string} p - The path to evaluate.
     * @returns {object} Metadata object: { dir, base, ext, name, isAbsolute }
     */
    metadata: (p: string) => {
        dir: string;
        base: string;
        ext: string;
        name: string;
        isAbsolute: boolean;
    };
    /**
     * **Convert to Namespaced Path**
     *
     * Converts the path to a platform-specific namespaced path (e.g., UNC on Windows).
     * This is essential for handling extremely long paths or network shares natively.
     *
     * @param {string} p - The path to convert.
     * @returns {string} The namespaced path.
     */
    toNamespacedPath: (p: string) => string;
    /**
     * **Normalize Separators**
     *
     * Standardizes all path separators (`/` or `\`) to the current operating system's
     * primary separator format.
     *
     * @param {string} p - The path to handle.
     * @returns {string} The path with uniform separators.
     */
    normalizeSeparators: (p: string) => string;
    /**
     * **Identify Common Base Directory**
     *
     * Analyzes multiple paths and returns the deepest common directory shared by all.
     *
     * @param {...string[]} paths - Multiple paths to analyze.
     * @returns {string} The shared parent directory.
     */
    commonBase: (...paths: string[]) => string;
    /**
     * **Check if Path is Absolute**
     *
     * Determines if the given path is an absolute path. This is platform-aware,
     * correctly handling Windows drive letters and Unix root slashes.
     *
     * @param {string} p - The path to check.
     * @returns {boolean} True if the path is absolute, false otherwise.
     */
    isAbsolute: (p: string) => boolean;
    /**
     * **Smart Path Correction**
     *
     * Attempts to fix path inconsistencies, such as doubled segments or redundant separators.
     * Prioritizes the high-performance XHSC implementation.
     *
     * @param p - Path to correct.
     * @param tentative - Maximum number of correction attempts.
     */
    correct(path: string, options?: {
        tentative?: number;
        verify?: boolean;
    }): string;
    /**
     * **Get System Temp Directory**
     */
    tempDir: () => string;
    /**
     * **User-Scoped Temp Directory**
     *
     * Resolves and ensures a unique, ephemeral temporary directory scoped
     * to the current user session under the XyPriss shared temp root
     * (`<os.tmpdir>/nehonix.xypriss.data/xuser/<hex4>`).
     *
     * Each access generates a fresh random sub-path — suited for
     * short-lived scratch space that must not collide across concurrent
     * processes or requests.
     *
     * @returns {string} Absolute path to the isolated user temp directory.
     *
     * @example
     * const scratch = __sys__.path.tmpUserDir;
     * __sys__.fs.writeFile(scratch + "/output.json", data);
     */
    get tmpUserDir(): string;
    /**
     * **Check Existence**
     */
    exist: (p: string) => boolean;
    /**
     * **Check Existence**
     * @deprecated use exist instead
     */
    exists: (p: string) => boolean;
    /**
     * **Check if Directory**
     */
    isDir: (p: string) => boolean;
    /**
     * **Check if File**
     */
    isFile: (p: string) => boolean;
    /**
     * **Check if Symlink**
     */
    isSymlink: (p: string) => boolean;
    /**
     * **Check if Empty**
     */
    isEmpty: (p: string) => boolean;
}

/**
 * **System Information Types**
 *
 * Standardized interfaces for the XyPriss System API.
 * Maps directly to the underlying native core structures.
 */
interface SystemInfo {
    hostname: string;
    os_name: string;
    os_version: string;
    os_edition: string;
    kernel_version: string;
    architecture: string;
    cpu_count: number;
    cpu_brand: string;
    cpu_vendor: string;
    cpu_frequency: number;
    total_memory: number;
    used_memory: number;
    available_memory: number;
    total_swap: number;
    used_swap: number;
    uptime: number;
    boot_time: number;
    load_average: {
        one: number;
        five: number;
        fifteen: number;
    };
}
interface CpuInfo {
    name: string;
    vendor_id: string;
    brand: string;
    frequency: number;
    usage: number;
    core_count: number;
}
interface CpuUsage {
    overall: number;
    per_core: number[];
    timestamp: number;
}
interface MemoryInfo {
    /** Total physical memory in bytes */
    total: number;
    /** available physical memory in bytes */
    available: number;
    /** Used physical memory in bytes */
    used: number;
    /** Free physical memory in bytes */
    free: number;
    /** Memory usage percentage (0-100) */
    usage_percent: number;
    /** Total swap memory in bytes */
    swap_total: number;
    /** Used swap memory in bytes */
    swap_used: number;
    /** Free swap memory in bytes */
    swap_free: number;
    /** Swap usage percentage (0-100) */
    swap_percent: number;
}
/**
 * **System Hardware**
 *
 * A consolidated, high-level view of the system's current hardware state.
 * Combines static host information with real-time memory metrics,
 * eliminating redundant fields for a cleaner API surface.
 */
interface SystemHardware extends MemoryInfo {
    /** Hostname of the operating system */
    hostname: string;
    /** Operating System Name (e.g., "Linux", "Windows_NT") */
    os_name: string;
    /** OS Release Version */
    os_version: string;
    /** Detailed OS Edition (e.g., "Ubuntu 22.04 LTS") */
    os_edition: string;
    /** Kernel Version */
    kernel_version: string;
    /** System Architecture (renamed from architecture) */
    arch: string;
    /** Number of logical CPU cores */
    cpu_count: number;
    /** CPU Brand String */
    cpu_brand: string;
    /** CPU Vendor ID */
    cpu_vendor: string;
    /** Base CPU Frequency in MHz */
    cpu_frequency: number;
    /** System Uptime in seconds */
    uptime: number;
    /** Boot Time (Unix Timestamp) */
    boot_time: number;
    /** System Load Averages (1, 5, 15 minutes) */
    load_average: {
        one: number;
        five: number;
        fifteen: number;
    };
}
interface DiskInfo {
    name: string;
    mount_point: string;
    file_system: string;
    total_space: number;
    available_space: number;
    used_space: number;
    usage_percent: number;
    is_removable: boolean;
    disk_type: string;
}
interface NetworkInterface {
    name: string;
    received: number;
    transmitted: number;
    packets_received: number;
    packets_transmitted: number;
    errors_received: number;
    errors_transmitted: number;
    mac_address: string;
    ip_addresses: string[];
}
interface NetworkStats {
    total_received: number;
    total_transmitted: number;
    download_speed: number;
    upload_speed: number;
    interfaces: NetworkInterface[];
}
interface ProcessInfo {
    pid: number;
    name: string;
    exe?: string;
    cmd: string[];
    cpu_usage: number;
    memory: number;
    virtual_memory: number;
    status: string;
    start_time: number;
    run_time: number;
    parent_pid?: number;
    user_id?: string;
    disk_read: number;
    disk_write: number;
}
interface ProcessStats {
    total_processes: number;
    running: number;
    sleeping: number;
    stopped: number;
    zombie: number;
}
interface PortInfo {
    protocol: string;
    local_address: string;
    local_port: number;
    remote_address: string;
    remote_port: number;
    state: string;
    pid?: number;
}
interface BatteryInfo {
    state: "Charging" | "Discharging" | "Full" | "Empty" | "Unknown";
    percentage: number;
    time_to_full?: number;
    time_to_empty?: number;
    power_consumption: number;
    is_present: boolean;
    technology: string;
    vendor: string;
    model: string;
    serial: string;
}
interface PathCheck {
    exists: boolean;
    readable: boolean;
    writable: boolean;
}
interface FileStats {
    size: number;
    is_file: boolean;
    is_dir: boolean;
    modified: number;
    permissions: number;
    is_symlink?: boolean;
    created?: number;
    accessed?: number;
    readonly?: boolean;
}
interface DirUsage {
    path: string;
    size: number;
    file_count: number;
    dir_count: number;
}
interface DedupeGroup {
    hash: string;
    paths: string[];
    size: number;
}
interface SearchMatch {
    file: string;
    line: number;
    content: string;
}
interface MonitorSnapshot {
    timestamp: string;
    cpu_usage: number;
    memory_used: number;
    memory_total: number;
    process_count: number;
}
interface ProcessMonitorSnapshot {
    timestamp: string;
    cpu_usage: number;
    memory: number;
    disk_read: number;
    disk_write: number;
}
interface ArchiveOptions {
    gzip?: boolean;
}
interface BatchRenameChange {
    old_path: string;
    new_path: string;
}
/**
 * **Filesystem Open Flags**
 *
 * Standardized flags for opening files, following Node.js conventions
 * and mapping to native XHSC `os` constants.
 *
 * ---
 *
 * ### Read flags
 * - `"r"`   — Open for **reading only**. Fails if the file does not exist.
 * - `"r+"`  — Open for **reading and writing**. Fails if the file does not exist.
 * - `"rs+"` — Open for **reading and writing in synchronous mode**. Instructs the OS
 *             to bypass the local file system cache. Useful for NFS mounts or
 *             scenarios where cache coherency is critical.
 *
 * ### Write flags
 * - `"w"`   — Open for **writing only**. The file is **created** if it does not exist,
 *             or **truncated to zero length** if it does.
 * - `"wx"`  — Like `"w"`, but **fails if the file already exists** (exclusive create).
 * - `"w+"`  — Open for **reading and writing**. The file is **created** if it does not
 *             exist, or **truncated** if it does.
 * - `"wx+"` — Like `"w+"`, but **fails if the file already exists** (exclusive create).
 *
 * ### Append flags
 * - `"a"`   — Open for **appending only**. The file is **created** if it does not exist.
 *             The write position is always set to the end of the file.
 * - `"ax"`  — Like `"a"`, but **fails if the file already exists** (exclusive create).
 * - `"a+"`  — Open for **reading and appending**. The file is **created** if it does
 *             not exist. Reading is allowed from any position; writes always go to EOF.
 * - `"ax+"` — Like `"a+"`, but **fails if the file already exists** (exclusive create).
 *
 * ---
 *
 * > **`x` suffix** — The exclusive flag (`x`) maps to `O_EXCL` at the OS level.
 * > It guarantees atomicity: the operation succeeds only if *this* call creates the file,
 * > preventing race conditions in concurrent environments.
 */
type OpenFlag = "r" | "r+" | "rs+" | "w" | "wx" | "w+" | "wx+" | "a" | "ax" | "a+" | "ax+";
type FileOpenFlags = OpenFlag | number;

/**
 * **Operating System & Hardware API**
 */
declare class OSApi extends BaseApi {
    /**
     * **CPU Statistics & Load Analysis**
     *
     * Retrieves detailed information about CPU performance. Can return either
     * an overall average usage snapshot or a per-core breakdown.
     *
     * @param {boolean} [cores=false] - If true, returns an array of individual core statistics.
     * @returns {CpuUsage | CpuInfo[]} Overall usage summary or detailed per-core array.
     *
     * @example
     * // Get overall CPU usage
     * const usage = __sys__.os.cpu();
     * console.log(`CPU Load: ${usage.overall}%`);
     *
     * // Get per-core details
     * const cores = __sys__.os.cpu(true);
     * cores.forEach(c => console.log(`Core ${c.id}: ${c.usage}%`));
     */
    cpu(cores: true): CpuInfo[];
    cpu(cores?: false): CpuUsage;
    /**
     * **Memory & Swap Utilization**
     *
     * Returns a snapshot of the system's memory state, including RAM (total, used, free)
     * and Swap space utilization.
     *
     * @param {boolean} [watch=false] - If true, triggers the underlying engine to start
     * tracking memory trends for subsequent calls.
     * @returns {MemoryInfo} Current memory and swap statistics.
     *
     * @example
     * const mem = __sys__.os.memory();
     * console.log(`RAM Used: ${mem.used / 1024 / 1024} MB`);
     */
    memory: (watch?: boolean) => MemoryInfo;
    /**
     * **General System Metadata**
     *
     * Retrieves fundamental operating system information such as kernel version,
     * hostname, uptime, and distribution details.
     *
     * @returns {SystemInfo} Basic system metadata.
     */
    info: () => SystemInfo;
    /**
     * **Unified Hardware Telemetry**
     *
     * Combines memory, CPU, and low-level system metadata into a single
     * comprehensive hardware profile. Useful for system monitoring dashboards.
     *
     * @returns {SystemHardware} Complete hardware and OS profile.
     */
    get hardware(): SystemHardware;
    /**
     * **Disk & Filesystem Storage Info**
     *
     * Lists all mounted filesystems or retrieves details for a specific mount point.
     * Provides capacity, usage, and available space for each disk.
     *
     * @param {string} [mount] - Optional mount point (e.g., '/', '/home') to filter.
     * @returns {DiskInfo[] | DiskInfo | undefined} List of all disks or a specific disk entry.
     *
     * @example
     * // List all disks
     * const allDisks = __sys__.os.disks();
     *
     * // Get root partition info
     * const root = __sys__.os.disks('/');
     */
    disks(mount: string): DiskInfo | undefined;
    disks(): DiskInfo[];
    /**
     * **Network Interface Statistics**
     *
     * Retrieves status and statistics for network interfaces, including
     * IP addresses, MAC addresses, and traffic metrics (bytes sent/received).
     *
     * @param {string} [interfaceName] - Optional name of the interface (e.g., 'eth0', 'wlan0').
     * @returns {NetworkStats | NetworkInterface} Global stats or specific interface details.
     */
    network: (interfaceName?: string) => NetworkStats | NetworkInterface;
    /**
     * **Process Listing & Querying**
     *
     * Retrieves the current process tree with options to filter by PID or
     * sort by resource consumption (CPU/Memory).
     *
     * @param {Object} [options] - Query options.
     * @param {number} [options.pid] - Filter by specific Process ID.
     * @param {number} [options.topCpu] - Number of top CPU-consuming processes to return.
     * @param {number} [options.topMem] - Number of top Memory-consuming processes to return.
     * @returns {ProcessInfo[] | ProcessInfo | ProcessStats} Process list or individual process data.
     *
     * @security Sensitive internal processes (signature/root flags) are automatically filtered.
     */
    processes: (options?: {
        pid?: number;
        topCpu?: number;
        topMem?: number;
    }) => ProcessInfo[] | ProcessInfo | ProcessStats;
    /**
     * **System Health Assessment**
     *
     * Performs a high-level check of system stability, identifying potential issues
     * with resource exhaustion, high temperatures, or service failures.
     *
     * @returns {any} A health status object with warnings and critical flags.
     */
    health: () => any;
    /**
     * **Real-time System Monitoring**
     *
     * Starts a monitoring session to capture system performance snapshots over time.
     *
     * @param {number} [duration=60] - How long to monitor in seconds.
     * @param {number} [interval=1] - Frequency of snapshots in seconds.
     * @returns {MonitorSnapshot[] | void} Captured snapshots (if not running in interactive mode).
     */
    monitor: (duration?: number, interval?: number) => void | MonitorSnapshot[];
    /**
     * **Individual Process Monitoring**
     *
     * Tracks resource usage (CPU, Memory, Threads) for a specific process over time.
     *
     * @param {number} pid - The ID of the process to monitor.
     * @param {number} [duration=60] - Monitoring duration in seconds.
     * @returns {ProcessMonitorSnapshot[] | void} Captured snapshots.
     */
    monitorProcess: (pid: number, duration?: number) => void | ProcessMonitorSnapshot[];
    /**
     * **Terminate Process**
     *
     * Forcefully stops a process by its ID or Name.
     *
     * @param {number | string} target - PID (number) or Process Name (string).
     */
    kill: (target: number | string) => void;
    /**
     * **Network Port Discovery**
     *
     * Scans and lists all active TCP/UDP ports on the system, including
     * local/remote addresses and associated process names.
     *
     * @returns {PortInfo[]} List of active network ports.
     */
    ports: () => PortInfo[];
    /**
     * **Thermal Sensors Data**
     *
     * Retrieves temperature readings from various hardware sensors (CPU, GPU, Motherboard).
     *
     * @returns {any[]} List of sensor names and their current temperature in Celsius.
     */
    temp: () => any[];
    /**
     * **Battery & Power Management**
     *
     * Retrieves battery status, charge level, and power source information.
     * Useful for managing background tasks on mobile/laptop hardware.
     *
     * @returns {BatteryInfo} Battery status metadata.
     */
    battery: () => BatteryInfo;
    /**
     * **Current OS Platform**
     *
     * Returns the operating system platform (e.g., 'linux', 'darwin', 'win32').
     *
     * @returns {string} Platform identifier.
     */
    platform: () => string;
    /**
     * **User Home Path**
     *
     * Returns the absolute path to the current user's home directory.
     *
     * @returns {string} Absolute home directory path.
     */
    homeDir: () => string;
    /**
     * **System CPU Architecture**
     *
     * Returns the processor architecture (e.g., 'x64', 'arm64').
     *
     * @returns {string} Architecture identifier.
     */
    arch: () => string;
}

/**
 * **Base Filesystem API**
 *
 * Provides the foundation for all filesystem operations, including
 * logger initialization and runner access.
 */
declare class FSBase extends PathApi {
    protected logger: Logger;
    constructor(runner: XyPrissRunner);
}

/**
 * **High-Performance File Toolbox**
 * Exposed via __sys__.fs.open(path, callback)
 */
declare class FileHandle {
    private id;
    private runner;
    private ipc;
    constructor(id: number, runner: any);
    /**
     * **Get Native Handle ID**
     */
    get nativeId(): number;
    /**
     * **Read from File**
     * @param length - Max bytes to read
     */
    read(length: number): Promise<Buffer>;
    /**
     * **Write to File**
     * @param data - Buffer or String
     */
    write(data: Buffer | string): Promise<number>;
    /**
     * **Seek within File**
     * @param offset - Position
     * @param whence - 0: Start, 1: Current, 2: End
     */
    seek(offset: number, whence?: number): Promise<number>;
    /**
     * **Get File Statistics**
     */
    stat(): Promise<FileStats>;
    /**
     * **Close Handle**
     */
    close(): Promise<void>;
}

/**
 * **Core Filesystem Operations**
 */
declare class FSCore extends FSBase {
    /**
     * **List Directory Contents**
     *
     * Retrieves a list of files and directories within a specified path.
     * Can optionally include detailed statistics for each item and recurse
     * into subdirectories.
     *
     * @param {string} p - Absolute or relative path to the directory.
     * @param {Object} [options] - Listing options.
     * @param {boolean} [options.stats=false] - If true, returns an array of `[name, stats]` tuples.
     * @param {boolean} [options.recursive=false] - If true, explores all subdirectories.
     * @returns {string[] | [string, FileStats][]} List of entry names or entry/stats pairs.
     *
     * @example
     * // List names
     * const files = __sys__.fs.ls("/var/log");
     *
     * // List with stats and recursion
     * const details = __sys__.fs.ls("./src", { stats: true, recursive: true });
     * details.forEach(([name, stats]) => console.log(`${name}: ${stats.size} bytes`));
     */
    ls(p: string, options: {
        stats: true;
        recursive?: boolean;
    }): [string, FileStats][];
    ls(p: string, options?: {
        stats?: false;
        recursive?: boolean;
    }): string[];
    /**
     * **Read File Content (Asynchronous)**
     *
     * Asynchronously reads the full content of a file. Supports reading as
     * a string (default) or as a hex-encoded string if bytes are requested.
     *
     * @param {string} p - Path to the file.
     * @param {Object} [options] - Read options.
     * @param {boolean} [options.bytes=false] - If true, returns the raw data as a hex string.
     * @returns {Promise<string>} The file content.
     *
     * @example
     * const content = await __sys__.fs.read("config.yaml");
     * console.log(content);
     */
    read: (p: string, options?: {
        bytes?: boolean;
    }) => Promise<string>;
    /**
     * **Read File Content (Synchronous)**
     *
     * Synchronously reads the full content of a file. Blocks execution until
     * the read operation is complete.
     *
     * @param {string} p - Path to the file.
     * @param {Object} [options] - Read options.
     * @param {boolean} [options.bytes=false] - If true, returns the raw data as a hex string.
     * @returns {string} The file content.
     *
     * @example
     * const content = __sys__.fs.readSync("/etc/hosts");
     */
    readSync: (p: string, options?: {
        bytes?: boolean;
    }) => string;
    /**
     * **High-Performance Read Stream**
     *
     * Creates a readable stream directly from the native XHSC engine. This is
     * the most memory-efficient way to process large files.
     *
     * @param {string} p - Path to the file.
     * @param {Object} [options] - Stream options.
     * @param {number} [options.start] - Start byte offset.
     * @param {number} [options.end] - End byte offset (inclusive).
     * @returns {Readable} A standard Node.js Readable stream.
     *
     * @example
     * const stream = __sys__.fs.createReadStream("big-data.log", { start: 1024, end: 2048 });
     * stream.pipe(process.stdout);
     */
    createReadStream: (p: string, options?: {
        start?: number;
        end?: number;
    }) => Readable;
    /**
     * **High-Performance Write Stream**
     *
     * Creates a writable stream directly to the native XHSC engine. Ideal for
     * generating large files or piping network data to disk.
     *
     * @param {string} p - Destination file path.
     * @returns {Writable & { close(): void }} A standard Node.js Writable stream with a close method.
     *
     * @example
     * const writer = __sys__.fs.createWriteStream("output.tar.gz");
     * source.pipe(writer);
     */
    createWriteStream: (p: string) => Writable & {
        close(): void;
    };
    /**
     * **Write File Content (Asynchronous)**
     *
     * Asynchronously writes data to a file. Automatically handles Buffers,
     * Objects (JSON serialization), and primitives.
     *
     * @param {string} p - Destination path.
     * @param {any} data - Data to write.
     * @param {Object} [options] - Write options.
     * @param {boolean} [options.append=false] - If true, appends to the file instead of overwriting.
     * @param {boolean} [options.ensureFile=true] - If true, creates parent directories if they don't exist.
     * @returns {Promise<void>}
     *
     * @example
     * await __sys__.fs.writeFile("data.json", { user: "iDevo" });
     * await __sys__.fs.writeFile("log.txt", "Event happened\n", { append: true });
     */
    writeFile: (p: string, data: any, options?: {
        append?: boolean;
        ensureFile?: boolean;
    }) => Promise<void>;
    /**
     * **Write File Content (Synchronous)**
     *
     * Synchronously writes data to a file. Blocks execution until the write
     * is finalized on disk.
     *
     * @param {string} p - Destination path.
     * @param {any} data - Data to write.
     * @param {Object} [options] - Write options.
     * @param {boolean} [options.append=false] - If true, appends to the file instead of overwriting.
     * @param {boolean} [options.ensureFile=true] - If true, creates parent directories if they don't exist.
     */
    writeFileSync: (p: string, data: any, options?: {
        append?: boolean;
        ensureFile?: boolean;
    }) => void;
    /**
     * **Copy File or Directory**
     *
     * Recursively copies a file or a complete directory tree from source to destination.
     *
     * @param {string} src - Source path.
     * @param {string} dest - Destination path.
     * @param {Object} [options] - Copy options.
     * @param {boolean} [options.progress=false] - If true, emits progress events for large operations.
     */
    copy: (src: string, dest: string, options?: {
        progress?: boolean;
    }) => void;
    /**
     * **Move/Rename File or Directory**
     *
     * Atomically moves or renames a path. If source and destination are on different
     * filesystems, a copy-and-delete strategy is used.
     *
     * @param {string} src - Original path.
     * @param {string} dest - New path.
     */
    move: (src: string, dest: string) => void;
    /**
     * **Remove File or Directory**
     *
     * Deletes a file or recursively deletes a directory tree.
     *
     * @param {string} p - Path to remove.
     * @param {Object} [options] - Removal options.
     * @param {boolean} [options.force=false] - If true, ignores errors if the path doesn't exist.
     *
     * @example
     * __sys__.fs.rm("./tmp/cache", { force: true });
     */
    rm: (p: string, options?: {
        force?: boolean;
    }) => void;
    /**
     * **Remove Multiple Files or Directories**
     *
     * Bulk deletion of an array of paths. The operation is applied to each
     * path sequentially via the native engine.
     *
     * @param paths - Array of file or directory paths to delete.
     * @param options - Options forwarded to each `rm` call.
     *
     * @example
     * ```typescript
     * __sys__.fs.rmMany([
     *     ".data/chunk.001",
     *     ".data/chunk.002",
     *     ".data/chunk.003",
     * ], { force: true });
     * ```
     */
    rmMany: (paths: string[], options?: {
        force?: boolean;
    }) => void;
    /**
     * **Create Directory**
     *
     * Creates a new directory.
     *
     * @param {string} p - Path to create.
     * @param {Object} [options] - Options.
     * @param {boolean} [options.parents=false] - If true, creates missing parent directories (mkdir -p).
     *
     * @example
     * __sys__.fs.mkdir("/path/to/new-dir", { parents: true });
     */
    mkdir: (p: string, options?: {
        parents?: boolean;
    }) => void;
    /**
     * **Touch File**
     *
     * Updates the access and modification times of a file to the current time.
     * Creates the file if it does not exist.
     *
     * @param {string} p - Path to touch.
     */
    touch: (p: string) => void;
    /**
     * **Create Symbolic Link**
     *
     * Creates a symbolic link pointing to a source path.
     *
     * @param {string} src - The target of the link.
     * @param {string} dest - The path where the link will be created.
     */
    link: (src: string, dest: string) => void;
    /**
     * **Get File Statistics**
     *
     * Retrieves low-level metadata for a path, including size, permissions,
     * and timestamps (creation, modification, access).
     *
     * @param {string} p - Path to query.
     * @returns {FileStats} Metadata object.
     */
    stats: (p: string) => FileStats;
    /**
     * **Calculate Cryptographic Hash**
     *
     * Computes the SHA-256 checksum of a file. Optimized for large files
     * using native buffering.
     *
     * @param {string} p - Path to the file.
     * @returns {string} Hex-encoded hash.
     *
     * @example
     * const sha = __sys__.fs.hash("dist.tar.gz");
     */
    hash: (p: string) => string;
    /**
     * **Verify Integrity**
     *
     * Compares a file's current hash with a provided value to detect
     * corruption or modifications.
     *
     * @param {string} p - Path to the file.
     * @param {string} hash - Expected SHA-256 hash.
     * @returns {boolean} True if hashes match.
     */
    verify: (p: string, hash: string) => boolean;
    /**
     * **Get Size in Bytes or Human Readable**
     *
     * Retrieves the size of a file or directory.
     *
     * @param {string} p - Path.
     * @param {Object} [options] - Options.
     * @param {boolean} [options.human=false] - If true, returns a string (e.g., '1.5 GB').
     * @returns {number | string} Numeric bytes or formatted string.
     */
    size: (p: string, options?: {
        human?: boolean;
    }) => number | string;
    /**
     * **Change File Permissions**
     *
     * Modifies the access permissions (mode) of a file or directory.
     *
     * @param {string} p - Path.
     * @param {string | number} mode - Octal permissions (e.g., 0o755 or '755').
     */
    chmod: (p: string, mode: string | number) => void;
    /**
     * **Comprehensive Path Existence & State Check**
     *
     * Returns an object indicating if the path exists, and whether it is a
     * file, directory, or symbolic link.
     *
     * @param {string} p - Path to check.
     * @returns {PathCheck} Status object.
     */
    check: (p: string) => PathCheck;
    /**
     * **Directory Usage Summary**
     *
     * Recursively calculates the total size and file count of a directory.
     *
     * @param {string} p - Directory path.
     * @returns {DirUsage} Usage summary.
     */
    du: (p: string) => DirUsage;
    /**
     * **Bidirectional Directory Synchronization**
     *
     * Efficiently synchronizes two directories, mirroring changes from source
     * to destination.
     *
     * @param {string} src - Source directory.
     * @param {string} dest - Destination directory.
     */
    sync: (src: string, dest: string) => void;
    /**
     * **Content-Based Duplicate Detection**
     *
     * Analyzes a directory for identical files (using hash comparisons) and
     * groups them together.
     *
     * @param {string} p - Search path.
     * @returns {DedupeGroup[]} Groups of duplicate files.
     */
    dedupe: (p: string) => DedupeGroup[];
    /**
     * **Open File**
     *
     * Opens a file and returns a numeric file descriptor (or runs a scoped callback).
     *
     * ---
     *
     * ### Modes via `flags`
     *
     * | Flag    | Behavior                                                        |
     * |---------|-----------------------------------------------------------------|
     * | `"r"`   | Read-only. Fails if the file does not exist.                    |
     * | `"r+"`  | Read-write. Fails if the file does not exist.                   |
     * | `"rs+"` | Read-write, bypasses OS cache (useful for NFS / shared drives). |
     * | `"w"`   | Write-only. Creates the file or truncates it if it exists.      |
     * | `"wx"`  | Write-only. Fails if the file already exists (atomic create).   |
     * | `"w+"`  | Read-write. Creates the file or truncates it if it exists.      |
     * | `"wx+"` | Read-write. Fails if the file already exists (atomic create).   |
     * | `"a"`   | Append-only. Creates the file if missing. Writes go to EOF.     |
     * | `"ax"`  | Append-only. Fails if the file already exists (atomic create).  |
     * | `"a+"`  | Read-append. Creates the file if missing. Writes always at EOF. |
     * | `"ax+"` | Read-append. Fails if the file already exists (atomic create).  |
     *
     * > **`x` suffix** — Maps to `O_EXCL` at the OS level: the call succeeds only if
     * > *this* invocation creates the file, preventing race conditions.
     *
     * ---
     *
     * ### Transport strategy
     *
     * The method resolves the file descriptor through two transports, in order:
     *
     * 1. **IPC** (`XYPRISS_IPC_PATH` set) — communicates with the XHSC daemon via a
     *    Unix socket. File descriptors are **stateful and persistent** across calls.
     * 2. **Runner fallback** — used when IPC is unavailable or the environment variable
     *    is not set. Descriptors are **not persistent** across multiple independent calls;
     *    a warning is emitted to the console.
     *
     * ---
     *
     * ### Callback (scoped) mode
     *
     * When a `callback` is provided, the file is opened, passed as a {@link FileHandle}
     * toolbox to the callback, then **automatically closed** in a `finally` block —
     * even if the callback throws. In this mode the method returns `void`.
     *
     * When no callback is provided, the raw numeric file descriptor is returned and
     * **the caller is responsible for closing it**.
     *
     * ---
     *
     * @param p        - Absolute or relative path to the target file.
     * @param flags    - Open mode, as a string flag (default: `"r"`) or a numeric
     *                   `os` constant. See the flag table above.
     * @param callback - Optional scoped handler receiving a {@link FileHandle}.
     *                   When supplied, the handle is closed automatically on completion.
     *
     * @returns The numeric file descriptor when no callback is given; `void` otherwise.
     *
     * @example <caption>Scoped read (handle closed automatically)</caption>
     * ```typescript
     * await __sys__.fs.open("data.bin", "r", async (file) => {
     *     const chunk = await file.read(1024);
     *     console.log(chunk.toString());
     * });
     * ```
     *
     * @example <caption>Manual descriptor (caller must close)</caption>
     * ```typescript
     * const fd = await __sys__.fs.open("output.log", "a");
     * // ... write operations ...
     * await __sys__.fs.close(fd);
     * ```
     */
    open(p: string, flags?: FileOpenFlags, callback?: (handle: FileHandle) => Promise<void> | void): Promise<number | void>;
    /**
     * **Close File Handle**
     *
     * @param handle - The file handle to close.
     */
    close: (handle: number) => Promise<void>;
    private mapFlags;
}

/**
 * **Filesystem Convenience Helpers**
 */
declare class FSHelpers extends FSCore {
    /**
     * **Deep Recursive Directory Listing**
     *
     * Explores a directory tree and returns a flat array of all file and
     * subdirectory paths found. Supports optional filtering.
     *
     * @param {string} p - Root path to start recursion.
     * @param {Function} [filter] - Optional callback to include/exclude paths.
     * @returns {string[]} Flat list of matching paths.
     *
     * @example
     * const tsFiles = __sys__.fs.lsRecursive("./src", (path) => path.endsWith(".ts"));
     */
    lsRecursive: (p: string, filter?: (path: string) => boolean) => string[];
    /**
     * **Filter Directories Only**
     *
     * Returns a list of directory names within the specified path.
     *
     * @param {string} p - Path to scan.
     * @returns {string[]} List of directory names.
     */
    lsDirs: (p: string) => string[];
    /**
     * **Filter Files Only**
     *
     * Returns a list of file names within the specified path.
     *
     * @param {string} p - Path to scan.
     * @returns {string[]} List of file names.
     */
    lsFiles: (p: string) => string[];
    /**
     * **Read File (Asynchronous String)**
     *
     * Wrapper for `read()` that explicitly returns the content as a string.
     *
     * @param {string} p - Path to the file.
     * @param {BufferEncoding} [encoding='utf8'] - Ignored (system uses native UTF-8).
     * @returns {Promise<string>} File content string.
     */
    readFile: (p: string, encoding?: BufferEncoding) => Promise<string>;
    /**
     * **Read File (Synchronous String)**
     *
     * Wrapper for `readSync()` that explicitly returns the content as a string.
     *
     * @param {string} p - Path to the file.
     * @param {BufferEncoding} [encoding='utf8'] - Ignored (system uses native UTF-8).
     * @returns {string} File content string.
     */
    readFileSync: (p: string, encoding?: BufferEncoding) => string;
    /**
     * **Read & Parse JSON (Asynchronous)**
     *
     * Reads a file and parses its content into a JavaScript object.
     *
     * @template T - Expected object structure.
     * @param {string} p - Path to the JSON file.
     * @returns {Promise<T>} Parsed object.
     */
    readJson: <T = any>(p: string) => Promise<T>;
    /**
     * **Read & Parse JSON (Synchronous)**
     *
     * Synchronously reads a file and parses its content into a JavaScript object.
     *
     * @template T - Expected object structure.
     * @param {string} p - Path to the JSON file.
     * @returns {T} Parsed object.
     *
     * @example
     * const config = __sys__.fs.readJsonSync("package.json");
     */
    readJsonSync: <T = any>(p: string) => T;
    /**
     * **Read File as Binary (Asynchronous)**
     *
     * Reads a file and returns its raw binary content as a Node.js Buffer.
     *
     * @param {string} p - Path to the file.
     * @returns {Promise<Buffer>} Binary data.
     */
    readBytes: (p: string) => Promise<Buffer>;
    /**
     * **Read File as Binary (Synchronous)**
     *
     * Synchronously reads a file and returns its raw binary content as a Node.js Buffer.
     *
     * @param {string} p - Path to the file.
     * @returns {Buffer} Binary data.
     */
    readBytesSync: (p: string) => Buffer;
    /**
     * **Write Binary Data (Asynchronous)**
     *
     * Writes a Node.js Buffer directly to a file.
     *
     * @param {string} p - Destination path.
     * @param {Buffer} data - Binary data to write.
     * @returns {Promise<void>}
     */
    writeBytes: (p: string, data: Buffer) => Promise<void>;
    /**
     * **Write Binary Data (Synchronous)**
     *
     * Synchronously writes a Node.js Buffer directly to a file.
     *
     * @param {string} p - Destination path.
     * @param {Buffer} data - Binary data to write.
     */
    writeBytesSync: (p: string, data: Buffer) => void;
    /**
     * **Fault-Tolerant JSON Read (Asynchronous)**
     *
     * Attempts to read and parse a JSON file. If the file is missing or invalid,
     * it returns a provided default value instead of throwing.
     *
     * @template T - Expected object structure.
     * @param {string} p - Path to the JSON file.
     * @param {T} defaultValue - Value to return on failure.
     * @returns {Promise<T>} Parsed object or default value.
     */
    readJsonSafe: <T = any>(p: string, defaultValue: T) => Promise<T>;
    /**
     * **Fault-Tolerant JSON Read (Synchronous)**
     *
     * Synchronously attempts to read and parse a JSON file, returning a default
     * value on any error.
     *
     * @template T - Expected object structure.
     * @param {string} p - Path to the JSON file.
     * @param {T} defaultValue - Value to return on failure.
     * @returns {T} Parsed object or default value.
     */
    readJsonSafeSync: <T = any>(p: string, defaultValue: T) => T;
    /**
     * **Write Object as JSON (Asynchronous)**
     *
     * Serializes an object to JSON and writes it to a file.
     *
     * @param {string} p - Destination path.
     * @param {any} data - Object to serialize.
     * @returns {Promise<void>}
     */
    writeJson: (p: string, data: any) => Promise<void>;
    /**
     * **Write Object as JSON (Synchronous)**
     *
     * Synchronously serializes an object to JSON and writes it to a file.
     *
     * @param {string} p - Destination path.
     * @param {any} data - Object to serialize.
     */
    writeJsonSync: (p: string, data: any) => void;
    /**
     * **Split File into Lines (Asynchronous)**
     *
     * Reads a file and splits its content into an array of lines based on
     * platform-agnostic newline characters.
     *
     * @param {string} p - Path to the file.
     * @returns {Promise<string[]>} Array of lines.
     */
    readLines: (p: string) => Promise<string[]>;
    /**
     * **Split File into Lines (Synchronous)**
     *
     * Synchronously reads a file and splits its content into an array of lines.
     *
     * @param {string} p - Path to the file.
     * @returns {string[]} Array of lines.
     */
    readLinesSync: (p: string) => string[];
    /**
     * **Read Filtered Content (Asynchronous)**
     *
     * Reads a file and returns an array containing only non-empty, trimmed lines.
     *
     * @param {string} p - Path to the file.
     * @returns {Promise<string[]>} Array of non-empty lines.
     */
    readNonEmptyLines: (p: string) => Promise<string[]>;
    /**
     * **Read Filtered Content (Synchronous)**
     *
     * Synchronously reads a file and returns an array of non-empty, trimmed lines.
     *
     * @param {string} p - Path to the file.
     * @returns {string[]} Array of non-empty lines.
     */
    readNonEmptyLinesSync: (p: string) => string[];
    /**
     * **Append Text to File (Asynchronous)**
     *
     * Adds content to the end of a file.
     *
     * @param {string} p - Path to the file.
     * @param {any} data - Content to append.
     * @returns {Promise<void>}
     */
    append: (p: string, data: any) => Promise<void>;
    /**
     * **Append Text to File (Synchronous)**
     *
     * Synchronously adds content to the end of a file.
     *
     * @param {string} p - Path to the file.
     * @param {any} data - Content to append.
     */
    appendSync: (p: string, data: any) => void;
    /**
     * **Append Single Line (Asynchronous)**
     *
     * Adds content followed by a newline character to the end of a file.
     *
     * @param {string} p - Path to the file.
     * @param {any} line - Line content to append.
     * @returns {Promise<void>}
     */
    appendLine: (p: string, line: any) => Promise<void>;
    /**
     * **Append Single Line (Synchronous)**
     *
     * Synchronously adds a line of content to the end of a file.
     *
     * @param {string} p - Path to the file.
     * @param {any} line - Line content to append.
     */
    appendLineSync: (p: string, line: any) => void;
    /**
     * **Write If New (Asynchronous)**
     *
     * Writes data to a file ONLY if the file does not already exist.
     *
     * @param {string} p - Destination path.
     * @param {any} data - Data to write.
     * @returns {Promise<boolean>} True if the file was written, false if it already existed.
     */
    writeIfNotExists: (p: string, data: any) => Promise<boolean>;
    /**
     * **Write If New (Synchronous)**
     *
     * Synchronously writes data to a file only if it does not already exist.
     *
     * @param {string} p - Destination path.
     * @param {any} data - Data to write.
     * @returns {boolean} True if written, false otherwise.
     */
    writeIfNotExistsSync: (p: string, data: any) => boolean;
    /**
     * **Ensure Directory Existence**
     *
     * Guarantees that a directory (and all its parents) exists. Does nothing
     * if the directory is already present.
     *
     * @param {string} p - Directory path to ensure.
     *
     * @example
     * __sys__.fs.ensureDir("./data/logs/archive");
     */
    ensureDir: (p: string) => void;
    /**
     * **Non-Blocking Directory Creation**
     *
     * Attempts to create a directory tree. Returns false if the path already exists.
     *
     * @param {string} p - Path to create.
     * @returns {boolean} True if the directory was created.
     */
    mkdirSafe: (p: string) => boolean;
    /**
     * **List with Absolute Paths**
     *
     * Lists directory contents and returns them as a flat array of absolute paths.
     *
     * @param {string} p - Directory to scan.
     * @returns {string[]} List of absolute paths.
     */
    lsFullPath: (p: string) => string[];
    /**
     * **Rename Entry**
     *
     * Alias for `move()`. Changes the name or location of a file/directory.
     *
     * @param {string} oldPath - Current path.
     * @param {string} newPath - Target path.
     */
    rename: (oldPath: string, newPath: string) => void;
    /**
     * **Clone Entry**
     *
     * Creates a copy of a file or directory in the same parent folder with a new name.
     *
     * @param {string} p - Original path.
     * @param {string} newName - New filename or directory name.
     */
    duplicate: (p: string, newName: string) => void;
    /**
     * **Safe Removal**
     *
     * Deletes a file or directory only if it currently exists on the filesystem.
     *
     * @param {string} p - Path to remove.
     */
    rmIfExists: (p: string) => void;
    /**
     * **Clear Directory Contents**
     *
     * Deletes all files and subdirectories within a directory, but keeps
     * the empty directory itself.
     *
     * @param {string} p - Directory to empty.
     */
    emptyDir: (p: string) => void;
    /**
     * **Get Formatted Size String**
     *
     * Returns the size of a path in a human-readable format (e.g., '12 MB', '1.2 GB').
     *
     * @param {string} p - Path to query.
     * @returns {string} Human-readable size.
     */
    sizeHuman: (p: string) => string;
    /**
     * **Get Creation Timestamp**
     *
     * Retrieves the exact date and time when the file or directory was created.
     *
     * @param {string} p - Path to query.
     * @returns {Date} Creation date object.
     */
    createdAt: (p: string) => Date;
    /**
     * **Get Last Modification Timestamp**
     *
     * Retrieves the exact date and time when the file content or directory
     * was last changed.
     *
     * @param {string} p - Path to query.
     * @returns {Date} Modification date object.
     */
    modifiedAt: (p: string) => Date;
    /**
     * **Get Last Access Timestamp**
     *
     * Retrieves the exact date and time when the file was last accessed
     * (read or written).
     *
     * @param {string} p - Path to query.
     * @returns {Date} Access date object.
     */
    accessedAt: (p: string) => Date;
    /**
     * **Verify Content Identity**
     *
     * Compares two files to see if they have identical content by comparing
     * their cryptographic hashes.
     *
     * @param {string} p1 - First file path.
     * @param {string} p2 - Second file path.
     * @returns {boolean} True if content is identical.
     */
    isSameContent: (p1: string, p2: string) => boolean;
    /**
     * **Compare Timestamps**
     *
     * Checks if the first path was modified more recently than the second path.
     *
     * @param {string} p1 - Primary path.
     * @param {string} p2 - Path to compare against.
     * @returns {boolean} True if p1 is newer than p2.
     */
    isNewer: (p1: string, p2: string) => boolean;
}

/**
 * **Filesystem Search & Pattern Matching**
 */
declare class FSSearch extends FSHelpers {
    /**
     * **Content Search (Grep)**
     *
     * Scans all files within a directory for a specific text pattern.
     * Extremely fast, leveraging the native engine's parallel search.
     *
     * @param {string} dir - Directory to search in.
     * @param {string} pattern - Text or regex pattern to look for.
     * @returns {SearchMatch[]} List of matches with line numbers and snippets.
     *
     * @example
     * const matches = __sys__.fs.searchInFiles("./src", "TODO");
     */
    searchInFiles: (dir: string, pattern: string) => SearchMatch[];
    /**
     * **Filenames Search (Find)**
     *
     * Searches for files by name pattern within a directory.
     *
     * @param {string} dir - Directory to search in.
     * @param {string} pattern - Glob or regex pattern for filenames.
     * @returns {string[]} List of matching file paths.
     *
     * @example
     * const tsFiles = __sys__.fs.findByPattern("./src", "*.ts");
     */
    findByPattern: (dir: string, pattern: string) => string[];
    /**
     * **Filter by File Extension**
     *
     * Retrieves all files within a directory that match the specified extension.
     *
     * @param {string} dir - Directory to search in.
     * @param {string} ext - File extension (e.g., 'png', '.jpg').
     * @returns {string[]} List of matching file paths.
     *
     * @example
     * const images = __sys__.fs.findByExt("./assets", "png");
     */
    findByExt: (dir: string, ext: string) => string[];
    /**
     * **Pattern-Based Batch Renaming**
     *
     * Renames multiple files at once by replacing occurrences of a pattern
     * in their filenames.
     *
     * @param {string} path - Directory to operate on.
     * @param {string} pattern - Pattern to match in filenames.
     * @param {string} replacement - String to replace the pattern with.
     * @param {boolean} [dryRun=false] - If true, returns the planned changes without applying them.
     * @returns {number | BatchRenameChange[]} Number of files renamed, or change list if dryRun is true.
     *
     * @example
     * __sys__.fs.batchRename("./logs", "log-", "archive-");
     */
    batchRename: (path: string, pattern: string, replacement: string, dryRun?: boolean) => number | BatchRenameChange[];
    /**
     * **Recent Modification Discovery**
     *
     * Finds files that have been modified within a specific number of hours.
     *
     * @param {string} dir - Directory to search in.
     * @param {number} hours - Time window in hours.
     * @returns {string[]} List of recently modified file paths.
     *
     * @example
     * const changedInLastDay = __sys__.fs.findModifiedSince("./src", 24);
     */
    findModifiedSince: (dir: string, hours: number) => string[];
}

/**
 * **Filesystem Archive & Compression**
 */
declare class FSArchive extends FSSearch {
    /**
     * **File Compression (Gzip)**
     *
     * Performs lossless compression on a file using the Gzip algorithm.
     *
     * @param {string} src - Source file path.
     * @param {string} dest - Destination path for the compressed file (e.g., 'data.gz').
     *
     * @example
     * __sys__.fs.compress("backup.sql", "backup.sql.gz");
     */
    compress: (src: string, dest: string) => void;
    /**
     * **File Decompression**
     *
     * Extracts a compressed file back to its original state.
     *
     * @param {string} src - Path to the compressed file.
     * @param {string} dest - Destination path for the extracted file.
     *
     * @example
     * __sys__.fs.decompress("data.gz", "data.json");
     */
    decompress: (src: string, dest: string) => void;
    /**
     * **Tarball Creation**
     *
     * Bundles a directory or file into a single TAR archive.
     *
     * @param {string} dir - Directory to archive.
     * @param {string} output - Destination path for the .tar file.
     *
     * @example
     * __sys__.fs.tar("./src", "project_source.tar");
     */
    tar: (dir: string, output: string) => void;
    /**
     * **Tarball Extraction**
     *
     * Extracts the contents of a TAR archive into a specified directory.
     *
     * @param {string} archive - Path to the .tar file.
     * @param {string} dest - Destination directory for extraction.
     *
     * @example
     * __sys__.fs.untar("dist.tar", "./production");
     */
    untar: (archive: string, dest: string) => void;
}

/**
 * **Filesystem Watching & Streaming**
 */
declare class FSWatch extends FSArchive {
    /**
     * **Real-time Path Monitoring**
     *
     * Monitors one or more paths for changes (file creation, modification,
     * or deletion). Runs in interactive mode by default.
     *
     * @param {string | string[]} p - Path(s) to watch.
     * @param {Object} [options] - Monitoring options.
     * @param {number} [options.duration=60] - How long to watch in seconds.
     *
     * @example
     * __sys__.fs.watch("./src", { duration: 120 });
     */
    watch: (p: string | string[], options?: {
        duration?: number;
    }) => void;
    /**
     * **Optimized File Streaming**
     *
     * Reads a file in chunks and returns a streaming representation.
     *
     * @param {string} p - Path to the file.
     * @param {Object} [options] - Stream options.
     * @param {number} [options.chunkSize] - Size of each chunk in bytes.
     * @param {boolean} [options.hex=false] - If true, returns chunks as hex strings.
     * @returns {string} Streamed content.
     *
     * @example
     * const data = __sys__.fs.stream("large-asset.dat", { chunkSize: 4096 });
     */
    stream: (p: string, options?: {
        chunkSize?: number;
        hex?: boolean;
    }) => string;
    /**
     * **Reactive File Watching**
     *
     * Monitors a path for changes and executes a callback function whenever
     * a modification is detected.
     *
     * @param {string} p - Path to watch.
     * @param {Function} callback - Function to run on changes.
     * @param {Object} [options] - Monitoring options.
     * @param {number} [options.duration=60] - How long to watch in seconds.
     *
     * @example
     * __sys__.fs.watchAndProcess("./src", () => {
     *   console.log("Re-building project...");
     * });
     */
    watchAndProcess: (p: string, callback: () => void, options?: {
        duration?: number;
    }) => void;
    /**
     * **Content Diff Monitoring**
     *
     * Monitors file content changes and optionally displays or returns
     * the diff between versions.
     *
     * @param {string | string[]} p - Path(s) to monitor.
     * @param {Object} [options] - Options.
     * @param {number} [options.duration=60] - Monitoring duration.
     * @param {boolean} [options.diff=true] - If true, performs a deep content diff.
     *
     * @example
     * __sys__.fs.watchContent("config.json", { diff: true });
     */
    watchContent: (p: string | string[], options?: {
        duration?: number;
        diff?: boolean;
    }) => void;
    /**
     * **Watch Parallel**
     */
    watchParallel: (p: string | string[], options?: {
        duration?: number;
    }) => void;
    /**
     * **Watch Content Parallel**
     */
    watchContentParallel: (p: string | string[], options?: {
        duration?: number;
        diff?: boolean;
    }) => void;
    /**
     * Alias for $watchAndProcess
     */
    wap(...args: Parameters<typeof this.watchAndProcess>): void;
    /**
     * Alias for $watchContent
     */
    wc(...args: Parameters<typeof this.watchContent>): void;
    /**
     * Alias for $watchParallel
     */
    wp(...args: Parameters<typeof this.watchParallel>): void;
    /**
     * Alias for $watchContentParallel
     */
    wcp(...args: Parameters<typeof this.watchContentParallel>): void;
}

/**
 * **Advanced & Security Filesystem Operations**
 */
declare class FSExtended extends FSWatch {
    /**
     * **Atomic Write (Asynchronous)**
     *
     * Writes data to a temporary file first and renames it to the target path
     * to ensure file system atomicity. This prevents partial writes or file
     * corruption during system crashes.
     *
     * @param {string} p - Destination path.
     * @param {any} data - Data to write.
     * @param {Object} [options] - Options.
     * @param {boolean} [options.ensureFile=true] - Create parent directories if missing.
     * @returns {Promise<void>}
     *
     * @example
     * await __sys__.fs.atomicWrite("database.json", largeObject);
     */
    atomicWrite: (p: string, data: any, options?: {
        ensureFile?: boolean;
    }) => Promise<void>;
    /**
     * **Atomic Write (Synchronous)**
     *
     * Synchronously performs an atomic write operation. Blocks until the
     * operation is confirmed by the OS.
     *
     * @param {string} p - Destination path.
     * @param {any} data - Data to write.
     * @param {Object} [options] - Options.
     */
    atomicWriteSync: (p: string, data: any, options?: {
        ensureFile?: boolean;
    }) => void;
    /**
     * **Secure File Erasure (Shred)**
     *
     * Overwrites file content multiple times with random data before deletion
     * to prevent recovery via forensic tools.
     *
     * @param {string} p - Path to the file to destroy.
     * @param {number} [passes=3] - Number of overwrite iterations.
     *
     * @example
     * __sys__.fs.shred("passwords.txt", 7);
     */
    shred: (p: string, passes?: number) => void;
    /**
     * **Retrieve End of File (Tail)**
     *
     * Reads the last N lines of a file. Optimized for large log files.
     *
     * @param {string} p - Path to the file.
     * @param {number} [lines=10] - Number of lines to retrieve.
     * @returns {string[]} Array of lines.
     *
     * @example
     * const lastLogs = __sys__.fs.tail("server.log", 50);
     */
    tail: (p: string, lines?: number) => string[];
    /**
     * **In-Place File Patching**
     *
     * Replaces content within a file without rewriting the entire file.
     *
     * @param {string} p - Path to the file.
     * @param {string | RegExp} searchValue - Pattern to search for.
     * @param {string} replaceValue - New content.
     * @returns {boolean} True if any replacement occurred.
     *
     * @example
     * __sys__.fs.patch("setup.cfg", "VERSION=1.0", "VERSION=1.1");
     */
    patch: (p: string, searchValue: string | RegExp, replaceValue: string) => boolean;
    /**
     * **File Fragmentation (Split)**
     *
     * Splits a large file into multiple smaller chunks.
     *
     * @param {string} p - Path to the source file.
     * @param {number} bytesPerChunk - Maximum size of each chunk.
     * @param {string} [outDir] - Directory where chunks will be saved.
     * @returns {string[]} Paths to the generated chunks.
     */
    split: (p: string, bytesPerChunk: number, outDir?: string) => string[];
    /**
     * **File Reconstruction (Merge)**
     *
     * Reassembles multiple file chunks into a single destination file.
     *
     * @param {string[]} sourceFiles - Ordered array of chunk paths.
     * @param {string} destFile - Target destination for the merged file.
     */
    merge: (sourceFiles: string[], destFile: string) => void;
    /**
     * **Advisory File Locking**
     *
     * Attempts to acquire an exclusive lock on a file to prevent concurrent access.
     *
     * @param {string} p - Path to the file.
     * @returns {boolean} True if the lock was successfully acquired.
     */
    lock: (p: string) => boolean;
    /**
     * **Release File Lock**
     *
     * Unlocks a previously locked file.
     *
     * @param {string} p - Path to the file.
     *
     * @example
     * __sys__.fs.unlock("exclusive.data");
     */
    unlock: (p: string) => void;
    /**
     * **Secure Permission Write (Asynchronous)**
     *
     * Writes data to a file and immediately applies a restricted permission mode.
     *
     * @param {string} p - Destination path.
     * @param {any} data - Data to write.
     * @param {string} mode - Octal mode (e.g., '600').
     * @returns {Promise<void>}
     */
    writeSecure: (p: string, data: any, mode: string) => Promise<void>;
    /**
     * **Secure Permission Write (Synchronous)**
     *
     * Synchronously writes data and applies a restricted mode.
     *
     * @param {string} p - Destination path.
     * @param {any} data - Data to write.
     * @param {string} mode - Octal mode.
     */
    writeSecureSync: (p: string, data: any, mode: string) => void;
    /**
     * **Transparent File Encryption (AES-256-GCM)**
     *
     * Encrypts the contents of a file in-place using a symmetric key.
     *
     * @param {string} p - Path to the file.
     * @param {string} key - Secret encryption key.
     * @returns {Promise<void>}
     */
    encryptFile: (p: string, key: string) => Promise<void>;
    /**
     * **Transparent File Decryption**
     *
     * Decrypts a file previously encrypted with `encryptFile()`.
     *
     * @param {string} p - Path to the file.
     * @param {string} key - Secret decryption key.
     * @returns {Promise<void>}
     *
     * @example
     * await __sys__.fs.decryptFile("vault.bin", "passphrase");
     */
    decryptFile: (p: string, key: string) => Promise<void>;
    /**
     * **Hardware-Bound Encryption**
     *
     * Encrypts a file using a key derived from the system's unique hardware ID.
     * This file can ONLY be decrypted on this specific machine.
     *
     * @param {string} p - Path to the file.
     * @param {string} key - User-provided part of the secret.
     * @returns {Promise<void>}
     */
    hardwareEncryptFile: (p: string, key: string) => Promise<void>;
    /**
     * **Hardware-Bound Decryption**
     *
     * Decrypts a file using the system's hardware ID.
     *
     * @param {string} p - Path to the file.
     * @param {string} key - User-provided part of the secret.
     * @returns {Promise<void>}
     */
    hardwareDecryptFile: (p: string, key: string) => Promise<void>;
    /**
     * **Deep File Diff**
     *
     * Performs a line-by-line comparison between two files and returns
     * all differences.
     *
     * @param {string} fileA - First file.
     * @param {string} fileB - Second file.
     * @returns {Array<Object>} List of differences with line numbers.
     */
    diffFiles: (fileA: string, fileB: string) => Array<{
        line: number;
        file_a: string;
        file_b: string;
    }>;
    /**
     * **Storage Analysis**
     *
     * Scans a directory and returns a list of the largest files found.
     *
     * @param {string} dir - Directory to scan.
     * @param {number} [limit=50] - Number of top files to return.
     * @returns {Array<Object>} List of paths and sizes.
     */
    topBigFiles: (dir: string, limit?: number) => Array<{
        path: string;
        size: number;
    }>;
}

/**
 * **Professional Filesystem API (High Performance)**
 *
 * The `FSApi` class provides a unified, high-performance interface for all filesystem operations.
 * It is modularized into several specialized layers while maintaining a single cohesive API.
 *
 * **Modular Structure:**
 * - `FSCore`: Fundamental operations (ls, read, write, move, rm)
 * - `FSHelpers`: Convenience methods (JSON patterns, type checks)
 * - `FSSearch`: Regex-based discovery and grep
 * - `FSArchive`: Compression and TAR handling
 * - `FSWatch`: Real-time monitoring and streaming
 * - `FSExtended`: Advanced security and atomic operations
 *
 * @class FSApi
 * @extends FSExtended
 */
declare class FSApi extends FSExtended {
}

/**
 * **Dynamic Variables & Configuration API**
 *
 * Provides a managed key-value store for application variables and system metadata.
 */
declare class VarsApi extends BaseApi {
    private vars;
    __version__: string;
    __author__: string;
    __description__: string;
    __app_urls__: Record<string, string>;
    __name__: string;
    __alias__: string;
    __port__: number;
    __PORT__: number;
    get __root__(): string;
    constructor(runner: any);
    /**
     * **Get Variable**
     *
     * Retrieves the value of a dynamic variable.
     *
     * @param {string} key - The variable name.
     * @param {any} [defaultValue] - Value to return if key is missing.
     * @returns {any} The variable value or default.
     */
    get(key: string, defaultValue?: any): any;
    /**
     * **Set Variable**
     *
     * Sets or updates a dynamic variable.
     *
     * @param {string} key - The variable name.
     * @param {any} value - The value to store.
     * @returns {void}
     */
    set(key: string, value: any): void;
    /**
     * **Check Existence**
     *
     * @param {string} key - The variable name.
     * @returns {boolean} True if defined.
     */
    has(key: string): boolean;
    /**
     * **Remove Variable**
     *
     * @param {string} key - The variable name.
     */
    delete(key: string): void;
    /**
     * **Update Multiple Variables**
     *
     * Merges a configuration object into the variable store.
     *
     * @param {Record<string, any>} data - Data to merge.
     */
    update(data: Record<string, any>): void;
    /**
     * **List Keys**
     */
    keys(): string[];
    /**
     * **Get All Variables**
     */
    all(): Record<string, any>;
    /**
     * **Serialize to JSON**
     */
    toJSON(): Record<string, any>;
    /**
     * **Deep Clone**
     */
    clone(): Record<string, any>;
    /**
     * **Clear All**
     */
    clear(): void;
}

declare const XY_XHSC_REGISTER_FS: unique symbol;
/**
 * Represents the result of a bulk environment variable retrieval.
 *
 * The object is frozen at the moment of creation. Keys map to their
 * corresponding string values, or `undefined` if the key was requested via
 * `options.keys` but was not present in the store.
 */
type EnvSnapshot = Readonly<Record<string, string | undefined>>;
/**
 * Options accepted by {@link EnvApi.getStrict} to control validation behaviour.
 */
interface EnvGetStrictOptions {
    /**
     * When `true`, an empty string is treated as a missing value and triggers
     * the same {@link EnvAccessError} as a completely absent key.
     *
     * @default false
     */
    rejectEmpty?: boolean;
}
/**
 * Options accepted by {@link EnvApi.all}.
 */
interface EnvAllOptions {
    /**
     * Restricts the snapshot to the listed keys. Keys absent from the store
     * are included with value `undefined`. When omitted, all stored keys are
     * returned.
     *
     * Providing an explicit key list is strongly preferred in production code
     * to avoid accidentally surfacing secrets in logs or serialised payloads.
     *
     * @example
     * const subset = __sys__.__env__.all({
     *   keys: ["DATABASE_URL", "REDIS_URL"],
     * });
     */
    keys?: string[];
}
/**
 * Public contract for the XyPriss Environment Manager.
 *
 * All access to environment variables within XyPriss applications must go
 * through this interface. Direct use of `process.env` is blocked by the
 * Environment Security Shield and returns `undefined` at runtime.
 *
 * @see {@link EnvApi} for the concrete implementation.
 *
 * @example
 * // Reading with a fallback
 * const port = __sys__.__env__.get("PORT", "3000");
 *
 * // Reading a required variable — throws EnvAccessError if absent
 * const secret = __sys__.__env__.getStrict("JWT_SECRET");
 *
 * // Checking the execution mode
 * if (__sys__.__env__.isProduction()) {
 *   // Apply production hardening
 * }
 */
interface IEnvApi {
    /**
     * The current execution mode (`"development"`, `"production"`,
     * `"staging"`, `"test"`, or a custom value). Set once at bootstrap;
     * never mutated at runtime.
     */
    readonly mode: string;
    /**
     * Writes an environment variable to the secure internal store.
     *
     * @param key   - Non-empty variable name without surrounding whitespace.
     * @param value - The value to assign. Must not contain CR, LF, or NUL.
     * @throws {EnvKeyError} When the key or value fails validation.
     * @throws {EnvStoreError} When called before store initialisation.
     */
    set(key: string, value: string): void;
    /**
     * Reads an environment variable from the secure internal store.
     *
     * @param key          - The variable name to look up.
     * @param defaultValue - Returned when the key is not defined.
     * @returns The stored value, or `defaultValue` / `undefined`.
     * @throws {EnvStoreError} When called before store initialisation.
     *
     * @example
     * const host = __sys__.__env__.get("HOST", "0.0.0.0");
     */
    get(key: string): string | undefined;
    get(key: string, defaultValue: string): string;
    get(key: string, defaultValue?: string): string | undefined;
    /**
     * Reads an environment variable for a specific project root, bypassing caller discovery.
     * Useful when parsing configuration files on behalf of another project context.
     *
     * @param key   - The variable name to look up.
     * @param root  - The explicit project root to read the environment from.
     * @returns The stored value, or `undefined`.
     */
    getForRoot(key: string, root: string): string | undefined;
    /**
     * Reads a required environment variable. Throws when absent.
     *
     * @param key     - The variable name to look up.
     * @param options - Optional validation settings.
     * @returns The stored value as a guaranteed non-undefined string.
     * @throws {EnvAccessError} When the variable is missing or empty.
     * @throws {EnvStoreError} When called before store initialisation.
     *
     * @example
     * const dbUrl    = __sys__.__env__.getStrict("DATABASE_URL");
     * const jwtKey   = __sys__.__env__.getStrict("JWT_SECRET", { rejectEmpty: true });
     */
    getStrict(key: string, options?: EnvGetStrictOptions): string;
    /**
     * Returns `true` when the variable is present in the store, regardless of
     * its value (including empty strings).
     *
     * @throws {EnvStoreError} When called before store initialisation.
     *
     * @example
     * if (__sys__.__env__.has("SENTRY_DSN")) {
     *   Sentry.init({ dsn: __sys__.__env__.get("SENTRY_DSN") });
     * }
     */
    has(key: string): boolean;
    /**
     * Removes a variable from the secure internal store and from `process.env`.
     * Deleting a non-existent key is a no-op.
     *
     * @throws {EnvStoreError} When called before store initialisation.
     *
     * @example
     * __sys__.__env__.delete("CI_DEPLOY_TOKEN");
     */
    delete(key: string): void;
    /**
     * Returns a frozen, point-in-time snapshot of stored variables.
     *
     * Providing `options.keys` is strongly recommended in production to avoid
     * accidentally capturing secrets in logs or serialised payloads.
     *
     * @throws {EnvStoreError} When called before store initialisation.
     *
     * @example
     * const dbConfig = __sys__.__env__.all({
     *   keys: ["DATABASE_URL", "DATABASE_POOL_SIZE"],
     * });
     */
    all(options?: EnvAllOptions): EnvSnapshot;
    /** Returns `true` when the current execution mode is `"production"`. */
    isProduction(): boolean;
    /** Returns `true` when the current execution mode is `"development"`. */
    isDevelopment(): boolean;
    /** Returns `true` when the current execution mode is `"staging"`. */
    isStaging(): boolean;
    /** Returns `true` when the current execution mode is `"test"`. */
    isTest(): boolean;
    /**
     * Returns `true` when the execution mode matches `envName` exactly
     * (case-sensitive). Useful for custom environments beyond the four presets.
     *
     * @example
     * if (__sys__.__env__.is("canary")) {
     *   featureFlags.enableAll();
     * }
     */
    is(envName: string): boolean;
    /**
     * Returns the OS-level username of the process owner, resolved via the
     * XHSC native binary. Returns `""` on failure.
     *
     * @example
     * const actor = __sys__.__env__.user() || "<unknown>";
     * auditLog.write({ actor, action: "deploy" });
     */
    user(): string;
}

declare class EnvApi implements IEnvApi {
    readonly mode: string;
    private readonly runner;
    private readonly isDynamic;
    /**
     * Keys that may pass through the Shield to the real `process.env` without
     * restriction. Stored as a `Set` for O(1) lookup inside the Proxy trap.
     *
     * This list covers OS and Node.js internals required for system stability.
     * Application secrets must never be added here.
     */
    private readonly defaultWhitelist;
    private whitelistedFields;
    /**
     * @param runner - The XyPrissRunner used to invoke native Go binaries.
     * @param mode   - The execution mode. Defaults to `"development"`.
     * @param isDynamic - Whether this EnvApi should use dynamic project discovery (Sandboxing).
     */
    constructor(runner: XyPrissRunner, mode?: string, isDynamic?: boolean);
    /**
     * Writes a variable to the secure internal store.
     *
     * The key must be non-empty and must not consist solely of whitespace.
     * The value must not contain CR (`\r`), LF (`\n`), or NUL (`\0`) — these
     * characters can corrupt downstream parsers and log sinks.
     *
     * @param key   - Variable name.
     * @param value - Value to store.
     * @throws {EnvKeyError}   When the key or value fails validation.
     * @throws {EnvStoreError} When the store has not been initialised.
     *
     * @example
     * __sys__.__env__.set("MAINTENANCE_MODE", "true");
     *
     * const resolvedBase = resolveBaseUrl(config);
     * __sys__.__env__.set("APP_BASE_URL", resolvedBase);
     */
    set(key: string, value: string): void;
    /**
     * Removes a variable from the secure internal store and from `process.env`.
     * Deleting a key that does not exist is a no-op; no error is thrown.
     *
     * @param key - Variable name to remove.
     * @throws {EnvStoreError} When the store has not been initialised.
     *
     * @example
     * // Revoke a short-lived deployment credential immediately after use
     * __sys__.__env__.delete("CI_DEPLOY_TOKEN");
     */
    delete(key: string): void;
    /**
     * Reads a variable from the secure internal store.
     *
     * @param key          - Variable name to look up.
     * @param defaultValue - Fallback when the key is absent.
     * @returns The stored string, or `defaultValue` / `undefined`.
     * @throws {EnvStoreError} When the store has not been initialised.
     *
     * @example
     * // May return undefined — handle it explicitly
     * const region = __sys__.__env__.get("AWS_REGION");
     *
     * // Always returns a string when a default is provided
     * const timeout = __sys__.__env__.get("REQUEST_TIMEOUT_MS", "5000");
     * const ms = parseInt(timeout, 10);
     *
     * // Concise fallback with nullish coalescing
     * const logLevel = __sys__.__env__.get("LOG_LEVEL") ?? "info";
     */
    get(key: string): string | undefined;
    get(key: string, defaultValue: string): string;
    /**
     * Reads a variable from the secure internal store for a specific root.
     */
    getForRoot(key: string, root: string): string | undefined;
    /**
     * Reads a required variable from the secure internal store and throws if
     * it cannot be resolved.
     *
     * Use this method for every variable that is mandatory for application
     * correctness. It surfaces configuration errors at startup rather than
     * silently producing `undefined` at the point of use.
     *
     * @param key     - Variable name to look up.
     * @param options - Optional validation settings.
     * @returns The stored value, guaranteed non-undefined.
     * @throws {EnvAccessError} When the variable is missing or empty.
     * @throws {EnvStoreError}  When the store has not been initialised.
     *
     * @example
     * // Fail fast at boot if a critical variable is absent
     * const databaseUrl = __sys__.__env__.getStrict("DATABASE_URL");
     * const jwtSecret   = __sys__.__env__.getStrict("JWT_SECRET", { rejectEmpty: true });
     * const smtpHost    = __sys__.__env__.getStrict("SMTP_HOST");
     *
     * // Collect all required variables once at module initialisation
     * const config = {
     *   db:   __sys__.__env__.getStrict("DATABASE_URL"),
     *   jwt:  __sys__.__env__.getStrict("JWT_SECRET", { rejectEmpty: true }),
     *   smtp: __sys__.__env__.getStrict("SMTP_HOST"),
     * };
     */
    getStrict(key: string, options?: EnvGetStrictOptions): string;
    /**
     * Returns `true` when the given key is present in the secure internal
     * store, regardless of its value (including empty strings).
     *
     * @param key - Variable name to test.
     * @throws {EnvStoreError} When the store has not been initialised.
     *
     * @example
     * if (__sys__.__env__.has("SENTRY_DSN")) {
     *   Sentry.init({ dsn: __sys__.__env__.get("SENTRY_DSN") });
     * }
     *
     * const betaEnabled = __sys__.__env__.has("ENABLE_BETA_UI");
     */
    has(key: string): boolean;
    /**
     * Returns a frozen, point-in-time snapshot of stored variables.
     *
     * The object is frozen at the moment of the call; subsequent `set` or
     * `delete` calls do not affect it.
     *
     * Providing `options.keys` is strongly recommended in production code.
     * Returning the full store risks inadvertently capturing secrets in log
     * statements or JSON serialisations.
     *
     * @param options - Optional filter configuration.
     * @returns A frozen {@link EnvSnapshot}.
     * @throws {EnvStoreError} When the store has not been initialised.
     *
     * @example
     * // Filtered snapshot — preferred in all production code paths
     * const dbConfig = __sys__.__env__.all({
     *   keys: ["DATABASE_URL", "DATABASE_POOL_SIZE", "DATABASE_TIMEOUT_MS"],
     * });
     *
     * // Full snapshot — use only for diagnostics / startup validation
     * const full = __sys__.__env__.all();
     * logger.debug("Env snapshot", { count: Object.keys(full).length });
     */
    all(options?: EnvAllOptions): EnvSnapshot;
    /**
     * Returns `true` when the execution mode is `"production"`.
     *
     * @example
     * const logger = createLogger({
     *   level: __sys__.__env__.isProduction() ? "error" : "debug",
     * });
     */
    isProduction(): boolean;
    /**
     * Returns `true` when the execution mode is `"development"`.
     *
     * @example
     * if (__sys__.__env__.isDevelopment()) {
     *   app.use(requestLogger({ colorize: true }));
     * }
     */
    isDevelopment(): boolean;
    /**
     * Returns `true` when the execution mode is `"staging"`.
     *
     * @example
     * if (__sys__.__env__.isStaging()) {
     *   payment.useSandbox();
     * }
     */
    isStaging(): boolean;
    /**
     * Returns `true` when the execution mode is `"test"`.
     *
     * @example
     * const dbUrl = __sys__.__env__.isTest()
     *   ? __sys__.__env__.getStrict("TEST_DATABASE_URL")
     *   : __sys__.__env__.getStrict("DATABASE_URL");
     */
    isTest(): boolean;
    /**
     * Returns `true` when the execution mode exactly matches `envName`
     * (case-sensitive).
     *
     * @param envName - Mode name to compare against.
     *
     * @example
     * if (__sys__.__env__.is("canary")) {
     *   featureFlags.enableAll();
     * }
     */
    is(envName: string): boolean;
    /**
     * Configures the XESS (XyPriss Environment Security Shield) dynamically.
     *
     * @param config - XESS configuration options.
     */
    configureShield(config?: {
        whitelist?: string[];
        replaceDefaultWhitelist?: boolean;
    }): void;
    /**
     * Retrieves the OS-level username of the current process owner by invoking
     * the XHSC native Go binary.
     *
     * This method is synchronous and blocks until the native call completes.
     * Do not call it in request hot paths. Returns `""` on failure so callers
     * can safely use the result without null checks.
     *
     * @returns The current OS username, or `""` on failure.
     *
     * @example
     * const actor = __sys__.__env__.user() || "<unknown>";
     * auditLog.write({ actor, action: "deploy" });
     */
    user(): string;
    /**
     * Returns the internal store, throwing {@link EnvStoreError} if it has not
     * yet been initialised.
     *
     * SECURITY: This is the single point of store access. Every read and write
     * method must go through here — never access `globalThis[XY_ENV_STORE_KEY]`
     * directly outside this method.
     *
     * Eliminating the `?? process.env` fallback is intentional. A silent
     * fallback to `process.env` during the bootstrap race window would bypass
     * the Shield and leak values without any warning. A thrown error is
     * immediately visible during development and integration testing.
     *
     * @internal
     * @throws {EnvStoreError}
     */
    private requireStoreMap;
    private getStoreForCaller;
    /**
     * Asserts that `key` is a valid environment variable name.
     *
     * @internal
     * @throws {EnvKeyError}
     */
    private validateKey;
    /**
     * Asserts that `value` does not contain characters that can corrupt
     * downstream parsers, log sinks, or HTTP serialisers.
     *
     * Rejected characters:
     * - CR (`\r`) and LF (`\n`) — break line-oriented `.env` parsers and
     *   enable log injection attacks.
     * - NUL (`\0`) — truncates strings in C-based runtimes and can bypass
     *   suffix-based extension checks in some file path handling code.
     *
     * @internal
     * @throws {EnvKeyError}
     */
    private validateValue;
    /**
     * **Environment Security Shield**
     *
     * Replaces the `process.env` object with a hardened Proxy that enforces
     * the following policies on every property access:
     *
     * **Read trap**
     * - Whitelisted keys (see {@link EnvApi.whitelistedFields}) and keys
     *   matching the prefixes `XY_`, `XYPRISS_`, `ENC_`, `DOTENV_`, or `__`
     *   pass through to the real value.
     * - All other reads return `undefined`. A one-time per-key warning is
     *   written to `process.stderr` (suppressed when
     *   `XYPRISS_ENV_SHIELD=silent`).
     *
     * **`ownKeys` and `has` traps**
     * - Restrict the apparent key set to the whitelist. This prevents
     *   third-party code from enumerating the real store through
     *   `Object.keys(process.env)`, `JSON.stringify(process.env)`, or spread
     *   operators — all of which bypass the `get` trap.
     *
     * The descriptor is applied with `writable: false` to prevent replacement
     * by application code, and `configurable: true` to allow test teardown.
     *
     * @internal
     */
    /**
     * **Environment Security Shield**
     *
     * Replaces the `process.env` object with a hardened Proxy that enforces
     * the following policies on every property access:
     *
     * **Read trap**
     * - Whitelisted keys (see {@link EnvApi.whitelistedFields}) and keys
     *   matching the prefixes `XY_`, `XYPRISS_`, `ENC_`, `DOTENV_`, or `__`
     *   pass through to the real value.
     * - All other reads return `undefined`. A one-time per-key warning is
     *   written to `process.stderr` (suppressed when
     *   `XYPRISS_ENV_SHIELD=silent`).
     *
     * **`ownKeys` and `has` traps**
     * - Restrict the apparent key set to the whitelist. This prevents
     *   third-party code from enumerating the real store through
     *   `Object.keys(process.env)`, `JSON.stringify(process.env)`, or spread
     *   operators — all of which bypass the `get` trap.
     *
     * The descriptor is applied with `writable: false` to prevent replacement
     * by application code, and `configurable: true` to allow test teardown.
     *
     * @internal
     */
    private applyShield;
    private isCallerProjectCode;
}

/**
 * **StringUtils — XyPriss String Utilities**
 */
declare class StringUtils {
    /**
     * **Generate a Random String**
     *
     * Generates a pseudo-random character sequence of a specified length.
     * Uses alphanumeric characters (A-Z, a-z, 0-9).
     *
     * @param length - The desired length of the string (default: `10`).
     * @returns A random alphanumeric string.
     *
     * @example
     * ```ts
     * utils.randomString(8); // "a7B2k9Xz"
     * ```
     */
    randomString(length?: number): string;
    /**
     * **Slugify a String**
     *
     * Converts a string into a URL-friendly "slug" by lowering case,
     * removing non-alphanumeric characters, and replacing spaces with hyphens.
     *
     * @param text - The string to slugify.
     * @returns The URL-friendly slug.
     *
     * @example
     * ```ts
     * utils.slugify("Hello World!"); // "hello-world"
     * ```
     */
    slugify(text: string): string;
    /**
     * **Truncate a String**
     *
     * Shortens a string to a specified length and appends a suffix (default: `...`)
     * if the original string was longer than the limit.
     *
     * @param text      - The string to truncate.
     * @param maxLength - Maximum length including the suffix.
     * @param suffix    - The string to append (default: `"..."`).
     * @returns The truncated string.
     *
     * @example
     * ```ts
     * utils.truncate("Very long sentence", 10); // "Very lo..."
     * ```
     */
    truncate(text: string, maxLength: number, suffix?: string): string;
    /**
     * **Capitalize a String**
     *
     * Uppercases the first character of the string.
     *
     * @param text - The string to capitalize.
     * @returns The capitalized string.
     */
    capitalize(text: string): string;
    /**
     * **Convert to camelCase**
     *
     * Converts hyphen-separated, underscore-separated, or space-separated
     * strings into camelCase.
     *
     * @param text - The string to convert.
     * @returns The camelCase string.
     */
    toCamelCase(text: string): string;
    /**
     * **Pad a String**
     *
     * Adds padding characters to the start or end of a string until it
     * reaches the target length.
     *
     * @param text     - The source string.
     * @param length   - Target length.
     * @param char     - Padding character (default: `" "`).
     * @param position - Whether to pad at `"start"` or `"end"`.
     * @returns The padded string.
     */
    pad(text: string, length: number, char?: string, position?: "start" | "end"): string;
    /**
     * **Count Word/Substring Occurrences**
     *
     * Returns the number of times a specific word or substring appears.
     *
     * @param text          - The body of text to search.
     * @param word          - The substring to look for.
     * @param caseSensitive - Whether to respect case (default: `false`).
     * @returns The number of occurrences.
     */
    countOccurrences(text: string, word: string, caseSensitive?: boolean): number;
    /**
     * **toQueryString**
     *
     * Serializes a flat record into a URL-encoded query string format.
     *
     * @param params The object to serialize.
     * @returns The query string.
     */
    toQueryString(params: Record<string, unknown>): string;
}

/**
 * **NumberUtils — XyPriss Number & Math Utilities**
 */
declare class NumberUtils {
    /**
     * **Clamp a Value**
     *
     * Restricts a numeric value to a defined range [min, max].
     *
     * @param value - The value to clamp.
     * @param min   - The lower bound.
     * @param max   - The upper bound.
     * @returns The clamped value.
     */
    clamp(value: number, min: number, max: number): number;
    /**
     * **Linear Interpolation (LERP)**
     *
     * Returns the linear interpolation between `start` and `end` for a factor `t`.
     *
     * @param start - The start value.
     * @param end   - The end value.
     * @param t     - The interpolation factor (0.0 to 1.0).
     * @returns The interpolated value.
     */
    lerp(start: number, end: number, t: number): number;
    /**
     * **Get a Random Integer**
     *
     * Returns a random integer between min (inclusive) and max (inclusive).
     *
     * @param min - Minimum value.
     * @param max - Maximum value.
     * @returns A random integer.
     */
    randomInt(min: number, max: number): number;
    /**
     * **Format Number**
     *
     * Locale-aware number formatting.
     *
     * @param value   - The number to format.
     * @param locale  - Optional locale (default: `en-US`).
     * @param options - Intl.NumberFormatOptions.
     * @returns A localized string.
     */
    formatNumber(value: number, locale?: string, options?: Intl.NumberFormatOptions): string;
    /**
     * **Format Bytes**
     *
     * Converts raw bytes into a human-readable size string (KB, MB, GB, etc.).
     *
     * @param bytes    - The number of bytes.
     * @param decimals - Decimal precision.
     * @returns A human-readable size string.
     */
    formatBytes(bytes: number, decimals?: number): string;
}

/**
 * @file DateUtils.ts
 * @description XyPriss Date & Time Utilities — A comprehensive, zero-dependency
 * date/time utility class built on the native `Date` object and the `Intl` API.
 *
 * @remarks
 * All methods are pure and side-effect-free unless otherwise noted.
 * Timestamps can be provided in either **seconds** (Unix) or **milliseconds**
 * (JavaScript). The class auto-detects the unit using the heuristic:
 * values below `1e11` are treated as seconds; values at or above `1e11` are
 * treated as milliseconds. This heuristic is valid until **November 2286**.
 *
 * @example
 * ```ts
 * const du = new DateUtils();
 *
 * du.format(Date.now());            // "Apr 15, 2026"
 * du.timeAgo(Date.now() - 90_000); // "2 minutes ago"
 * du.formatDuration(3_661_000);    // "1h 1m 1s"
 * du.startOf("month");             // 2026-04-01T00:00:00.000Z
 * ```
 */
declare class DateUtils {
    /**
     * Converts any supported input value to a `Date` object.
     *
     * Supported inputs:
     * - `Date` — returned as-is (not cloned).
     * - `number` — auto-detected as Unix seconds (`< 1e11`) or milliseconds.
     * - `string` — parsed via `new Date(string)` (ISO 8601 recommended).
     *
     * @param date - The value to convert.
     * @returns The corresponding `Date` object.
     * @throws {RangeError} If the resulting `Date` is invalid.
     *
     * @internal
     */
    private toDate;
    /**
     * Converts any supported input value to a millisecond timestamp.
     *
     * @param date - The value to convert.
     * @returns Milliseconds since the Unix epoch.
     *
     * @internal
     */
    private toMs;
    /**
     * Returns the current Unix timestamp in **seconds**.
     *
     * @returns The current time as a Unix timestamp (integer seconds).
     *
     * @example
     * ```ts
     * du.now(); // e.g. 1776287197
     * ```
     */
    now(): number;
    /**
     * Returns the current time as a JavaScript timestamp in **milliseconds**.
     *
     * Equivalent to `Date.now()`.
     *
     * @returns The current time in milliseconds since the Unix epoch.
     *
     * @example
     * ```ts
     * du.nowMs(); // e.g. 1776287197000
     * ```
     */
    nowMs(): number;
    /**
     * Returns the current time as a `Date` object.
     *
     * @returns A new `Date` representing the current instant.
     *
     * @example
     * ```ts
     * du.today(); // Date { ... }
     * ```
     */
    today(): Date;
    /**
     * Serializes a date value into a localized string using `Intl.DateTimeFormat`.
     *
     * Automatically handles Unix timestamps (seconds) and JavaScript timestamps
     * (milliseconds) via the `< 1e11` heuristic.
     *
     * @param date    - The input to format: `Date`, number (timestamp), or ISO string.
     * @param locale  - BCP 47 locale tag (default: `"en-US"`).
     * @param options - `Intl.DateTimeFormatOptions` to customize the output.
     * @returns A localized date string.
     *
     * @example
     * ```ts
     * du.format(1776287197);
     * // → "Apr 15, 2026"
     *
     * du.format(new Date(), "fr-FR", { dateStyle: "full" });
     * // → "mercredi 15 avril 2026"
     *
     * du.format("2026-04-15T12:00:00Z", "en-GB", { timeStyle: "short" });
     * // → "12:00"
     * ```
     */
    format(date: Date | number | string, locale?: string, options?: Intl.DateTimeFormatOptions): string;
    /**
     * Formats a date as an ISO 8601 string (`YYYY-MM-DDTHH:mm:ss.sssZ`).
     *
     * This is the format recommended for data interchange and storage.
     *
     * @param date - The date to format (default: current time).
     * @returns An ISO 8601 UTC string.
     *
     * @example
     * ```ts
     * du.toISO();
     * // → "2026-04-15T10:30:00.000Z"
     *
     * du.toISO(1776287197);
     * // → "2026-04-15T..."
     * ```
     */
    toISO(date?: Date | number | string): string;
    /**
     * Formats a date as a plain date string: `YYYY-MM-DD`.
     *
     * The date is rendered in **local time** unless a UTC flag is set.
     *
     * @param date - The date to format (default: current time).
     * @param utc  - If `true`, use UTC date components instead of local time (default: `false`).
     * @returns A date-only string in `YYYY-MM-DD` format.
     *
     * @example
     * ```ts
     * du.toDateString();
     * // → "2026-04-15"
     *
     * du.toDateString(new Date("2026-12-31T23:59:00Z"), true);
     * // → "2026-12-31"
     * ```
     */
    toDateString(date?: Date | number | string, utc?: boolean): string;
    /**
     * Formats a date as a time string: `HH:mm:ss`.
     *
     * The time is rendered in **local time** unless the UTC flag is set.
     *
     * @param date - The date to format (default: current time).
     * @param utc  - If `true`, use UTC time components (default: `false`).
     * @returns A time-only string in `HH:mm:ss` format.
     *
     * @example
     * ```ts
     * du.toTimeString(new Date("2026-04-15T08:05:03Z"), true);
     * // → "08:05:03"
     * ```
     */
    toTimeString(date?: Date | number | string, utc?: boolean): string;
    /**
     * Converts a duration into a human-readable string (e.g., `"1d 2h 30m 5s"`).
     *
     * Components are omitted when their value is zero, except for seconds which
     * always appear when the total duration is less than one minute.
     *
     * @param value - The duration to format.
     * @param unit  - The unit of `value`: `"ms"` (milliseconds, default) or `"s"` (seconds).
     * @returns A compact, space-separated duration string.
     *
     * @example
     * ```ts
     * du.formatDuration(3_661_000);       // → "1h 1m 1s"
     * du.formatDuration(90, "s");         // → "1m 30s"
     * du.formatDuration(0);              // → "0s"
     * du.formatDuration(86_400_000);     // → "1d"
     * ```
     */
    formatDuration(value: number, unit?: "ms" | "s"): string;
    /**
     * Returns a relative time string (e.g., `"5 minutes ago"`, `"in 2 hours"`).
     *
     * Uses `Intl.RelativeTimeFormat` for locale-aware output. Automatically
     * selects the most appropriate unit (second → minute → hour → day → month → year).
     *
     * @param date   - The reference date, in the past or future.
     * @param locale - BCP 47 locale tag (default: `"en-US"`).
     * @returns A localized relative time string.
     *
     * @example
     * ```ts
     * du.timeAgo(Date.now() - 90_000);       // → "2 minutes ago"
     * du.timeAgo(Date.now() + 3_600_000);    // → "in 1 hour"
     * du.timeAgo(Date.now() - 90_000, "fr"); // → "il y a 2 minutes"
     * ```
     */
    timeAgo(date: Date | number | string, locale?: string): string;
    /**
     * Adds a given amount of time to a date and returns a new `Date`.
     *
     * Supported units: `"ms"`, `"s"` (seconds), `"m"` (minutes), `"h"` (hours),
     * `"d"` (days), `"w"` (weeks), `"mo"` (months), `"y"` (years).
     *
     * Month and year arithmetic is handled using `setMonth` / `setFullYear`,
     * which correctly accounts for varying month lengths (e.g., adding 1 month
     * to January 31 yields February 28/29).
     *
     * @param date  - The starting date.
     * @param value - The amount to add (can be negative to subtract).
     * @param unit  - The time unit.
     * @returns A new `Date` offset by the specified amount.
     *
     * @example
     * ```ts
     * du.add(new Date("2026-01-31"), 1, "mo");
     * // → Date("2026-02-28") — accounts for shorter February
     *
     * du.add(new Date("2026-04-15"), -7, "d");
     * // → Date("2026-04-08")
     *
     * du.add(Date.now(), 2, "h");
     * // → Date 2 hours from now
     * ```
     */
    add(date: Date | number | string, value: number, unit: "ms" | "s" | "m" | "h" | "d" | "w" | "mo" | "y"): Date;
    /**
     * Subtracts a given amount of time from a date and returns a new `Date`.
     *
     * This is a convenience wrapper around {@link add} with a negated `value`.
     *
     * @param date  - The starting date.
     * @param value - The amount to subtract (must be positive).
     * @param unit  - The time unit (same options as {@link add}).
     * @returns A new `Date` shifted back by the specified amount.
     *
     * @example
     * ```ts
     * du.subtract(new Date("2026-03-01"), 1, "mo");
     * // → Date("2026-02-01")
     * ```
     */
    subtract(date: Date | number | string, value: number, unit: "ms" | "s" | "m" | "h" | "d" | "w" | "mo" | "y"): Date;
    /**
     * Returns the difference between two dates in the specified unit.
     *
     * The result is the **signed** difference `(dateA - dateB)` truncated
     * toward zero. A positive value means `dateA` is later than `dateB`.
     *
     * Supported units: `"ms"`, `"s"`, `"m"`, `"h"`, `"d"`, `"w"`.
     * Month and year differences are intentionally excluded because their
     * variable length makes a lossless inverse impossible; use {@link add}
     * and calendar-aware logic for those cases.
     *
     * @param dateA - The first date.
     * @param dateB - The second date.
     * @param unit  - The unit for the result (default: `"ms"`).
     * @returns The signed integer difference in the requested unit.
     *
     * @example
     * ```ts
     * du.diff("2026-04-20", "2026-04-15", "d");  // → 5
     * du.diff("2026-04-10", "2026-04-15", "d");  // → -5
     * du.diff(Date.now(), Date.now() - 3600_000, "h"); // → 1
     * ```
     */
    diff(dateA: Date | number | string, dateB: Date | number | string, unit?: "ms" | "s" | "m" | "h" | "d" | "w"): number;
    /**
     * Returns `true` if `dateA` is strictly before `dateB`.
     *
     * @param dateA - The first date.
     * @param dateB - The second date.
     * @returns `true` if `dateA < dateB`.
     *
     * @example
     * ```ts
     * du.isBefore("2026-01-01", "2026-06-01"); // → true
     * ```
     */
    isBefore(dateA: Date | number | string, dateB: Date | number | string): boolean;
    /**
     * Returns `true` if `dateA` is strictly after `dateB`.
     *
     * @param dateA - The first date.
     * @param dateB - The second date.
     * @returns `true` if `dateA > dateB`.
     *
     * @example
     * ```ts
     * du.isAfter("2026-12-31", "2026-06-01"); // → true
     * ```
     */
    isAfter(dateA: Date | number | string, dateB: Date | number | string): boolean;
    /**
     * Returns `true` if two dates represent the same instant in time.
     *
     * Comparison is performed at millisecond precision.
     *
     * @param dateA - The first date.
     * @param dateB - The second date.
     * @returns `true` if both dates resolve to the same millisecond.
     *
     * @example
     * ```ts
     * du.isSame(new Date("2026-04-15"), 1776268800000); // → true (if same instant)
     * ```
     */
    isSame(dateA: Date | number | string, dateB: Date | number | string): boolean;
    /**
     * Returns `true` if `date` falls within the range `[start, end]` (inclusive).
     *
     * @param date  - The date to test.
     * @param start - The start of the range.
     * @param end   - The end of the range.
     * @returns `true` if `start ≤ date ≤ end`.
     *
     * @example
     * ```ts
     * du.isBetween("2026-04-15", "2026-01-01", "2026-12-31"); // → true
     * du.isBetween("2025-12-31", "2026-01-01", "2026-12-31"); // → false
     * ```
     */
    isBetween(date: Date | number | string, start: Date | number | string, end: Date | number | string): boolean;
    /**
     * Returns a new `Date` set to the **start** of the specified unit
     * (i.e., all smaller components zeroed out).
     *
     * Supported units: `"day"`, `"week"` (Monday = start), `"month"`, `"year"`.
     *
     * @param unit - The boundary unit.
     * @param date - The reference date (default: current time).
     * @returns A new `Date` at the beginning of the unit.
     *
     * @example
     * ```ts
     * du.startOf("day");
     * // → 2026-04-15T00:00:00.000 (local)
     *
     * du.startOf("month", new Date("2026-04-15"));
     * // → 2026-04-01T00:00:00.000
     *
     * du.startOf("year", "2026-06-15");
     * // → 2026-01-01T00:00:00.000
     * ```
     */
    startOf(unit: "day" | "week" | "month" | "year", date?: Date | number | string): Date;
    /**
     * Returns a new `Date` set to the **end** of the specified unit
     * (i.e., the last millisecond of that unit).
     *
     * Supported units: `"day"`, `"week"` (Sunday = end), `"month"`, `"year"`.
     *
     * @param unit - The boundary unit.
     * @param date - The reference date (default: current time).
     * @returns A new `Date` at the very last millisecond of the unit.
     *
     * @example
     * ```ts
     * du.endOf("month", new Date("2026-02-01"));
     * // → 2026-02-28T23:59:59.999
     *
     * du.endOf("year", "2026-01-01");
     * // → 2026-12-31T23:59:59.999
     * ```
     */
    endOf(unit: "day" | "week" | "month" | "year", date?: Date | number | string): Date;
    /**
     * Returns `true` if the given year is a leap year.
     *
     * A year is a leap year if it is divisible by 4, except for century years,
     * which must also be divisible by 400.
     *
     * @param year - The four-digit year to test (default: current year).
     * @returns `true` if the year is a leap year.
     *
     * @example
     * ```ts
     * du.isLeapYear(2024); // → true
     * du.isLeapYear(2100); // → false
     * du.isLeapYear(2000); // → true
     * ```
     */
    isLeapYear(year?: number): boolean;
    /**
     * Returns the number of days in a given month of a given year.
     *
     * Correctly accounts for leap years when querying February.
     *
     * @param month - The 1-based month index (1 = January, 12 = December).
     * @param year  - The four-digit year (default: current year).
     * @returns The number of days in the specified month (28–31).
     *
     * @example
     * ```ts
     * du.daysInMonth(2, 2024); // → 29  (leap year)
     * du.daysInMonth(2, 2023); // → 28
     * du.daysInMonth(1, 2026); // → 31
     * ```
     */
    daysInMonth(month: number, year?: number): number;
    /**
     * Returns the ISO 8601 week number (1–53) for a given date.
     *
     * ISO 8601 defines Week 1 as the week containing the year's first Thursday.
     * Weeks run Monday–Sunday. A date in early January may belong to the
     * final week of the previous year (e.g., January 1, 2016 → Week 53 of 2015).
     *
     * @param date - The reference date (default: current time).
     * @returns The ISO week number.
     *
     * @example
     * ```ts
     * du.weekNumber(new Date("2026-01-01")); // → 1
     * du.weekNumber(new Date("2016-01-03")); // → 53 (belongs to 2015)
     * ```
     */
    weekNumber(date?: Date | number | string): number;
    /**
     * Returns the day of the year (1–366) for a given date.
     *
     * @param date - The reference date (default: current time).
     * @returns An integer from 1 to 366.
     *
     * @example
     * ```ts
     * du.dayOfYear(new Date("2026-02-01")); // → 32
     * du.dayOfYear(new Date("2026-12-31")); // → 365
     * ```
     */
    dayOfYear(date?: Date | number | string): number;
    /**
     * Returns the ISO 8601 quarter (1–4) in which the given date falls.
     *
     * @param date - The reference date (default: current time).
     * @returns A quarter number: `1`, `2`, `3`, or `4`.
     *
     * @example
     * ```ts
     * du.quarter(new Date("2026-04-15")); // → 2  (Apr–Jun)
     * du.quarter(new Date("2026-11-01")); // → 4  (Oct–Dec)
     * ```
     */
    quarter(date?: Date | number | string): 1 | 2 | 3 | 4;
    /**
     * Returns `true` if the given date falls on a weekend (Saturday or Sunday).
     *
     * The check uses **local time**.
     *
     * @param date - The date to check (default: current time).
     * @returns `true` if the date is a Saturday or Sunday.
     *
     * @example
     * ```ts
     * du.isWeekend(new Date("2026-04-18")); // → true  (Saturday)
     * du.isWeekend(new Date("2026-04-15")); // → false (Wednesday)
     * ```
     */
    isWeekend(date?: Date | number | string): boolean;
    /**
     * Returns `true` if the given date falls on a weekday (Monday–Friday).
     *
     * @param date - The date to check (default: current time).
     * @returns `true` if the date is Monday through Friday.
     *
     * @example
     * ```ts
     * du.isWeekday(new Date("2026-04-15")); // → true
     * du.isWeekday(new Date("2026-04-19")); // → false (Sunday)
     * ```
     */
    isWeekday(date?: Date | number | string): boolean;
    /**
     * Returns `true` if two dates fall on the same calendar day (in local time).
     *
     * Only the year, month, and date components are compared; time is ignored.
     *
     * @param dateA - The first date.
     * @param dateB - The second date.
     * @returns `true` if both dates share the same year, month, and day.
     *
     * @example
     * ```ts
     * du.isSameDay("2026-04-15T08:00:00", "2026-04-15T22:00:00"); // → true
     * du.isSameDay("2026-04-15", "2026-04-16");                   // → false
     * ```
     */
    isSameDay(dateA: Date | number | string, dateB: Date | number | string): boolean;
    /**
     * Returns `true` if the given date is today (in local time).
     *
     * @param date - The date to test.
     * @returns `true` if `date` falls on the current calendar day.
     *
     * @example
     * ```ts
     * du.isToday(new Date()); // → true
     * du.isToday("2020-01-01"); // → false
     * ```
     */
    isToday(date: Date | number | string): boolean;
    /**
     * Returns `true` if the given date is in the past (before the current instant).
     *
     * @param date - The date to check.
     * @returns `true` if `date` is strictly before `Date.now()`.
     *
     * @example
     * ```ts
     * du.isPast("2020-01-01"); // → true
     * du.isPast(Date.now() + 1000); // → false
     * ```
     */
    isPast(date: Date | number | string): boolean;
    /**
     * Returns `true` if the given date is in the future (after the current instant).
     *
     * @param date - The date to check.
     * @returns `true` if `date` is strictly after `Date.now()`.
     *
     * @example
     * ```ts
     * du.isFuture(Date.now() + 5000); // → true
     * du.isFuture("2020-01-01");       // → false
     * ```
     */
    isFuture(date: Date | number | string): boolean;
    /**
     * Clamps a date to a `[min, max]` range.
     *
     * If `date` is before `min`, `min` is returned.
     * If `date` is after `max`, `max` is returned.
     * Otherwise, `date` is returned unchanged (as a new `Date`).
     *
     * @param date - The date to clamp.
     * @param min  - The lower bound.
     * @param max  - The upper bound.
     * @returns A new `Date` clamped within `[min, max]`.
     *
     * @example
     * ```ts
     * du.clamp("2025-01-01", "2026-01-01", "2026-12-31");
     * // → Date("2026-01-01")  — clamped to min
     *
     * du.clamp("2026-06-15", "2026-01-01", "2026-12-31");
     * // → Date("2026-06-15")  — within range, unchanged
     * ```
     */
    clamp(date: Date | number | string, min: Date | number | string, max: Date | number | string): Date;
    /**
     * Generates an array of `Date` objects representing each day in the range
     * `[start, end]`, inclusive.
     *
     * The range is capped at **3 650 days** (~10 years) to prevent accidental
     * allocation of enormous arrays.
     *
     * @param start - The first day of the range.
     * @param end   - The last day of the range.
     * @returns An ordered array of `Date` objects, one per day.
     * @throws {RangeError} If the range exceeds 3 650 days.
     *
     * @example
     * ```ts
     * du.dateRange("2026-04-13", "2026-04-15");
     * // → [Date("2026-04-13"), Date("2026-04-14"), Date("2026-04-15")]
     * ```
     */
    dateRange(start: Date | number | string, end: Date | number | string): Date[];
    /**
     * Returns `true` if the given value can be successfully interpreted
     * as a valid, finite date.
     *
     * Accepts `Date`, `number`, and `string` inputs. A `Date` whose
     * `getTime()` returns `NaN` is considered invalid.
     *
     * @param value - The value to validate.
     * @returns `true` if the value represents a valid date.
     *
     * @example
     * ```ts
     * du.isValid(new Date());           // → true
     * du.isValid("2026-04-15");         // → true
     * du.isValid("not-a-date");         // → false
     * du.isValid(new Date("invalid"));  // → false
     * du.isValid(NaN);                  // → false
     * ```
     */
    isValid(value: unknown): boolean;
    /**
     * Parses a date string using an ordered list of format patterns and returns
     * the first successfully parsed `Date`, or `null` if none match.
     *
     * Supported format tokens:
     * - `YYYY` — 4-digit year
     * - `MM`   — 2-digit month (01–12)
     * - `DD`   — 2-digit day (01–31)
     * - `HH`   — 2-digit hours (00–23)
     * - `mm`   — 2-digit minutes (00–59)
     * - `ss`   — 2-digit seconds (00–59)
     *
     * @param value   - The date string to parse.
     * @param formats - An ordered list of format strings to attempt.
     * @returns The first successfully parsed `Date`, or `null`.
     *
     * @example
     * ```ts
     * du.parse("15/04/2026", ["DD/MM/YYYY"]);
     * // → Date("2026-04-15")
     *
     * du.parse("2026-04-15 08:30:00", ["YYYY-MM-DD HH:mm:ss"]);
     * // → Date("2026-04-15T08:30:00")
     *
     * du.parse("bad-input", ["YYYY-MM-DD"]);
     * // → null
     * ```
     */
    parse(value: string, formats: string[]): Date | null;
    /**
     * Returns the UTC offset of the local environment in minutes.
     *
     * Positive values indicate zones **behind** UTC (e.g., UTC-5 → `300`),
     * mirroring the behaviour of `Date.prototype.getTimezoneOffset()`.
     *
     * @returns The UTC offset in minutes.
     *
     * @example
     * ```ts
     * du.timezoneOffset(); // → -120 for UTC+2, 300 for UTC-5
     * ```
     */
    timezoneOffset(): number;
    /**
     * Formats a date in a specific IANA timezone using `Intl.DateTimeFormat`.
     *
     * Requires the runtime to support the `timeZone` option (all modern
     * environments do).
     *
     * @param date     - The date to format.
     * @param timeZone - A valid IANA timezone identifier (e.g., `"America/New_York"`).
     * @param locale   - BCP 47 locale tag (default: `"en-US"`).
     * @param options  - Additional `Intl.DateTimeFormatOptions`.
     * @returns A localized date string in the given timezone.
     *
     * @example
     * ```ts
     * du.formatInTimezone(Date.now(), "Asia/Tokyo", "ja-JP", { dateStyle: "full", timeStyle: "short" });
     * // → "2026年4月15日水曜日 19:00"
     * ```
     */
    formatInTimezone(date: Date | number | string, timeZone: string, locale?: string, options?: Omit<Intl.DateTimeFormatOptions, "timeZone">): string;
}

/**
 * **ObjectUtils — XyPriss Object Utilities**
 */
declare class ObjectUtils {
    /**
     * **Deep Clone an Object**
     *
     * Creates a deep copy of `obj` using `XStringify` for serialization,
     * which handles cyclic references and offers better performance
     * than the native `JSON.stringify` in complex object graphs.
     *
     * @param obj - The object to clone. Must be serializable.
     * @returns A completely independent deep copy of the input object.
     *
     * @example
     * ```ts
     * const original = { a: 1, nested: { b: 2 } };
     * const clone = utils.deepClone(original);
     * clone.nested.b = 99;
     * // original.nested.b is still 2
     * ```
     */
    deepClone<T>(obj: T): T;
    /**
     * **Pick Specific Keys from an Object**
     *
     * Returns a new object containing only the key-value pairs whose
     * keys appear in the `keys` array. Non-existent keys are silently ignored.
     *
     * @param obj  - The source object.
     * @param keys - Array of keys to extract.
     * @returns A new object with only the specified keys.
     *
     * @example
     * ```ts
     * utils.pick({ a: 1, b: 2, c: 3 }, ["a", "c"]);   // { a: 1, c: 3 }
     * ```
     */
    pick<T extends object, K extends keyof T>(obj: T, keys: K[]): Pick<T, K>;
    /**
     * **Omit Specific Keys from an Object**
     *
     * Returns a new object that is a shallow copy of `obj` with the
     * specified keys removed.
     *
     * @param obj  - The source object.
     * @param keys - Array of keys to exclude.
     * @returns A new object without the specified keys.
     *
     * @example
     * ```ts
     * utils.omit({ a: 1, b: 2, c: 3 }, ["b"]);   // { a: 1, c: 3 }
     * ```
     */
    omit<T extends object, K extends keyof T>(obj: T, keys: K[]): Omit<T, K>;
    /**
     * **Check if an Object is Empty**
     *
     * Returns `true` if the object has no own enumerable keys.
     * Works correctly with objects created via `Object.create(null)`.
     *
     * @param obj - The object to inspect.
     * @returns `true` if the object has no own keys, `false` otherwise.
     *
     * @example
     * ```ts
     * utils.isEmpty({});             // true
     * utils.isEmpty({ a: 1 });       // false
     * utils.isEmpty(Object.create(null)); // true
     * ```
     */
    isEmpty(obj: object): boolean;
    /**
     * **flattenObject**
     *
     * Collapses nested objects into flat dot-notation (or custom) keys.
     * Useful for configuration mapping or CSV generation.
     *
     * @param obj - The object to flatten.
     * @param separator - Optional path separator (default: `"."`).
     * @returns A shallow object with path-based keys.
     */
    flattenObject(obj: Record<string, unknown>, separator?: string): Record<string, unknown>;
    /**
     * **parse**
     *
     * Safely parses a JSON string. If the parsing fails, the provided fallback
     * value is returned instead of throwing an exception.
     *
     * @param json The JSON string to parse.
     * @param fallback The fallback value to return on failure.
     * @returns The parsed object or the fallback value.
     */
    parse<T>(json: string, fallback?: T | null): T | null;
}

/**
 * **ArrayUtils — XyPriss Array Utilities**
 */
declare class ArrayUtils {
    /**
     * **Chunk an Array**
     *
     * Splits an array into sub-arrays of a fixed maximum size.
     */
    chunk<T>(arr: T[], size: number): T[][];
    /**
     * **Unique Elements**
     *
     * Returns a new array with all duplicates removed.
     */
    unique<T>(arr: T[]): T[];
    /**
     * **Shuffle Elements**
     *
     * Randomly reorders an array using the Fisher-Yates algorithm.
     */
    shuffle<T>(arr: T[]): T[];
    /**
     * **Group Elements**
     *
     * Groups array elements into an object based on a key-mapping function.
     */
    groupBy<T>(arr: T[], keyFn: (item: T) => string): Record<string, T[]>;
    /**
     * **Pick Random Sample**
     */
    sample<T>(arr: T[]): T | undefined;
    /**
     * **Flatten One Level**
     */
    flatten<T>(arr: T[][]): T[];
}

/**
 * # AsyncUtils — XyPriss Async Control Flow
 *
 * A comprehensive library of asynchronous control flow primitives for TypeScript.
 * Each method is designed to be safe, performant, and composable.
 *
 * @example
 * ```ts
 * const async = new AsyncUtils();
 *
 * // Auto-retry + debounce + performance measurement in a few lines
 * const save = async.debounce(async (data: string) => {
 *   const { result, durationMs } = await async.measure(() =>
 *     async.retry(() => api.save(data), { maxAttempts: 3, delay: 1000 })
 *   );
 *   console.log(`Saved in ${durationMs.toFixed(1)}ms`, result);
 * }, 500);
 * ```
 *
 * @module AsyncUtils
 */
/** Advanced options for {@link AsyncUtils.retry}. */
interface RetryOptions {
    /** Maximum number of attempts. @default 3 */
    maxAttempts?: number;
    /** Initial delay between attempts (ms). @default 500 */
    delay?: number;
    /** Multiplicative factor for the delay at each attempt (exponential backoff). @default 1 */
    backoffFactor?: number;
    /** Maximum delay regardless of backoff (ms). @default Infinity */
    maxDelay?: number;
    /** Abort signal allowing to interrupt attempts at any time. */
    signal?: AbortSignal;
    /**
     * Optional predicate — returns `true` if the error is "retryable".
     * Useful for not retrying a 400 or 401 error that won't change.
     *
     * @example
     * ```ts
     * retryIf: (err) => err instanceof NetworkError
     * ```
     */
    retryIf?: (error: unknown, attempt: number) => boolean;
    /**
     * Callback called at each failed attempt (ideal for telemetry).
     *
     * @example
     * ```ts
     * onRetry: (err, attempt) => logger.warn(`Attempt ${attempt} failed`, err)
     * ```
     */
    onRetry?: (error: unknown, attempt: number) => void;
}
/** Options for {@link AsyncUtils.timeout}. */
interface TimeoutOptions {
    /** Message of the error thrown in case of timeout. @default "Operation timed out" */
    message?: string;
    /** External signal allowing to cancel the promise before timeout. */
    signal?: AbortSignal;
}
/** Result of an execution via {@link AsyncUtils.measure}. */
interface MeasureResult<T> {
    result: T;
    /** Operation duration in milliseconds (µs precision via `performance.now()`). */
    durationMs: number;
}
/** Result of an execution via {@link AsyncUtils.attempt}. */
type AttemptResult<T> = {
    ok: true;
    value: T;
    error?: never;
} | {
    ok: false;
    error: unknown;
    value?: never;
};
declare class AsyncUtils {
    /**
     * ## Asynchronous Pause
     *
     * Suspends execution for a given duration.
     * Compatible with `AbortSignal`: sleep will be interrupted cleanly
     * if the signal is triggered (the promise **resolves** without error in this case).
     *
     * @param ms    - Pause duration in milliseconds.
     * @param signal - Optional cancellation signal (AbortController).
     * @returns A promise that resolves after `ms` ms (or earlier if signal triggered).
     *
     * @example Simple pause
     * ```ts
     * await utils.sleep(2000); // waits 2 seconds
     * ```
     *
     * @example Cancellation via AbortController
     * ```ts
     * const controller = new AbortController();
     * setTimeout(() => controller.abort(), 500);
     *
     * await utils.sleep(5000, controller.signal); // resolves after ~500ms
     * ```
     */
    sleep(ms: number, signal?: AbortSignal): Promise<void>;
    /**
     * ## Asynchronous Pause (alias of `sleep`)
     *
     * @alias sleep
     * @see {@link sleep}
     */
    wait(ms: number, signal?: AbortSignal): Promise<void>;
    /**
     * ## Retry with Exponential Backoff
     *
     * Retries an asynchronous operation up to `maxAttempts` times.
     * Supports exponential backoff, maximum delay, filter predicate,
     * and `AbortSignal` to interrupt the retry cycle.
     *
     * Delay formula: `min(delay × backoffFactor^attempt, maxDelay)`.
     *
     * @param fn      - The asynchronous function to execute.
     * @param options - Retry options (see {@link RetryOptions}).
     * @returns Resolved value of `fn` on the first successful attempt.
     * @throws Last error if all attempts fail.
     *
     * @example Basic retry (3 attempts, 500ms between each)
     * ```ts
     * const data = await utils.retry(() => fetch("/api/data").then(r => r.json()));
     * ```
     *
     * @example Exponential backoff: 200ms → 400ms → 800ms → max 1000ms
     * ```ts
     * const result = await utils.retry(() => unstableApi(), {
     *   maxAttempts: 4,
     *   delay: 200,
     *   backoffFactor: 2,
     *   maxDelay: 1000,
     *   onRetry: (err, n) => console.warn(`Retry #${n}`, err),
     * });
     * ```
     *
     * @example Do not retry auth errors
     * ```ts
     * await utils.retry(() => api.call(), {
     *   retryIf: (err) => !(err instanceof AuthError),
     * });
     * ```
     */
    retry<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T>;
    /**
     * ## Promise Timeout
     *
     * Wraps a promise with a maximum duration. If the promise does not
     * resolve within the given time, an `Error` is thrown.
     *
     * Automatically handles internal timer cleanup to prevent memory leaks.
     *
     * @param fn      - Function returning the promise to monitor.
     * @param ms      - Maximum delay in milliseconds before rejecting.
     * @param options - Additional options (error message, cancellation signal).
     * @returns Resolved value if the promise succeeds within delay.
     * @throws `Error` with `options.message` if timeout is reached.
     *
     * @example
     * ```ts
     * const result = await utils.timeout(
     *   () => fetch("/slow-api").then(r => r.json()),
     *   3000,
     *   { message: "API took too long to respond" }
     * );
     * ```
     */
    timeout<T>(fn: () => Promise<T>, ms: number, options?: TimeoutOptions): Promise<T>;
    /**
     * ## Safe Execution (Never Throws)
     *
     * Executes an asynchronous function and always captures the result as a
     * discriminated object `{ ok, value }` or `{ ok, error }`.
     * **Never throws exceptions**, simplifying control flow.
     *
     * Ideal for API calls, parsing, or any operation where failure is a normal outcome
     * and must be handled explicitly.
     *
     * @param fn - Asynchronous function to execute safely.
     * @returns Discriminated object indicating success or failure.
     *
     * @example Without `attempt` (verbose)
     * ```ts
     * let user;
     * try { user = await fetchUser(id); }
     * catch (e) { console.error(e); return; }
     * ```
     *
     * @example With `attempt` (concise)
     * ```ts
     * const { ok, value: user, error } = await utils.attempt(() => fetchUser(id));
     * if (!ok) { console.error(error); return; }
     * // `user` is guaranteed defined here
     * ```
     *
     * @example Combined with `retry`
     * ```ts
     * const { ok, value } = await utils.attempt(() =>
     *   utils.retry(() => api.getData(), { maxAttempts: 5 })
     * );
     * ```
     */
    attempt<T>(fn: () => Promise<T>): Promise<AttemptResult<T>>;
    /**
     * ## Debounce
     *
     * Delays execution of `fn` until `wait` ms have elapsed since the last call.
     * If a new call arrives before the delay ends, the previous one is cancelled
     * and the timer restarts from zero.
     *
     * Typical use cases: search fields (prevents one request per keystroke),
     * resize listeners, auto-save.
     *
     * The returned version exposes a `.cancel()` method to manually cancel the
     * pending timer, and `.flush()` to trigger execution immediately.
     *
     * @param fn   - Function to debounce.
     * @param wait - Quiet period required before execution (ms). @default 300
     * @returns Debounced version of `fn` with `.cancel()` and `.flush()` methods.
     *
     * @example Real-time search
     * ```ts
     * const search = utils.debounce((query: string) => {
     *   fetch(`/api/search?q=${query}`);
     * }, 400);
     *
     * input.addEventListener("input", (e) => search(e.target.value));
     * ```
     *
     * @example Explicit cancellation (e.g., on component unmount)
     * ```ts
     * const save = utils.debounce(saveToServer, 1000);
     * onUnmount(() => save.cancel());
     * ```
     *
     * @example Immediate flush (e.g., before navigation)
     * ```ts
     * window.addEventListener("beforeunload", () => save.flush());
     * ```
     */
    debounce<T extends (...args: any[]) => any>(fn: T, wait?: number): ((...args: Parameters<T>) => void) & {
        cancel: () => void;
        flush: (...args: Parameters<T>) => void;
    };
    /**
     * ## Throttle
     *
     * Guarantees that `fn` executes no more than once per `limit` ms window,
     * regardless of how many calls are received.
     *
     * Unlike debounce, throttle executes `fn` **immediately** on the first call,
     * then ignores subsequent calls until the window ends.
     *
     * Typical use cases: scroll handlers, mousemove, drag-and-drop, gamepads.
     *
     * The returned version exposes a `.cancel()` method to manually reset the
     * throttle window.
     *
     * @param fn    - Function to throttle.
     * @param limit - Minimum duration between two executions (ms). @default 300
     * @returns Throttled version of `fn` with `.cancel()` method.
     *
     * @example Scroll handler limited to 60fps (~16ms)
     * ```ts
     * const onScroll = utils.throttle(() => {
     *   updateScrollIndicator();
     * }, 16);
     *
     * window.addEventListener("scroll", onScroll);
     * ```
     */
    throttle<T extends (...args: any[]) => any>(fn: T, limit?: number): ((...args: Parameters<T>) => void) & {
        cancel: () => void;
    };
    /**
     * ## High-Precision Execution Time Measurement
     *
     * Wraps a synchronous or asynchronous function and returns its result
     * along with its execution time in milliseconds (microsecond precision via `performance.now()`).
     *
     * @param fn - Function to measure (sync or async).
     * @returns An object `{ result, durationMs }`.
     *
     * @example Measuring an API call
     * ```ts
     * const { result, durationMs } = await utils.measure(() =>
     *   fetch("/api/heavy").then(r => r.json())
     * );
     * console.log(`Response received in ${durationMs.toFixed(2)}ms:`, result);
     * ```
     */
    measure<T>(fn: () => T | Promise<T>): Promise<MeasureResult<T>>;
    /**
     * ## High-Precision Drift-Corrected Interval
     *
     * Repeatedly executes `fn` with automatic compensation for accumulated
     * clock drift. Unlike `setInterval`, this implementation adjusts each delay
     * based on actual elapsed time.
     *
     * The current tick count is passed as a parameter to `fn`, enabling
     * animations or progression counting.
     *
     * Execution stops cleanly when `signal` is aborted.
     *
     * @param fn     - Callback called at each tick, receiving the tick index (0-indexed).
     * @param ms     - Target interval in milliseconds.
     * @param signal - `AbortSignal` to stop the loop.
     * @returns A promise that resolves when the signal is aborted.
     *
     * @example Counter update every second
     * ```ts
     * const controller = new AbortController();
     *
     * utils.repeat((tick) => {
     *   console.log(`Tick ${tick} — ${new Date().toLocaleTimeString()}`);
     * }, 1000, controller.signal);
     *
     * // Stop after 5 seconds
     * setTimeout(() => controller.abort(), 5000);
     * ```
     */
    repeat(fn: (tick: number) => void | Promise<void>, ms: number, signal?: AbortSignal): Promise<void>;
    /**
     * ## Parallel Execution with Limited Concurrency
     *
     * Processes an array of values in parallel via `fn`, limiting the number
     * of active promises simultaneously to `concurrency`. Results are returned
     * in the same order as inputs.
     *
     * Ideal for scenarios where you want to avoid saturating a server or database
     * with thousands of simultaneous requests.
     *
     * @param items       - Array of items to process.
     * @param fn          - Asynchronous function applied to each element.
     * @param concurrency - Maximum number of active parallel promises. @default 5
     * @returns Array of results in the same order as `items`.
     *
     * @example Batch file import (max 3 at a time)
     * ```ts
     * const files = ["f1.csv", "f2.csv", "f3.csv", "f4.csv"];
     * const results = await utils.pool(files, f => importFile(f), 3);
     * ```
     */
    pool<T, R>(items: T[], fn: (item: T, index: number) => Promise<R>, concurrency?: number): Promise<R[]>;
    /**
     * ## Race with Built-in Timeout
     *
     * Launches multiple promises in parallel and returns the first one to resolve.
     * If none resolve within `timeoutMs`, an error is thrown.
     *
     * Similar to `Promise.race`, but with an integrated temporal safety net.
     *
     * @param fns       - Array of functions returning promises.
     * @param timeoutMs - Maximum delay in milliseconds. @default Infinity
     * @returns Value of the first resolved promise.
     * @throws `Error("Race timed out")` if timeout is reached.
     */
    race<T>(fns: Array<() => Promise<T>>, timeoutMs?: number): Promise<T>;
    /**
     * ## Async Memoization with TTL
     *
     * Returns a memoized version of `fn`: results are cached for `ttlMs` milliseconds.
     * After this delay, the next call triggers a fresh execution.
     *
     * If multiple identical calls arrive simultaneously (while the promise is pending),
     * they share the same promise — avoiding "thundering herd" on cold caches.
     *
     * @param fn    - Asynchronous function to memoize.
     * @param ttlMs - Cache entry TTL (ms). `0` = no expiration.
     * @param keyFn - Serialization function for arguments into cache keys.
     *                @default `JSON.stringify`
     * @returns Memoized version of `fn` with `.clear()` method.
     */
    memoize<TArgs extends any[], TResult>(fn: (...args: TArgs) => Promise<TResult>, ttlMs?: number, keyFn?: (...args: TArgs) => string): ((...args: TArgs) => Promise<TResult>) & {
        clear: () => void;
    };
    /**
     * ## Sequential Queue
     *
     * Guarantees that tasks are executed **one by one, in the order they were added**.
     * Tasks submitted while another is pending are queued and executed sequentially.
     *
     * Unlike `pool(items, fn, 1)`, `queue` allows adding tasks dynamically over time.
     *
     * @returns An object `{ add, size }`:
     *   - `add(fn)` — Enqueues a task and returns a promise for its result.
     *   - `size` — Getter for the current number of pending tasks.
     *
     * @example Critical Database Mutation
     * ```ts
     * const db = utils.queue();
     *
     * async function transfer(from: string, to: string, amount: number) {
     *   return db.add(async () => {
     *     const balance = await getBalance(from);
     *     if (balance < amount) throw new Error("Insufficient funds");
     *     await debit(from, amount);
     *     await credit(to, amount);
     *   });
     * }
     * ```
     */
    queue(): {
        add: <T>(fn: () => Promise<T>) => Promise<T>;
        readonly size: number;
    };
    /**
     * ## Once — Guaranteed Single Execution
     *
     * Returns a version of `fn` that executes only **once**, regardless of how
     * many calls are made. Subsequent calls receive the cached promise or value
     * without re-executing `fn`.
     *
     * Particularly useful for expensive initializations (DB connections, config loading).
     *
     * @param fn - The function to execute exactly once.
     * @returns A function that always returns the same resolved promise.
     */
    once<TArgs extends any[], TResult>(fn: (...args: TArgs) => Promise<TResult>): (...args: TArgs) => Promise<TResult>;
    /**
     * ## Conditional Polling
     *
     * Repeatedly polls `fn` until `predicate` returns `true` or a signal is aborted.
     *
     * @param fn        - Asynchronous function returning value to test.
     * @param predicate - Success condition for the returned value.
     * @param interval  - Delay between attempts (ms). @default 1000
     * @param signal    - `AbortSignal` to stop polling.
     * @returns The value for which `predicate` returned `true`.
     * @throws `DOMException("AbortError")` if signal is aborted before success.
     */
    poll<T>(fn: () => Promise<T>, predicate: (value: T) => boolean, interval?: number, signal?: AbortSignal): Promise<T>;
}

/**
 * **ValidationUtils — XyPriss Validation Utilities**
 */
declare class ValidationUtils {
    /**
     * **email**
     *
     * Performs semantic validation on an email address string.
     *
     * @param email The email string to validate.
     * @returns `true` if valid, `false` otherwise.
     */
    email(email: string): boolean;
    /**
     * **url**
     *
     * Validates a URL string using the `strulink` RFC-compliant URI parser.
     *
     * @param url The URL string to validate.
     * @returns `true` if valid, `false` otherwise.
     */
    url(url: string | URL): boolean;
    /**
     * **nullish**
     *
     * A type guard that determines if a value is either `null` or `undefined`.
     *
     * @param value The value to check.
     * @returns `true` if null or undefined.
     */
    nullish(value: unknown): value is null | undefined;
}

/**
 * **IdUtils — Identity Primitives**
 */
declare class IdUtils {
    /**
     * **uuid**
     *
     * Generates a RFC-compliant UUID v4 using the `nehoid` engine.
     *
     * @returns A random UUID string.
     */
    uuid(): string;
}

/**
 * **FunctionUtils — Functional Programming Helpers**
 */
declare class FunctionUtils {
    /**
     * **memo**
     *
     * Returns a memoized version of a function that caches its results based on input parameters.
     *
     * @param fn The function to memoize.
     * @returns The memoized function.
     */
    memo<T extends (...args: any[]) => any>(fn: T): T;
}

/***************************************************************************
 * XyPrissJS - Fast And Secure
 *
 * @author Nehonix
 * @license Nehonix OSL (NOSL)
 *
 * Copyright (c) 2025 Nehonix. All rights reserved.
 ***************************************************************************** */
/**
 * All supported log levels, ordered by increasing severity.
 *
 * | Level     | Rank | Use case                                              |
 * |-----------|------|-------------------------------------------------------|
 * | `debug`   | 0    | Low-level diagnostic traces, dev-only                 |
 * | `info`    | 1    | General operational messages                          |
 * | `success` | 2    | Confirmation that an operation completed successfully |
 * | `warn`    | 3    | Non-fatal issues that deserve attention               |
 * | `error`   | 4    | Recoverable failures — operation did not complete     |
 * | `fatal`   | 5    | Unrecoverable failures — system integrity at risk     |
 *
 * Used as the `minLevel` option to silence everything below a given rank.
 *
 * @example
 * ```ts
 * const log = new LoggerUtils({ minLevel: "warn" });
 * // → only "warn", "error", and "fatal" are printed
 * ```
 */
type LogLevel = "debug" | "info" | "success" | "warn" | "error" | "fatal";
/**
 * Configuration options accepted by the {@link LoggerUtils} constructor.
 *
 * All fields are optional — the logger works out of the box with zero config.
 *
 * @example
 * ```ts
 * // Minimal — global logger, all levels visible, ANSI colors on
 * new LoggerUtils();
 *
 * // Scoped production logger — only warnings and above, no colors
 * new LoggerUtils({ namespace: "API", minLevel: "warn", plain: true });
 *
 * // Dev logger with timestamps disabled (cleaner for rapid iteration)
 * new LoggerUtils({ namespace: "Dev", timestamps: false });
 * ```
 */
interface LoggerOptions {
    /**
     * A short label prepended to every log line, rendered in bold cyan.
     *
     * Namespaces are composable: {@link LoggerUtils.child} automatically
     * concatenates parent and child names with a colon separator.
     *
     * @example
     * ```ts
     * new LoggerUtils({ namespace: "DB" });
     * // output → ... [DB] Connected to postgres
     *
     * const child = log.child("Pool");
     * // output → ... [DB:Pool] Acquired connection
     * ```
     *
     * @default "" (no prefix)
     */
    namespace?: string;
    /**
     * The lowest {@link LogLevel} that will be printed.
     * Any level with a lower rank is silently discarded.
     *
     * Typical environment presets:
     * - Development → `"debug"` (see everything)
     * - Staging     → `"info"`  (skip debug noise)
     * - Production  → `"warn"`  (only actionable signals)
     *
     * @example
     * ```ts
     * const log = new LoggerUtils({ minLevel: "info" });
     * log.debug("Verbose trace"); // ← silently dropped
     * log.info("User signed in"); // ← printed ✔
     * ```
     *
     * @default "debug"
     */
    minLevel?: LogLevel;
    /**
     * When `true`, each line is prefixed with a full `YYYY-MM-DD HH:mm:ss.mmm`
     * timestamp, which helps correlate logs with external events or other systems.
     *
     * Disable when timestamps are added by an outer log aggregator (e.g. Docker,
     * systemd, Datadog) to avoid duplication.
     *
     * @example
     * ```ts
     * new LoggerUtils({ timestamps: false });
     * // output → [INFO] ℹ️  [App] Server started
     * //        (no date prefix)
     * ```
     *
     * @default true
     */
    timestamps?: boolean;
    /**
     * When `true`, all ANSI escape codes (colors, bold, dim) are stripped from
     * the output, producing clean plain text.
     *
     * Recommended for:
     * - CI environments (GitHub Actions, GitLab CI, Jenkins)
     * - Log files that will be processed by grep / awk / sed
     * - Terminals that do not support ANSI (some Windows consoles)
     *
     * @example
     * ```ts
     * const log = new LoggerUtils({ plain: true });
     * log.warn("Disk usage high");
     * // output → [2025-06-01 12:00:00.000] [WARN] ⚠️  Disk usage high
     * ```
     *
     * @default false
     */
    plain?: boolean;
}
/**
 * **LoggerUtils** — Structured, colorful console logger for XyPriss.
 *
 * Provides six severity levels, ANSI-colored output, optional namespacing,
 * child loggers, execution timers, and visual log groups — all with zero
 * external dependencies.
 *
 * ---
 *
 * ### Quick start
 * ```ts
 * // Global logger — no configuration needed
 * const log = new LoggerUtils();
 * log.info("App started");
 *
 * // Scoped logger — namespace visible in every line
 * const log = new LoggerUtils({ namespace: "Auth", minLevel: "info" });
 * log.success("User authenticated", { userId: "u_42" });
 * ```
 *
 * ### Log levels (low → high severity)
 * ```ts
 * log.debug("Verbose trace");                          // 🔍 dev-only
 * log.info("Server listening", { port: 3000 });        // ℹ️  general
 * log.success("Migration complete");                   // ✅ confirmation
 * log.warn("Rate limit at 90%", { remaining: 10 });    // ⚠️  attention needed
 * log.error("Payment failed", new Error("Timeout"));   // ❌ recoverable
 * log.fatal("DB unreachable — aborting");              // 💀 unrecoverable
 * ```
 *
 * ### Advanced features
 * ```ts
 * // ── Execution timer
 * const stop = log.time("Fetch users");
 * await fetchUsers();
 * stop(); // → ✅ [Auth] Fetch users — 38 ms
 *
 * // ── Visual group
 * log.group("Bootstrap", () => {
 *   log.info("Loading config");
 *   log.info("Connecting to DB");
 * });
 *
 * // ── Child logger (inherits namespace + options)
 * const dbLog = log.child("DB"); // namespace → "Auth:DB"
 * dbLog.debug("Query plan", { sql: "SELECT ..." });
 *
 * // ── CI / plain-text mode
 * const ciLog = new LoggerUtils({ plain: true });
 * ```
 */
declare class LoggerUtils {
    private readonly ns;
    private readonly minRank;
    private readonly timestamps;
    private readonly plain;
    /**
     * Create a new `LoggerUtils` instance.
     *
     * All options are optional — calling `new LoggerUtils()` produces a ready-to-use
     * global logger that prints every level with ANSI colors and timestamps.
     *
     * @param opts - {@link LoggerOptions} configuration bag.
     *
     * @example
     * ```ts
     * // Zero-config global logger
     * const log = new LoggerUtils();
     *
     * // Namespaced, production-safe logger
     * const log = new LoggerUtils({
     *   namespace:  "PaymentService",
     *   minLevel:   "warn",
     *   timestamps: true,
     *   plain:      false,
     * });
     * ```
     */
    constructor(opts?: LoggerOptions);
    private emit;
    private buildAnsi;
    private buildPlain;
    /**
     * Print a **debug** message — rank 0, lowest severity.
     *
     * Use for low-level diagnostic traces that are too noisy for production:
     * variable states, iteration counters, internal decisions.
     * Silenced whenever `minLevel` is set to `"info"` or above.
     *
     * Output style: `🔍` icon · gray message text · cyan `DEBUG` badge.
     *
     * @param message - Human-readable description of what is being traced.
     * @param extra   - Any additional values to print after the message.
     *                  Objects are pretty-printed as indented JSON.
     *                  `Error` instances show the full stack trace.
     *
     * @example
     * ```ts
     * log.debug("Cache miss — fetching from DB", { key: "user:42" });
     * log.debug("Loop iteration", { index: i, total: arr.length });
     * ```
     */
    debug(message: string, ...extra: unknown[]): void;
    /**
     * Print an **info** message — rank 1.
     *
     * Use for general operational milestones that are always relevant:
     * server start, feature flags loaded, scheduled job triggered.
     * Visible unless `minLevel` is set to `"success"` or above.
     *
     * Output style: `ℹ️` icon · white message text · blue `INFO` badge.
     *
     * @param message - A concise description of the event.
     * @param extra   - Optional context values (objects, primitives, Errors).
     *
     * @example
     * ```ts
     * log.info("HTTP server listening", { port: 3000, env: "production" });
     * log.info("Feature flag enabled", { flag: "new-checkout-flow" });
     * ```
     */
    info(message: string, ...extra: unknown[]): void;
    /**
     * Print a **success** message — rank 2.
     *
     * Use to confirm that an operation completed as expected:
     * migration applied, file uploaded, payment processed.
     *
     * Output style: `✅` icon · green message text · green `OK` badge.
     *
     * @param message - What succeeded.
     * @param extra   - Optional result details or metadata.
     *
     * @example
     * ```ts
     * log.success("User authenticated", { userId: "u_42", method: "OAuth" });
     * log.success("Email delivered", { to: "user@example.com", messageId: "msg_7" });
     * ```
     */
    success(message: string, ...extra: unknown[]): void;
    /**
     * Print a **warn** message — rank 3.
     *
     * Use for non-fatal anomalies that should be investigated but do not
     * stop the current operation: deprecated API usage, high latency,
     * approaching a quota limit, missing optional configuration.
     *
     * Routes to `console.warn` so it appears in the Warnings channel of
     * browser DevTools and some log aggregators.
     *
     * Output style: `⚠️` icon · yellow message text · yellow `WARN` badge.
     *
     * @param message - What is concerning and why.
     * @param extra   - Any relevant context (thresholds, current values, etc.).
     *
     * @example
     * ```ts
     * log.warn("Memory usage above 80%", { usedMb: 820, limitMb: 1024 });
     * log.warn("Deprecated endpoint called", { path: "/v1/users", caller: req.ip });
     * ```
     */
    warn(message: string, ...extra: unknown[]): void;
    /**
     * Print an **error** message — rank 4.
     *
     * Use when an operation has failed but the system can continue running:
     * a failed HTTP request, a rejected promise, an unexpected null value.
     * Always pass the originating `Error` object as an extra argument so the
     * stack trace is preserved in the output.
     *
     * Routes to `console.error`.
     *
     * Output style: `❌` icon · red message text · red `ERROR` badge.
     *
     * @param message - What failed.
     * @param extra   - The originating `Error` and/or contextual metadata.
     *
     * @example
     * ```ts
     * try {
     *   await db.query(sql);
     * } catch (err) {
     *   log.error("Query execution failed", err, { sql, params });
     * }
     *
     * log.error("Stripe charge rejected", { code: "card_declined", userId: "u_7" });
     * ```
     */
    error(message: string, ...extra: unknown[]): void;
    /**
     * Print a **fatal** message — rank 5, highest severity.
     *
     * Use when the system has entered an unrecoverable state and must halt:
     * database unreachable at startup, a required secret missing, an invariant
     * violated that makes further execution unsafe.
     *
     * After calling `fatal`, you should typically terminate the process
     * (`process.exit(1)`) or trigger a circuit-breaker.
     *
     * Routes to `console.error`.
     *
     * Output style: `💀` icon · magenta message text · magenta `FATAL` badge.
     *
     * @param message - What went wrong and why it is unrecoverable.
     * @param extra   - The originating `Error` and/or diagnostic context.
     *
     * @example
     * ```ts
     * if (!process.env.DATABASE_URL) {
     *   log.fatal("DATABASE_URL is not set — cannot start", { env: process.env.NODE_ENV });
     *   process.exit(1);
     * }
     *
     * process.on("uncaughtException", (err) => {
     *   log.fatal("Uncaught exception — shutting down", err);
     *   process.exit(1);
     * });
     * ```
     */
    fatal(message: string, ...extra: unknown[]): void;
    /**
     * Start a high-resolution execution timer and return a **stop function**.
     *
     * Call the stop function when the measured work is done; it logs a
     * {@link success} line with the elapsed time in milliseconds (2 decimal places).
     *
     * Internally uses `performance.now()` for sub-millisecond precision.
     *
     * > **Tip:** the stop function can be called multiple times — each call
     * > measures from the original `time()` invocation, so it doubles as a
     * > checkpoint logger.
     *
     * @param label - A short description of the operation being timed.
     *                Shown verbatim in the success message.
     * @returns A zero-argument function that stops the timer and emits the result.
     *
     * @example
     * ```ts
     * // Async operation
     * const stop = log.time("Fetch user profile");
     * const user = await userService.getById(id);
     * stop(); // ✅ [Auth] Fetch user profile — 42.31 ms
     *
     * // Sync operation
     * const stop = log.time("Parse config");
     * const cfg = JSON.parse(raw);
     * stop(); // ✅ Parse config — 0.18 ms
     *
     * // Checkpoint pattern
     * const stop = log.time("DB seed");
     * await insertUsers(users);
     * stop(); // ✅ DB seed — 120 ms  (users done)
     * await insertPosts(posts);
     * stop(); // ✅ DB seed — 380 ms  (total, from start)
     * ```
     */
    time(label: string): () => void;
    /**
     * Wrap a synchronous callback in a **visually separated log group**.
     *
     * Prints a labeled divider line before and a closing divider after the
     * callback, making it easy to visually isolate related log output (e.g.
     * a startup sequence, a batch job, a request lifecycle).
     *
     * > **Note:** this method is synchronous. For async callbacks, await the
     * > work inside the callback and let the outer caller handle the promise:
     * > ```ts
     * > log.group("Init", () => { /* sync logs only *\/ });
     * > // For async: manually print dividers with log.spacer() instead.
     * > ```
     *
     * @param label - Title shown in the opening divider.
     * @param fn    - Synchronous callback containing the grouped log calls.
     *
     * @example
     * ```ts
     * log.group("Bootstrap", () => {
     *   log.info("Loading environment variables");
     *   log.info("Connecting to PostgreSQL");
     *   log.success("All systems ready");
     * });
     * // ── Bootstrap ────────────────────────────────
     * // ℹ️  Loading environment variables
     * // ℹ️  Connecting to PostgreSQL
     * // ✅ All systems ready
     * // ────────────────────────────────────────────
     *
     * // Nested groups are supported
     * log.group("DB", () => {
     *   log.group("Migrations", () => {
     *     log.success("Applied 3 migrations");
     *   });
     *   log.info("Seeding complete");
     * });
     * ```
     */
    group(label: string, fn: () => void): void;
    /**
     * Create a **child logger** that inherits all options from this instance
     * but appends `subNamespace` to the current namespace with a `:` separator.
     *
     * Child loggers are useful for module or layer-level scoping without
     * repeating configuration. The parent's `minLevel`, `timestamps`, and
     * `plain` settings are all propagated automatically.
     *
     * Namespaces are composed as `"<parent>:<child>"`. Nesting is unlimited:
     * `App → App:DB → App:DB:Pool → App:DB:Pool:Query`.
     *
     * @param subNamespace - The label appended to the current namespace.
     * @returns A new {@link LoggerUtils} instance with the extended namespace.
     *
     * @example
     * ```ts
     * const log     = new LoggerUtils({ namespace: "App", minLevel: "info" });
     * const dbLog   = log.child("DB");       // namespace → "App:DB"
     * const poolLog = dbLog.child("Pool");   // namespace → "App:DB:Pool"
     *
     * dbLog.info("Connected to postgres");
     * // ℹ️  [App:DB] Connected to postgres
     *
     * poolLog.warn("Pool exhausted", { size: 10, waiting: 3 });
     * // ⚠️  [App:DB:Pool] Pool exhausted { size: 10, waiting: 3 }
     *
     * // minLevel is inherited — debug calls on dbLog are silenced too
     * dbLog.debug("This won't print"); // ← silenced (minLevel = "info")
     * ```
     */
    child(subNamespace: string): LoggerUtils;
    /**
     * Emit a **blank line** to the console — no level, no badge, no timestamp.
     *
     * A small but effective tool for creating visual breathing room between
     * unrelated log blocks, section separators, or before a {@link group}.
     *
     * @example
     * ```ts
     * log.success("Phase 1 complete");
     * log.spacer();
     * log.info("Starting phase 2...");
     *
     * // Combine with group for clear section separation
     * log.spacer();
     * log.group("Cleanup", () => {
     *   log.info("Removing temp files");
     * });
     * log.spacer();
     * ```
     */
    spacer(): void;
}

/***************************************************************************
 * XyPrissJS - Fast And Secure
 *
 * @author Nehonix
 * @license Nehonix OSL (NOSL)
 *
 * Copyright (c) 2025 Nehonix. All rights reserved.
 *
 * This License governs the use, modification, and distribution of software
 * provided by NEHONIX under its open source projects.
 * NEHONIX is committed to fostering collaborative innovation while strictly
 * protecting its intellectual property rights.
 * Violation of any term of this License will result in immediate termination of all granted rights
 * and may subject the violator to legal action.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
 * AND NON-INFRINGEMENT.
 * IN NO EVENT SHALL NEHONIX BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * OR CONSEQUENTIAL DAMAGES ARISING FROM THE USE OR INABILITY TO USE THE SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 ***************************************************************************** */

/**
 * **UtilsApi — XyPriss System Utility Module**
 *
 * A comprehensive, high-performance utility class for application development.
 * Utilities are grouped into specialized categories for better modularity.
 *
 * Exposed via `__sys__.utils`.
 *
 * @example
 * ```ts
 * __sys__.utils.num.formatBytes(1048576);      // "1 MB"
 * __sys__.utils.is.email("test@example.com");  // true
 * __sys__.utils.id.uuid();                     // "550e8400-e29b-41d4-a716-446655440000"
 *
 * // Logger — quick global usage
 * __sys__.utils.log.info("Server started", { port: 3000 });
 * __sys__.utils.log.success("User authenticated");
 * __sys__.utils.log.error("Connection refused", new Error("ECONNREFUSED"));
 *
 * // Logger — scoped instance with namespace
 * const log = __sys__.utils.createLogger({ namespace: "Auth", minLevel: "info" });
 * log.warn("Token expiring soon", { expiresIn: "5m" });
 *
 * // Logger — child namespace
 * const dbLog = log.child("DB"); // namespace → "Auth:DB"
 * dbLog.debug("Query executed", { rows: 42 });
 *
 * // Logger — execution timer
 * const stop = log.time("Fetch users");
 * await fetchUsers();
 * stop(); // ✅ [Auth] Fetch users — 38 ms
 * ```
 */
declare class UtilsApi {
    /** **String Utilities** (`slugify`, `truncate`, `randomString`, etc.) */
    readonly str: StringUtils;
    /** **Number & Math Utilities** (`clamp`, `lerp`, `formatBytes`, etc.) */
    readonly num: NumberUtils;
    /** **Date & Time Utilities** (`formatDuration`, `timeAgo`, etc.) */
    readonly date: DateUtils;
    /** **Object Utilities** (`deepClone`, `parse`, `pick`, etc.) */
    readonly obj: ObjectUtils;
    /** **Array Utilities** (`chunk`, `unique`, `groupBy`, etc.) */
    readonly arr: ArrayUtils;
    /** **Async & Control Flow Utilities** (`sleep`, `retry`, `debounce`, etc.) */
    readonly async: AsyncUtils;
    /** **Validation Utilities** (`email`, `url`, `nullish`) */
    readonly is: ValidationUtils;
    /** **Identity Utilities** (`uuid`) */
    readonly id: IdUtils;
    /** **Functional Utilities** (`memo`) */
    readonly fn: FunctionUtils;
    /**
     * **Logger Utilities** — Structured, colorful console logger.
     *
     * This is the **global** logger instance (no namespace).
     * For scoped/namespaced loggers, use {@link UtilsApi.createLogger}.
     *
     * @example
     * ```ts
     * __sys__.utils.log.info("App ready");
     * __sys__.utils.log.warn("Low memory", { freeKb: 128 });
     * __sys__.utils.log.error("Crash", new Error("OOM"));
     * ```
     */
    readonly log: LoggerUtils;
    /**
     * **Create a scoped logger** with a custom namespace and options.
     *
     * Use this instead of `log` when you want per-module namespacing,
     * a minimum level filter, or plain-text output for CI environments.
     *
     * @example
     * ```ts
     * const log = __sys__.utils.createLogger({ namespace: "DB", minLevel: "warn" });
     * log.warn("Slow query detected", { ms: 850 });
     *
     * // Plain mode — no ANSI colors (great for log files / CI)
     * const ciLog = __sys__.utils.createLogger({ namespace: "CI", plain: true });
     * ```
     */
    createLogger(opts?: ConstructorParameters<typeof LoggerUtils>[0]): LoggerUtils;
}

/**
 * **XyPriss System API (Aggregator)**
 *
 * This class serves as the **Logic Aggregator** for the entire XyPriss system interface.
 * It sits at the top of the inheritance chain:
 * `XyPrissFS` -> `SysApi` -> `FSApi` -> `PathApi` -> `BaseApi`
 *
 * **Architecture:**
 * Instead of delegating to properties (e.g., `.fs`, `.sys`), this class **inherits**
 * all methods directly. This creates a "Flat API" structure where all capabilities
 * are available on the single instance.
 *
 * **Usage:**
 * This class is typically not instantiated directly by the user but is the base
 * for the global `__sys__` singleton (`__sys__`).
 *
 * @class XyPrissFS
 * @extends SysApi
 */
declare class XyPrissFS {
    vars: VarsApi;
    fs: FSApi;
    path: PathApi;
    os: OSApi;
    utils: UtilsApi;
    protected _internalRoot: string;
    /**
     * **Project Root Path**
     *
     * The absolute path to the project root directory. This is the primary
     * resolution anchor for all system operations.
     */
    get __root__(): string;
    /**
     * **EnvApi — Environment & Security Manager**
     *
     * `EnvApi` is the sole authorised gateway for reading and writing environment
     * variables inside XyPriss applications. It enforces the XyPriss
     * **Environment Security Shield**, which prevents direct `process.env` access
     * via a hardened runtime Proxy.
     *
     * ---
     *
     * ### Security model
     *
     * Four independent mechanisms work together:
     *
     * **1. Symbol-keyed internal store**
     * The backing store lives at `globalThis[XY_ENV_STORE_KEY]` where
     * `XY_ENV_STORE_KEY` is a module-scoped, unexported `Symbol`. There is no
     * string key to guess or enumerate; external code cannot reach the store
     * without a direct reference to the Symbol.
     *
     * **2. Strict store initialisation guard**
     * Every read and write method calls `requireStore()`, which throws
     * {@link EnvStoreError} if the store has not yet been initialised by the
     * XyPriss bootstrap. This eliminates the silent `process.env` fallback that
     * would otherwise leak values during the startup race window.
     *
     * **3. Value sanitisation**
     * `set()` rejects values containing CR (`\r`), LF (`\n`), or NUL (`\0`).
     * These characters can corrupt downstream log sinks, `.env` parsers, and
     * HTTP header serialisers.
     *
     * **4. Shield — Proxy with enumeration hardening**
     * `process.env` is replaced with a Proxy. Non-whitelisted reads return
     * `undefined`. The `ownKeys` and `has` traps restrict the apparent key set to
     * the whitelist, preventing third-party code (loggers, serialisers) from
     * enumerating the real store through `process.env`.
     *
     * ---
     *
     * ### Usage
     *
     * Do not instantiate this class directly. Use the pre-configured instance
     * exposed by the framework at `__sys__.__env__`:
     *
     * ```typescript
     * // Reading with a fallback
     * const port = __sys__.__env__.get("PORT", "3000");
     *
     * // Reading a required variable — throws EnvAccessError if absent
     * const jwtSecret = __sys__.__env__.getStrict("JWT_SECRET");
     *
     * // Reading a required variable, also rejecting empty strings
     * const dbPassword = __sys__.__env__.getStrict("DB_PASSWORD", { rejectEmpty: true });
     *
     * // Writing a variable at runtime
     * __sys__.__env__.set("FEATURE_FLAG_BETA", "true");
     *
     * // Checking the execution mode
     * if (__sys__.__env__.isProduction()) {
     *   // Apply production hardening
     * }
     * ```
     *
     * ---
     *
     * @see {@link IEnvApi} for the public interface contract.
     * @see {@link EnvAccessError} for the error thrown by `getStrict`.
     * @see {@link EnvKeyError} for the error thrown on invalid keys or values.
     * @see {@link EnvStoreError} for the error thrown when the store is not ready.
     */
    __env__: EnvApi;
    /**
     * **Initialize System API**
     *
     * Sets up the runner bridge with the specified project root.
     *
     * @param {Object} context - Initialization context.
     * @param {string} context.__root__ - Absolute path to the project root directory.
     * @param {string} [context.__mode__] - Optional execution mode (defaults to "development").
     */
    constructor(context: {
        __root__: string;
        __mode__?: string;
        isDynamicEnv?: boolean;
    });
}

/**
 * **XyPriss System Variables (`__sys__`)**
 *
 * The **Central Nervous System** of a XyPriss application.
 * This class serves as the singleton entry point for all system operations.
 *
 * - `fs`: Filesystem operations
 * - `os`: Operating system & hardware telemetry
 * - `path`: Path utilities
 * - `vars`: Dynamic configuration & metadata
 * - `__env__`: Environment variables & security manager (EnvApi)
 */
declare class XyPrissXHSC extends XyPrissFS {
    private readonly _pluginMap;
    private readonly _primaryRoot;
    /** Authorized specialized workspace filesystems for plugins. */
    readonly plugins: {
        get(pluginId: string): XyPrissFS | undefined;
    };
    [XY_XHSC_REGISTER_FS](pluginId: string, instance: XyPrissFS): void;
    get __root__(): string;
    constructor(data?: Record<string, any>);
    /**
     * **Sleep (Utility)**
     *
     * Asynchronously pauses execution for the specified number of milliseconds.
     *
     * @param {number} ms - Milliseconds to sleep.
     * @returns {Promise<void>}
     */
    sleep(ms: number): Promise<void>;
    /**
     * **Exit (Utility)**
     *
     * Forcefully terminates the process with the specified exit code.
     *
     * @param {number} code - The exit code (default: 0).
     */
    exit(code?: number): void;
    toJSON(): Record<string, any>;
    private _loadConfig;
    private _resolvePath;
}
/** Global singleton instance of the system. */
declare const __sys__: XyPrissXHSC;

/**************************************************************************************************************************************************************
 * This code contains proprietary source code from NEHONIX
 *
 * @author Nehonix
 * @license Nehonix OSL (NOSL)
 * @version v2.0
 * @see {@link https://dll.nehonix.com/licenses/NOSL}
 *
 * Copyright (c) 2025 Nehonix. All rights reserved.
 ************************************************************************************************************************************************************** */

/**
 * XyPriss Constant Variables Class - Enhanced Edition
 *
 * Provides ultra-aggressive immutability protection with multiple layers of defense.
 * Protects against all known mutation vectors including prototype pollution,
 * reflection APIs, and advanced tampering techniques.
 *
 * @class XyPrissConst
 * @version 3.0.0
 */
declare class XyPrissConst {
    private constants;
    private immutableCache;
    private accessLog;
    private readonly maxStackDepth;
    private stackDepthTracker;
    constructor();
    /**
     * Create an immutable server configuration.
     *
     * @param {ServerOptions} value - The configuration object
     * @returns {ServerOptions} The immutable configuration
     */
    $cfg(value: ServerOptions$1): ServerOptions$1;
    /**
     * Make a value deeply immutable with maximum protection.
     *
     * @template T - Type of the value to freeze
     * @param {T} value - The value to make immutable
     * @param {string} [path] - Internal path tracking for error messages
     * @param {Set<any>} [visited] - Circular reference tracker
     * @returns {T} The deeply protected immutable value
     */
    $make<T>(value: T, path?: string, visited?: Set<any>): T;
    /**
     * Create an immutable array with aggressive protection
     */
    private createImmutableArray;
    /**
     * Create an immutable Map
     */
    private createImmutableMap;
    /**
     * Create an immutable Set
     */
    private createImmutableSet;
    /**
     * Create an immutable WeakMap (limited protection - WeakMaps can't be fully frozen)
     */
    private createImmutableWeakMap;
    /**
     * Create an immutable WeakSet
     */
    private createImmutableWeakSet;
    /**
     * Create an immutable typed array
     */
    private createImmutableTypedArray;
    /**
     * Create an immutable function wrapper
     */
    private createImmutableFunction;
    /**
     * Create an immutable object with full prototype chain protection
     */
    private createImmutableObject;
    /**
     * Mark an object as immutable with a hidden property
     */
    private markAsImmutable;
    /**
     * Safe JSON stringification with circular reference handling
     */
    private safeStringify;
    /**
     * Define a new constant with enhanced validation
     */
    $set(key: string, value: any): void;
    /**
     * Retrieve a constant value with optional access tracking
     */
    $get<T = any>(key: string, defaultValue?: T): T;
    /**
     * Safe get that returns undefined instead of throwing
     */
    $getSafe<T = any>(key: string): T | undefined;
    /**
     * Check if a constant is defined
     */
    $has(key: string): boolean;
    /**
     * Export all constants as a deeply frozen object
     */
    $toJSON(): Record<string, any>;
    /**
     * Delete a constant (DANGEROUS - use only for testing)
     */
    $delete(key: string): boolean;
    /**
     * Clear all constants (DANGEROUS - use only for testing)
     */
    $clear(): void;
    /**
     * Get the total number of constants
     */
    $size(): number;
    /**
     * List all constant keys
     */
    $keys(): string[];
    /**
     * Get access information about a constant
     */
    $getAccessInfo(key: string): {
        created: number;
        exists: boolean;
    };
    /**
     * Validate that an object is truly immutable (deep check)
     */
    $validate(value: any): boolean;
}
/**
 * Default instance for easy access
 */
declare const __const__: XyPrissConst;

/**
 * Type definitions for Console Interception System
 */
interface ConsoleInterceptionConfig {
    enabled: boolean;
    /** Use XHSC (Go) native interception system (default: true) */
    useNative?: boolean;
    /** Methods to intercept */
    interceptMethods: readonly ("log" | "error" | "warn" | "info" | "debug" | "trace")[];
    /** Limit for interceptions per second */
    maxInterceptionsPerSecond?: number;
    /** Encryption settings (delegated to Go) */
    encryption?: {
        enabled: boolean;
        key?: string;
        algorithm?: "aes-128-gcm" | "aes-192-gcm" | "aes-256-gcm";
        displayMode?: "readable" | "encrypted" | "both";
    };
    /** Filter settings (delegated to Go) */
    filters?: {
        minLevel?: "debug" | "info" | "warn" | "error";
        maxLength?: number;
        includePatterns?: (string | RegExp)[];
        excludePatterns?: (string | RegExp)[];
        userAppPatterns?: (string | RegExp)[];
        systemPatterns?: (string | RegExp)[];
    };
    /**
     * Custom callback hook to receive intercepted logs synchronously.
     *
     * The second parameter `filtered` indicates whether `log.message` has been
     * processed through the full XCI pipeline (XHSC filtering, prefix stripping,
     * etc.) mirroring exactly what is displayed in the terminal.
     *
     * Controlled by `filteredOnLog`:
     * - `filteredOnLog: false` (default) — fires before XHSC delegation with the
     *   raw message. `filtered` is `false`.
     * - `filteredOnLog: true` — fires after XHSC processing with the formatted
     *   message. `filtered` is `true`. Logs filtered out by XHSC are not delivered.
     */
    onLog?: (log: {
        level: string;
        method: string;
        message: string;
        args: any[];
    }, filtered: boolean) => void;
    /**
     * When `true`, the `onLog` callback receives the XHSC-processed message
     * (same string displayed in the terminal) instead of the raw intercepted value.
     * Defaults to `false`.
     */
    filteredOnLog?: boolean;
    /** Performance-optimized mode */
    performanceMode?: boolean;
    /** Whether to include source mapping (file/line) */
    sourceMapping?: boolean;
    /** Whether to preserve original console output and in what mode */
    preserveOriginal?: boolean | {
        enabled: boolean;
        mode?: "original" | "intercepted" | "both" | "none";
        showPrefix?: boolean;
        customPrefix?: string;
        colorize?: boolean;
        allowDuplication?: boolean;
        separateStreams?: boolean;
        onlyUserApp?: boolean;
        /**
         * Limit the number of log lines displayed in the terminal.
         * Inspired by the Linux `head`/`tail` commands.
         *
         * - `head`: display only the first N logs then stop (like `head -n N`).
         * - `tail`: always keep the last N logs visible in memory;
         *           each new log evicts the oldest (circular buffer).
         *
         * @example
         * displayLimit: { mode: "tail", maxLines: 50 }
         */
        displayLimit?: {
            /** Limiting strategy. Defaults to "tail". */
            mode?: "head" | "tail";
            /** Maximum number of log lines to display. */
            maxLines: number;
        };
    };
}
interface InterceptedConsoleCall {
    method: "log" | "error" | "warn" | "info" | "debug" | "trace";
    args: any[];
    message?: string;
    timestamp: Date;
    category: "userApp" | "system" | "unknown";
    level: "info" | "warn" | "error" | "debug";
    source?: {
        file?: string;
        line?: number;
        column?: number;
    };
    component?: string;
}

/**
 * Plugin System Types
 */

/**
 * Restricted XyPrissApp for plugins.
 * Only allows HTTP methods, middleware registration, and — conditionally — server configs.
 */
interface PluginXyPrissApp {
    get(path: string, ...handlers: any[]): void;
    post(path: string, ...handlers: any[]): void;
    put(path: string, ...handlers: any[]): void;
    delete(path: string, ...handlers: any[]): void;
    patch(path: string, ...handlers: any[]): void;
    options(path: string, ...handlers: any[]): void;
    head(path: string, ...handlers: any[]): void;
    connect(path: string, ...handlers: any[]): void;
    trace(path: string, ...handlers: any[]): void;
    all(path: string, ...handlers: any[]): void;
    use(...args: any[]): void;
    /**
     * The full server configuration options passed to `createServer()` by the host application.
     *
     * This property is **permission-gated** at runtime. The security facade will return
     * `undefined` unless the plugin has been explicitly granted the
     * `XHS.PERM.SECURITY.CONFIGS` permission in the host project's `allowedHooks`.
     *
     * Wildcards (`"*"`) do NOT grant this permission — it must be declared explicitly.
     *
     * Typical use cases:
     *  - Reading the server port or host for building absolute URLs in generated docs.
     *  - Detecting the runtime environment (`env: "production" | "development"`) to
     *    adapt plugin behavior without hardcoding values.
     *  - Accessing feature flags passed through custom server options.
     *
     * @permission XHS.PERM.SECURITY.CONFIGS
     *
     * @example
     * // Inside onAuxiliaryServerDeploy or onServerStart:
     * const port = server.app.configs?.server?.port ?? 3000;
     * const env  = server.app.configs?.env ?? "development";
     */
    configs?: ServerOptions$1;
}
/**
 * Restricted XyPrissServer for plugins.
 *
 * This is the facade object injected as the `server` argument in lifecycle hooks
 * such as `onServerStart`, `onServerReady`, and `onAuxiliaryServerDeploy`.
 * It intentionally exposes only a safe subset of the real server's capabilities.
 *
 * The engine's security layer intercepts every property access on `server.app`
 * and enforces per-plugin permission checks before delegating to the real
 * underlying application instance.
 */
interface PluginServer {
    /**
     * The restricted application facade.
     *
     * Provides access to HTTP method registrars (`get`, `post`, etc.), `use()`,
     * and the conditional `configs` property. Any attempt to access properties
     * not in this interface will be silently blocked by the security layer.
     */
    app: PluginXyPrissApp;
}
interface PluginStats {
    name: string;
    version: string;
    description?: string;
    enabled: boolean;
    permissions: {
        allowedHooks: string[] | "*";
        deniedHooks: string[];
        policy: "allow" | "deny";
    };
    uid?: string;
    dependencies: string[];
}
interface PluginManagement {
    getStats: () => PluginStats[];
    setPermission: (pluginName: string, hookId: string, allowed: boolean, by?: string) => void;
    toggle: (pluginName: string, enabled: boolean) => void;
}
interface OpsServerManager {
    /**
     * Deploys a fully configured independent XyPriss auxiliary server.
     * Use this for internal admin dashboards, metric scrapers, or documentation servers.
     */
    createAuxiliaryServer: (options: ServerOptions$1) => XyPrissApp;
    /**
     * Returns the global route registry for documentation generation.
     */
    getRouteRegistry: () => any[];
}
interface XyPrissPlugin {
    name: string;
    version: string;
    type?: string;
    description: string;
    /**
     * @internal - Captured project root of the plugin.
     * Used for contract security verification.
     */
    __root__?: string;
    /**
     * @internal - Unique technical identifier for the plugin instance.
     * Generated at registration based on fingerprint.
     */
    uid?: string;
    /**
     * @internal - Metadata fingerprint used for duplicate discovery and unique identification.
     */
    fingerprint?: string;
    dependencies?: string[];
    onRegister?(error?: Error | null): void | Promise<void>;
    onServerStart?(server: PluginServer): void | Promise<void>;
    onServerReady?(server: PluginServer): void | Promise<void>;
    onServerStop?(server: PluginServer): void | Promise<void>;
    onRequest?(req: XyPrisRequest, res: XyPrisResponse, next: NextFunction): void | Promise<void>;
    onResponse?(req: XyPrisRequest, res: XyPrisResponse): void | Promise<void>;
    onError?(error: Error, req: XyPrisRequest, res: XyPrisResponse, next?: NextFunction): void | Promise<void>;
    /**
     * Hook triggered when a security attack or problem is detected
     */
    onSecurityAttack?(attackData: any, req: XyPrisRequest, res: XyPrisResponse): void | Promise<void>;
    /**
     * Hook triggered to report the response time of a request
     */
    onResponseTime?(responseTime: number, req: XyPrisRequest, res: XyPrisResponse): void | Promise<void>;
    /**
     * Hook triggered when a route generates a 500 error
     */
    onRouteError?(error: Error, req: XyPrisRequest, res: XyPrisResponse): void | Promise<void>;
    /**
     * Hook triggered when a rate limit is reached
     */
    onRateLimit?(limitData: any, req: XyPrisRequest, res: XyPrisResponse): void | Promise<void>;
    /**
     * Hook triggered when a console log is intercepted by the system.
     *
     * This hook allows plugins to monitor, analyze, or redirect all console output
     * (log, info, warn, error, debug, etc.) across the entire application.
     *
     * @param log - The intercepted console call data including method, arguments, and metadata.
     * @permission XHS.PERM.LOGGING.CONSOLE_INTERCEPT - Required to receive log data.
     * @performance This hook is executed synchronously; preserve performance by avoiding heavy tasks.
     * @security Sensitive data may be present in logs; handle with extreme care.
     * @default Disabled by default for security.
     */
    onConsoleIntercept?(log: InterceptedConsoleCall): void | Promise<void>;
    registerRoutes?(app: XyPrissApp): void;
    middleware?: any | any[];
    middlewarePriority?: "first" | "normal" | "last";
    /**
     * Hook for plugin management
     * Only called if the plugin has MANAGE_PLUGINS permission
     */
    managePlugins?(manager: PluginManagement): void | Promise<void>;
    /**
     * Advanced Ops Hook — Deploy an Independent Auxiliary Server
     *
     * This hook enables a plugin to spawn a fully isolated XyPriss server instance
     * on a separate port, completely independent from the main application server.
     * It is the recommended pattern for deploying internal-only tooling such as:
     *
     *  - Admin dashboards and back-office UIs
     *  - API documentation servers (e.g., Swagger, Redoc)
     *  - Internal metrics scrapers (e.g., Prometheus exposition endpoint)
     *  - Dedicated WebSocket or SSE servers
     *  - Debug/introspection interfaces (development only)
     *
     * --- Execution Context ---
     * This hook is called once during the server initialization phase, after
     * `onServerStart` has fired on all plugins. The auxiliary server created here
     * operates as a completely separate process listener and does NOT share
     * middleware, routes, or request lifecycle with the main server.
     *
     * --- Security Model ---
     * This is a **privileged Ops hook**. It will not be called unless the plugin
     * has been explicitly granted the `XHS.PERM.OPS.AUXILIARY_SERVER` permission
     * in the host project's configuration. Attempting to use it without the
     * required permission will result in a silent no-op (the engine will block
     * the hook invocation before your code is reached).
     *
     * The `server` argument is a restricted facade of the main XyPrissServer
     * instance (a `PluginServer`). It exposes only the HTTP method registrars
     * (`get`, `post`, etc.) and `use()`, scoped to your plugin's namespace.
     * Direct access to `server.app` internals or low-level engine properties
     * is blocked by the security layer.
     *
     * --- Parameters ---
     * @param ops - The `OpsServerManager` context. Provides two capabilities:
     *
     *   `ops.createAuxiliaryServer(options: ServerOptions): XyPrissApp`
     *   Spawns and returns a new, fully configured XyPriss app instance bound
     *   to the port specified in `options.server.port`. All standard XyPriss
     *   features (routing, middleware, logging) are available on this instance.
     *   The performance and plugin subsystems are disabled by default to avoid
     *   recursive initialization.
     *
     *   `ops.getRouteRegistry(): RouteEntry[]`
     *   Returns a snapshot of all routes registered on the MAIN server at the
     *   time of the call. Useful for generating live documentation or dashboards
     *   that reflect the host application's actual API surface.
     *
     * @param server - A restricted facade of the main XyPrissServer. Exposes
     *   only the HTTP methods and `use()` of the main `app` instance, scoped
     *   to this plugin's namespace. Use this to cross-register a route on the
     *   main server (e.g., a redirect from `/docs` on the main port to the
     *   auxiliary docs port) without full access to internal engine state.
     *
     * @permission XHS.PERM.OPS.AUXILIARY_SERVER
     *   Must be declared in `xfpm.permissions` inside `package.json` AND
     *   explicitly listed in `allowedHooks` in the host project's plugin
     *   configuration. Wildcards (`"*"`) do NOT grant this privileged hook.
     *
     * @example
     * // Use case 1: Spawn a dedicated Swagger documentation server
     * async onAuxiliaryServerDeploy(ops, server) {
     *     const routes = ops.getRouteRegistry();
     *     const openApiSpec = generateOpenApiSpec(routes);
     *
     *     const docsApp = ops.createAuxiliaryServer({
     *         server: { port: 9001, host: "127.0.0.1" },
     *         logging: { enabled: true, level: "warn" },
     *     });
     *
     *     docsApp.get("/openapi.json", (req, res) => {
     *         res.json(openApiSpec);
     *     });
     *
     *     docsApp.get("/", (req, res) => {
     *         res.send(renderSwaggerUI("/openapi.json"));
     *     });
     *
     *     // Optionally register a redirect on the main server (scoped to plugin namespace)
     *     server.app.get("/my-plugin/docs", (req, res) => {
     *         res.redirect("http://localhost:9001");
     *     });
     * }
     *
     * @example
     * // Use case 2: Internal Prometheus metrics endpoint (never exposed publicly)
     * async onAuxiliaryServerDeploy(ops, _server) {
     *     const metricsApp = ops.createAuxiliaryServer({
     *         server: { port: 9090, host: "127.0.0.1" },
     *         logging: { enabled: false },
     *     });
     *
     *     metricsApp.get("/metrics", (req, res) => {
     *         res.setHeader("Content-Type", "text/plain; version=0.0.4");
     *         res.send(collectMetrics());
     *     });
     * }
     */
    onAuxiliaryServerDeploy?(ops: OpsServerManager, server: PluginServer): void | Promise<void>;
}
type PluginCreator = (config?: any) => XyPrissPlugin;
interface PluginConfig {
    connection?: any;
    register?: Array<XyPrissPlugin | PluginCreator>;
    /** Route optimization plugin configuration */
    routeOptimization?: {
        enabled?: boolean;
        analysisInterval?: number;
        optimizationThreshold?: number;
        popularityWindow?: number;
        maxTrackedRoutes?: number;
        autoOptimization?: boolean;
        customRules?: Array<{
            pattern: string;
            minHits: number;
            maxResponseTime: number;
            cacheStrategy: "aggressive" | "moderate" | "conservative";
            preloadEnabled?: boolean;
        }>;
        onOptimization?: (route: string, optimization: string) => void;
        onAnalysis?: (stats: any[]) => void;
    };
    /** Server maintenance plugin configuration */
    serverMaintenance?: {
        enabled?: boolean;
        checkInterval?: number;
        errorThreshold?: number;
        memoryThreshold?: number;
        responseTimeThreshold?: number;
        logRetentionDays?: number;
        maxLogFileSize?: number;
        autoCleanup?: boolean;
        autoRestart?: boolean;
        onIssueDetected?: (issue: any) => void;
        onMaintenanceComplete?: (actions: string[]) => void;
    };
    /**
     * Allow lifecycle hooks (onServerStart, onServerReady, onServerStop) to execute
     * by default even if not explicitly whitelisted in allowedHooks.
     * @default false (Zero-Trust)
     */
    allowLifecycleByDefault?: boolean;
}

declare const IXStaticSchem: reliant_type.InterfaceSchema<{
    readonly lruCacheSize?: number | undefined;
    readonly defaultMaxAge?: "string" | "number?" | undefined;
    readonly zeroCopy?: boolean | undefined;
    readonly concurrencyPool?: number | undefined;
}>;

type DotfileModeT = "deny" | "allow";
/**
 * How to handle files starting with a dot (e.g. .env, .git).
 * - "allow": Serves the file (Security Risk)
 * - Object: Custom restricted file patterns.
 * @default "deny"
 */
type dotfiles = DotfileModeT | {
    mode: DotfileModeT;
    /** Custom file patterns to always restrict regardless of dot prefix */
    custom?: string[];
};
/**
 * Static file serving configuration (XStatic).
 *
 * Configures the high-performance XStatic engine, including
 * meta-caching and delegation behaviors.
 */
type IXStatic = typeof IXStaticSchem.types & {
    dotfiles?: dotfiles;
};
interface StaticOptions {
    /** Allow serving files outside of the project root (Security Risk) */
    allowOutsideRoot?: boolean;
    /** Disable path validation safety checks */
    unsafe?: boolean;
    /** Cache-Control max-age header */
    maxAge?: string | number;
    /** Fallback to standard TS streaming if delegation fails */
    fallback?: boolean;
}

interface RouteDefinition {
    method: string;
    path: string;
    handler: RouteHandler;
    middleware: MiddlewareEntry[];
    pattern?: RegExp;
    paramNames?: string[];
}
interface RouterOptions {
    caseSensitive?: boolean;
    mergeParams?: boolean;
    strict?: boolean;
}
interface MiddlewareEntry {
    path?: string;
    handler: MiddlewareFunction;
}

type MiddlewareFunction$1 = MiddlewareFunction;
type XyPrisRequest$1 = XyPrisRequest;
type XyPrisResponse$1 = XyPrisResponse;

/** Param type constraint descriptor */
type ParamType = "string" | "number" | "integer" | "boolean" | "uuid" | "alpha" | "alphanumeric" | `string(${number},${number})` | `number(${number},${number})` | `enum(${string})`;
/** A declarative guard: returns true to allow, false/string to deny */
type RouteGuard = (req: XyPrisRequest$1, res: XyPrisResponse$1) => boolean | string | Promise<boolean | string>;
/**
 * Declarative guard configuration for a route or group.
 *
 * Built-in properties (`authenticated`, `roles`, `permissions`) are resolved
 * automatically by the framework using resolvers registered via `XyGuard.define()`.
 *
 * Custom guards can be declared using any additional string key. The key must
 * correspond to a resolver registered via `XyGuard.define(name, resolver)`.
 * If no resolver is found for a key, it is silently ignored.
 *
 * @example
 * ```typescript
 * // Register a custom guard globally (e.g. in server.ts)
 * XyGuard.define("ipWhitelist", (req) => {
 *     return req.ip === "127.0.0.1" ? true : "Forbidden IP";
 * });
 *
 * // Use it declaratively alongside built-ins
 * router.get("/admin", {
 *     guards: {
 *         authenticated: true,
 *         roles: ["admin"],
 *         ipWhitelist: true,
 *     },
 * }, handler);
 * ```
 *
 * @remarks
 * BREAKING CHANGE (v2): The `custom` property has been removed.
 * Inline guard arrays must now be passed directly as the value of `guards`
 * instead of being nested inside `custom`.
 *
 * @example
 * ```typescript
 * // Before (v1 — no longer supported)
 * guards: { authenticated: true, custom: [myGuardFn] }
 *
 * // After (v2 — use the array form directly)
 * guards: [myGuardFn]
 *
 * // Or register the guard globally and use the declarative key form
 * XyGuard.define("myGuard", myGuardFn);
 * guards: { authenticated: true, myGuard: true }
 * ```
 */
type BuiltInGuards = {
    /**
     * Requires the request to be authenticated.
     * The resolver must be registered via `XyGuard.define("authenticated", ...)`.
     * Returns `true` to allow, `false` to block with 403, or a `string` to block with 401.
     */
    authenticated?: boolean;
    /**
     * Restricts access to the specified roles.
     * The resolver must be registered via `XyGuard.define("roles", ...)`.
     * The resolver receives the required roles array as a second argument.
     */
    roles?: string[];
    /**
     * Restricts access to the specified permissions.
     * The resolver must be registered via `XyGuard.define("permissions", ...)`.
     * The resolver receives the required permissions array as a second argument.
     */
    permissions?: string[];
    /**
     * @deprecated Removed in v2. The `custom` property no longer exists.
     *
     * Migrate by passing guard functions directly as the `guards` array, or by
     * registering them as named guards via `XyGuard.define()`.
     *
     * @example
     * ```typescript
     * // Before (v1 — triggers a TypeScript error)
     * guards: { authenticated: true, custom: [myGuardFn] }
     *
     * // After — option 1: array form
     * guards: [myGuardFn]
     *
     * // After — option 2: named declarative form
     * XyGuard.define("myGuard", myGuardFn);
     * guards: { authenticated: true, myGuard: true }
     * ```
     */
    custom?: never;
} & CustomGuards & Record<string, any>;
/**
 * Interface for TypeScript Declaration Merging.
 * Developers can augment this interface in their project to get auto-completion
 * for their custom guards.
 *
 * @example
 * ```typescript
 * declare module "xypriss" {
 *     interface CustomGuards {
 *         ipWhitelist?: boolean;
 *         plan?: "free" | "premium";
 *     }
 * }
 * ```
 */
interface CustomGuards {
}
/** Per-route rate limit config */
interface RoutRateLimit {
    /** Max requests allowed in window */
    max: number;
    /** Time window, e.g. "1m", "30s", "1h" */
    window?: string;
    /** Time window in milliseconds (optional, takes precedence over window) */
    windowMs?: number;
    /** Custom error message */
    message?: string;
    /** Key extractor — defaults to IP */
    keyBy?: "ip" | "user" | ((req: XyPrisRequest$1) => string);
}
/** Declarative cache config */
type RouteCache = string | {
    ttl: number;
    vary?: string[];
    key?: (req: XyPrisRequest$1) => string;
    invalidateOn?: string[];
};
/** Lifecycle hooks scoped to a single route */
interface RouteLifecycle {
    /** Called before the handler chain. Can modify req/res or abort. */
    beforeEnter?: (req: XyPrisRequest$1, res: XyPrisResponse$1, next: () => void) => void | Promise<void>;
    /** Called after a successful response. For metrics / logging. */
    afterLeave?: (req: XyPrisRequest$1, res: XyPrisResponse$1, durationMs: number) => void | Promise<void>;
    /** Route-level error handler */
    onError?: (err: unknown, req: XyPrisRequest$1, res: XyPrisResponse$1, next: () => void) => void | Promise<void>;
}
/** Route metadata for docs / OpenAPI / registry */
interface RouteMeta {
    summary?: string;
    description?: string;
    tags?: string[];
    /** Semver or numeric API version */
    version?: string;
    /** Mark as deprecated with optional sunset date */
    deprecated?: boolean | {
        since?: string;
        sunset?: string;
        replacement?: string;
    };
    /** Mark as internal (excluded from public docs) */
    internal?: boolean;
    /** Explicitly defined responses for documentation */
    responses?: Record<string, {
        description: string;
    }>;
    /** Arbitrary key-value pairs for plugins */
    [key: string]: unknown;
}
/** Condition deciding whether a route is active */
type RouteCondition = boolean | (() => boolean) | {
    env?: string | string[];
    feature?: string;
};
/**
 * **Comprehensive route configuration object.**
 * Provides full control over the route's lifecycle, security, caching, and matching behavior.
 */
interface RichRouteOptions {
    /**
     * **Declarative Security Guards.**
     * Injects protection layers before the controller execution.
     * Supports built-ins (`authenticated`, `roles`) as well as custom-defined guards.
     *
     * @example
     * ```ts
     * guards: {
     *     authenticated: true,
     *     roles: ["admin", "super-admin"],
     *     customIpWhitelist: true
     * }
     * ```
     */
    guards?: BuiltInGuards | RouteGuard[];
    /**
     * **Lifecycle Hooks.**
     * Attach custom logic to specific stages of the route's execution.
     * Includes `beforeEnter`, `afterLeave` (with execution duration), and `onError`.
     *
     * @example
     * ```ts
     * lifecycle: {
     *     beforeEnter: (req, res, next) => {
     *         if (req.headers["x-block"]) return res.status(403).send("Blocked");
     *         next();
     *     },
     *     afterLeave: (req, res, durationMs) => {
     *         console.log(`Request completed in ${durationMs}ms`);
     *     },
     *     onError: (err, req, res, next) => {
     *         res.status(500).json({ error: "Custom error handler" });
     *     }
     * }
     * ```
     */
    lifecycle?: RouteLifecycle;
    /**
     * **Route-specific Rate Limiting.**
     * Protect this endpoint from abuse by restricting the maximum number of requests.
     *
     * @example
     * ```ts
     * rateLimit: {
     *     max: 100,
     *     window: "1m", // or windowMs: 60000
     *     message: "Too many requests, try again later.",
     *     keyBy: (req) => req.headers["x-api-key"] as string // Defaults to "ip"
     * }
     * ```
     */
    rateLimit?: RoutRateLimit;
    /**
     * **Response Caching Strategy.**
     * Declaratively cache the response of this route to improve performance.
     *
     * @example
     * ```ts
     * // Shorthand (string):
     * cache: "5m"
     *
     * // Advanced:
     * cache: {
     *     ttl: 300, // seconds
     *     vary: ["Authorization", "Accept-Language"],
     *     key: (req) => `custom_key_${req.query.id}`
     * }
     * ```
     */
    cache?: RouteCache;
    /**
     * **Route Metadata.**
     * Used for OpenAPI generation, tagging, versioning, or attaching custom
     * payload data accessible by plugins.
     *
     * @example
     * ```ts
     * meta: {
     *     summary: "Get User Profile",
     *     description: "Fetches the profile details of the authenticated user.",
     *     tags: ["Users", "Profile"],
     *     version: "v2",
     *     deprecated: { since: "2.5", sunset: "2027-01-01", replacement: "/v3/user/profile" },
     *     internal: false
     * }
     * ```
     */
    meta?: RouteMeta;
    /**
     * **Router Resolution Priority.**
     * Determines the evaluation order when multiple routes could match.
     * A higher number means higher priority.
     *
     * @default 0
     * @example priority: 100
     */
    priority?: number;
    /**
     * **Dynamic Activation (Feature Flagging).**
     * Determines if this route is exposed. If evaluated to `false`, the route
     * is completely ignored by the engine (returns 404 Not Found).
     *
     * @default true
     * @example
     * ```ts
     * // Static boolean
     * active: false
     *
     * // Dynamic function (using Environment Security Shield)
     * active: () => __sys__.__env__.get("ENABLE_BETA") === "true"
     *
     * // Environment/Feature-based config
     * active: { env: ["development", "staging"], feature: "new-admin-panel" }
     * ```
     */
    active?: RouteCondition;
}
/** Internal extended route definition */
interface RichRouteDefinition extends RouteDefinition {
    guards?: BuiltInGuards | RouteGuard[];
    lifecycle?: RouteLifecycle;
    rateLimit?: RoutRateLimit;
    cache?: RouteCache;
    meta?: RouteMeta;
    priority: number;
    active: boolean;
    /** Full original path string (before regex compile) */
    originalPath: string;
    /** Typed param constraints extracted from path */
    paramConstraints: Record<string, ParamConstraint>;
    /** API version extracted from meta or path */
    version?: string;
    /** Unique route ID for registry */
    id: string;
    /** Detected or explicitly defined responses */
    responses?: Record<string, {
        description: string;
    }>;
}
interface ParamConstraint {
    name: string;
    type: string;
    options?: unknown;
}
/** Group config passed to router.group() */
interface RouteGroupOptions {
    prefix?: string;
    middleware?: MiddlewareFunction$1[];
    guards?: BuiltInGuards | RouteGuard[];
    meta?: Partial<RouteMeta>;
    rateLimit?: RoutRateLimit;
    /** API version prefix, e.g. "v1" → prepends /v1 */
    version?: string;
    active?: RouteCondition;
}
/** Registry entry type (for OpenAPI / docs) */
interface RouteRegistryEntry {
    id: string;
    method: string;
    path: string;
    version?: string;
    meta?: RouteMeta;
    hasGuards: boolean;
    hasRateLimit: boolean;
    hasCache: boolean;
    paramNames?: string[];
    paramConstraints: Record<string, ParamConstraint>;
    /** Detected or explicitly defined responses */
    responses?: Record<string, {
        description: string;
    }>;
}

/** Minimal interface for router instance to avoid circular imports */
interface IRouterInternal {
    getAllRoutes(): RichRouteDefinition[];
    getRoutes(): RichRouteDefinition[];
}

declare class XyPrissRouter implements IRouterInternal {
    private routes;
    private middleware;
    private logger;
    private routerOptions;
    static featureResolver: ((flag: string) => boolean) | null;
    static setFeatureResolver(fn: (flag: string) => boolean): void;
    constructor(options?: RouterOptions);
    get upload(): FileUploadAPI;
    use(middleware: MiddlewareFunction): XyPrissRouter;
    use(path: string, middleware: MiddlewareFunction): XyPrissRouter;
    use(path: string, router: XyPrissRouter): XyPrissRouter;
    use(path: string, options: RouteGroupOptions, router: XyPrissRouter): XyPrissRouter;
    get(path: string, options: RichRouteOptions, ...handlers: RouteHandler[]): XyPrissRouter;
    get(path: string, ...handlers: RouteHandler[]): XyPrissRouter;
    post(path: string, options: RichRouteOptions, ...handlers: RouteHandler[]): XyPrissRouter;
    post(path: string, ...handlers: RouteHandler[]): XyPrissRouter;
    put(path: string, options: RichRouteOptions, ...handlers: RouteHandler[]): XyPrissRouter;
    put(path: string, ...handlers: RouteHandler[]): XyPrissRouter;
    patch(path: string, options: RichRouteOptions, ...handlers: RouteHandler[]): XyPrissRouter;
    patch(path: string, ...handlers: RouteHandler[]): XyPrissRouter;
    delete(path: string, options: RichRouteOptions, ...handlers: RouteHandler[]): XyPrissRouter;
    delete(path: string, ...handlers: RouteHandler[]): XyPrissRouter;
    head(path: string, options: RichRouteOptions, ...handlers: RouteHandler[]): XyPrissRouter;
    head(path: string, ...handlers: RouteHandler[]): XyPrissRouter;
    options(path: string, options: RichRouteOptions, ...handlers: RouteHandler[]): XyPrissRouter;
    options(path: string, ...handlers: RouteHandler[]): XyPrissRouter;
    all(path: string, options: RichRouteOptions, ...handlers: RouteHandler[]): XyPrissRouter;
    all(path: string, ...handlers: RouteHandler[]): XyPrissRouter;
    group(options: RouteGroupOptions, callback: (r: XyPrissRouter) => void): this;
    version(ver: string, callback: (r: XyPrissRouter) => void): this;
    redirect(from: string, to: string, status?: 301 | 302 | 307 | 308): this;
    getRoutes(): RichRouteDefinition[];
    getAllRoutes(): RichRouteDefinition[];
    getMiddleware(): MiddlewareEntry[];
    findById(id: string): RichRouteDefinition | undefined;
    toRegistry(): RouteRegistryEntry[];
    getStats(): {
        totalRoutes: number;
        activeRoutes: number;
        totalMiddleware: number;
        routesByMethod: any;
        options: RouterOptions;
    };
    private _addRichRoute;
    private _getState;
}

declare const schm: reliant_type.InterfaceSchema<{
    readonly title: string;
    readonly message: string;
    readonly requestedPath: string;
    readonly mode: "dark" | "light" | "system";
    readonly customCSS: string;
    readonly faviconUrl: string;
    readonly requestedMethod: string;
    readonly appName: string;
    readonly redirectTo: string;
    readonly redirectText: string;
} & {
    readonly redirectScript?: ((...args: any[] | unknown[]) => void) | undefined;
    readonly contactEmail?: string | undefined;
}>;
type NotFoundTemplateData = typeof schm.types;
interface ntf {
    /**
     * Indicates whether the custom 404 template is active and should be rendered.
     */
    enabled?: boolean;
}
type NotFoundConfig = Partial<Omit<NotFoundTemplateData, "requestedMethod" | "requestedPath">> & ntf;

/**
 * Interface representing XEMS (XyPriss Encrypted Memory Store) configurations.
 * XEMS is a specialized temporary database with high-security features.
 */
interface XemsTypes {
    /**
     * Whether XEMS is enabled for this server instance.
     */
    enable?: boolean;
    /**
     * The default isolated storage namespace (Sandbox).
     */
    sandbox?: string;
    /**
     * Default Time-to-Live for stored records (e.g., "15m", "1h", "2d").
     * @important XEMS enforces a HARD GLOBAL LIMIT of 5 days. Any value exceeding "5d" will be capped.
     */
    ttl?: string;
    /**
     * Name of the HttpOnly cookie used for session tracking.
     */
    cookieName?: string;
    /**
     * Name of the HTTP header used for session tracking (for API callers).
     */
    headerName?: string;
    /**
     * Whether to automatically rotate tokens on every request.
     * Core of the "Moving Target Defense" strategy.
     */
    autoRotation?: boolean;
    /**
     * Property on the request object where session data will be attached (default: "session").
     */
    attachTo?: string;
    /**
     * Persistent storage configuration.
     */
    persistence?: {
        /**
         * Whether to persist data to disk in an encrypted vault.
         */
        enabled: boolean;
        /**
         * Path to the encrypted vault file.
         */
        path?: string;
        /**
         * Mandatory 32-byte (256-bit) encryption secret.
         * Used in combination with hardware ID for vault encryption.
         */
        secret: string;
        /**
         * Resource allocation for the XEMS sidecar.
         */
        resources?: {
            /** Cache size in MB (reserved for indexing performance) */
            cacheSize?: number;
        };
    };
    /**
     * Security options for the HttpOnly cookie.
     */
    cookieOptions?: CookieOptions;
    /**
     * Grace period for rotated sessions.
     * Duration in milliseconds for which the old token remains valid for READ access after rotation.
     * Prevents race conditions with simultaneous requests.
     * @maximum 55000 (55 seconds)
     */
    gracePeriod?: number;
}
interface CookieOptions {
    httpOnly?: boolean;
    secure?: boolean;
    sameSite?: "Strict" | "Lax" | "None";
    path?: string;
    domain?: string;
    maxAge?: number;
    expires?: Date;
    signed?: boolean;
}

interface XServerOptions {
    notFound?: NotFoundConfig;
    /** Response manipulation configuration */
    responseManipulation?: ResponseManipulationConfig;
    /** Plugin configuration */
    plugins?: PluginConfig;
    /**
     * Managed Cluster configuration (XHSC managed).
     *
     * When enabled, XHSC will act as an IPC server and manage a pool of
     * Node.js worker processes via clustering logic implemented in Rust.
     */
    cluster?: {
        /** Enable/Disable Rust-managed clustering (default: false) */
        enabled?: boolean;
        /** Number of workers to spawn, or "auto" for CPU core count (default: "auto") */
        workers?: number | "auto";
        /** Enable automatic worker respawn if a process crashes (default: true) */
        autoRespawn?: boolean;
        /** Path to the Node.js entry point script for workers */
        entryPoint?: string;
        /**
         * Load balancing strategy
         * - round-robin: Cyclic distribution
         * - least-connections: Send to worker with fewest active requests
         * - least-response-time: Send to worker with fastest historical response
         * - ip-hash: Sticky sessions based on client IP
         */
        strategy?: "round-robin" | "least-connections" | "least-response-time" | "ip-hash" | "weighted-round-robin" | "weighted-least-connections";
        /** Resource limits for each worker */
        resources?: {
            /** Max memory per worker in MB (e.g. 512) or string (e.g. "1GB") */
            maxMemory?: number | string;
            /** Max CPU usage percentage (0-100) */
            maxCpu?: number;
            /** Process priority level (maps to nice values) */
            priority?: "low" | "normal" | "high" | "critical" | number;
            /** Maximum number of open file descriptors */
            fileDescriptorLimit?: number;
            /** Optimize for garbage collection (expose-gc) */
            gcHint?: boolean;
            /** Memory management settings */
            memoryManagement?: {
                /** Interval in ms to check worker resource usage */
                checkInterval?: number;
            };
            /** Enforcement settings */
            enforcement?: {
                /** Kill worker if limits are exceeded (default: true) */
                hardLimits?: boolean;
            };
            /** Intelligence settings for resource management and recovery */
            intelligence?: {
                /** Enable smart resource management (default: false) */
                enabled?: boolean;
                /** Pre-allocate resources at startup to prevent competition (default: false) */
                preAllocate?: boolean;
                /** Fast rescue mode if all workers die (reboots in ms) (default: true) */
                rescueMode?: boolean;
            };
        };
    };
    /**
     * Static file serving configuration (XStatic).
     *
     * Configures the high-performance XStatic engine, including
     * meta-caching and delegation behaviors.
     */
    static?: IXStatic;
    /**
     * Environment mode for the server.
     *
     * Determines the runtime environment and enables environment-specific
     * optimizations and configurations.
     *
     * @default 'development'
     *
     * @example
     * ```typescript
     * env: 'production' // Enables production optimizations
     * ```
     */
    env?: "development" | "production" | "test";
    /**
     * Cache configuration for high-performance data access.
     *
     * Comprehensive caching system supporting multiple backends,
     * compression, and intelligent strategies.
     *
     * @example
     * ```typescript
     * cache: {
     *   strategy: 'hybrid', // Memory + Redis
     *   maxSize: 1024 * 1024 * 100, // 100MB
     *   ttl: 3600, // 1 hour
     *   enabled: true,
     *   enableCompression: true,
     *   compressionLevel: 6,
     *   redis: {
     *     host: 'localhost',
     *     port: 6379,
     *     cluster: true,
     *     nodes: [
     *       { host: 'redis-1', port: 6379 },
     *       { host: 'redis-2', port: 6379 }
     *     ]
     *   },
     *   memory: {
     *     heapSize: 1024 * 1024 * 50, // 50MB
     *     cleanupInterval: 60000 // 1 minute
     *   }
     * }
     * ```
     */
    cache?: {
        /** Maximum cache size in bytes */
        maxSize?: number;
        /** Cache strategy selection */
        strategy?: "auto" | "memory" | "redis" | "hybrid" | "distributed";
        /** Default TTL in seconds */
        ttl?: number;
        /** Redis configuration */
        redis?: {
            /** Redis server hostname */
            host?: string;
            /** Redis server port */
            port?: number;
            /** Redis authentication password */
            password?: string;
            /** Enable Redis cluster mode */
            cluster?: boolean;
            /** Cluster node configurations */
            nodes?: Array<{
                host: string;
                port: number;
            }>;
        };
        /** Memory cache configuration */
        memory?: MemoryConfig;
        /** Enable caching system */
        enabled?: boolean;
        /** Enable cache compression */
        enableCompression?: boolean;
        /** Compression level (0-9) */
        compressionLevel?: number;
    };
    /**
     * Performance and Engine Optimization settings.
     *
     * These settings are delegated directly to the XHSC engine
     * for maximum efficiency and ultra-low latency execution.
     *
     * @example
     * ```typescript
     * performance: {
     *   enabled: true,
     *   batchSize: 100,
     *   connectionPooling: true,
     *   intelligence: true,
     *   preAllocate: true
     * }
     * ```
     */
    performance?: {
        /** Enable engine-level optimizations (default: true) */
        enabled?: boolean;
        /**
         * Execution batch size for bulk operations.
         * Higher values improve throughput but may increase latency.
         * @default 100
         */
        batchSize?: number;
        /**
         * Enable high-performance connection pooling.
         * DRAMATICALLY improves performance for high-concurrency workloads.
         * @default true
         */
        connectionPooling?: boolean;
        /**
         * Enable Engine Intelligence (Pattern Recognition).
         * Enables smart resource management, GC hints, and predictive optimizations.
         * @default false
         */
        intelligence?: boolean;
        /**
         * Pre-allocate system resources at startup.
         * Prevents resource contention during peak loads.
         * @default false
         */
        preAllocate?: boolean;
    };
    server?: {
        port?: number;
        host?: string;
        trustProxy?: string[];
        jsonLimit?: string;
        urlEncodedLimit?: string;
        enableMiddleware?: boolean;
        autoParseJson?: 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;
        };
        /**
         * Automatically kill any process already using the required port.
         * Useful for resolving "Address already in use" (EADDRINUSE) errors automatically.
         * @default true
         */
        autoKillConflict?: boolean;
        /** Enables XHSC (XyPriss Hyper-System Core). This option cannot be turned off. */
        xhsc?: boolean;
        /**
         * XEMS automated session security.
         * Enables auto-rotating secure sessions in memory.
         */
        xems?: XemsTypes;
    };
    /**
     * Multi-server configuration for creating multiple server instances
     *
     * Allows running multiple server instances with different configurations,
     * ports, and route scopes from a single configuration.
     *
     *
     */
    multiServer?: {
        /** Enable multi-server mode */
        enabled?: boolean;
        /** Array of server configurations */
        servers?: MultiServerConfig[];
    };
    /**
     * Request management configuration for handling timeouts, network quality, and request lifecycle
     *
     * @example
     * ```typescript
     * requestManagement: {
     *   timeout: {
     *     enabled: true,
     *     defaultTimeout: 30000, // 30 seconds
     *     routes: {
     *       "/api/upload": 300000, // 5 minutes for uploads
     *       "/api/quick": 5000     // 5 seconds for quick endpoints
     *     }
     *   },
     *   networkQuality: {
     *     enabled: true,
     *     rejectOnPoorConnection: true,
     *     minBandwidth: 1000, // 1KB/s minimum
     *     maxLatency: 2000    // 2 seconds max latency
     *   },
     *   concurrency: {
     *     maxConcurrentRequests: 1000,
     *     maxPerIP: 50,
     *     queueTimeout: 10000
     *   }
     * }
     * ```
     */
    requestManagement?: {
        /** Request timeout configuration */
        timeout?: {
            /** Enable request timeout management */
            enabled?: boolean;
            /** Default timeout for all requests in milliseconds */
            defaultTimeout?: number;
            /** Route-specific timeout overrides */
            routes?: Record<string, number>;
            /** Timeout for static file serving */
            staticTimeout?: number;
            /** Custom timeout handler */
            onTimeout?: (req: any, res: any) => void;
            /** Include stack trace in timeout errors */
            includeStackTrace?: boolean;
            /** Custom timeout error message */
            errorMessage?: string;
        };
        /** Network quality detection and management */
        networkQuality?: {
            /** Enable network quality monitoring */
            enabled?: boolean;
            /** Reject requests on poor network conditions */
            rejectOnPoorConnection?: boolean;
            /** Minimum bandwidth requirement in bytes/second */
            minBandwidth?: number;
            /** Maximum acceptable latency in milliseconds */
            maxLatency?: number;
            /** Network quality check interval in milliseconds */
            checkInterval?: number;
            /** Custom network quality handler */
            onPoorNetwork?: (req: any, res: any, metrics: any) => void;
        };
        /** Request concurrency management */
        concurrency?: {
            /** Maximum concurrent requests server-wide */
            maxConcurrentRequests?: number;
            /** Maximum concurrent requests per IP */
            maxPerIP?: number;
            /** Maximum time to wait in queue in milliseconds */
            queueTimeout?: number;
            /** Priority queue for different request types */
            priorityQueue?: {
                enabled?: boolean;
                priorities?: Record<string, number>;
            };
            /** Custom queue overflow handler */
            onQueueOverflow?: (req: any, res: any) => void;
            /** Maximum number of requests allowed in the queue (Rust layer) */
            maxQueueSize?: number;
        };
        /** Request lifecycle monitoring */
        lifecycle?: {
            /** Enable request lifecycle tracking */
            enabled?: boolean;
            /** Track request start time */
            trackStartTime?: boolean;
            /** Track request processing stages */
            trackStages?: boolean;
            /** Maximum request processing time before warning */
            warnAfter?: number;
            /** Custom lifecycle event handler */
            onLifecycleEvent?: (event: string, req: any, data: any) => void;
        };
        /** Request retry and circuit breaker */
        resilience?: {
            /** Enable request retry mechanism */
            retryEnabled?: boolean;
            /** Maximum retry attempts */
            maxRetries?: number;
            /** Retry delay in milliseconds */
            retryDelay?: number;
            /** Circuit breaker configuration */
            circuitBreaker?: {
                enabled?: boolean;
                failureThreshold?: number;
                resetTimeout?: number;
                monitoringPeriod?: number;
            };
        };
        /** Request size and payload management */
        payload?: {
            /** Maximum request body size in bytes */
            maxBodySize?: number;
            /** Maximum URL length */
            maxUrlLength?: number;
            /** Maximum number of form fields */
            maxFields?: number;
            /** Custom payload validation */
            customValidator?: (req: any) => boolean | Promise<boolean>;
        };
    };
    /**
     * File upload configuration for handling multipart/form-data requests.
     *
     * Comprehensive file upload settings including size limits, allowed types,
     * storage options, and security features for file handling.
     *
     * @example
     * ```typescript
     * fileUpload: {
     *   enabled: true,
     *   maxFileSize: 10 * 1024 * 1024, // 10MB
     *   maxFiles: 5,
     *   allowedMimeTypes: ['image/jpeg', 'image/png', 'application/pdf'],
     *   allowedExtensions: ['.jpg', '.jpeg', '.png', '.pdf'],
     *   destination: './uploads',
     *   filename: (req, file, callback) => {
     *     callback(null, `${Date.now()}-${file.originalname}`);
     *   },
     *   limits: {
     *     fieldNameSize: 100,
     *     fieldSize: 1024,
     *     fields: 10,
     *     fileSize: 10 * 1024 * 1024,
     *     files: 5,
     *     headerPairs: 2000
     *   },
     *   preservePath: false,
     *   fileFilter: (req, file, callback) => {
     *     // Custom file validation logic
     *     callback(null, true);
     *   },
     *   storage: 'disk', // 'disk' | 'memory' | 'custom'
     *   createParentPath: true,
     *   abortOnLimit: false,
     *   responseOnLimit: 'File too large',
     *   useTempFiles: false,
     *   tempFileDir: '/tmp',
     *   parseNested: true,
     *   debug: false
     * }
     * ```
     */
    fileUpload?: FileUploadConfig;
    /**
     * Security configuration for the server.
     *
     * Comprehensive security settings including authentication, encryption,
     * CSRF protection, security headers, and various security features.
     *
     * @example
     * ```typescript
     * security: {
     *   enabled: true,
     *   level: 'enhanced',
     *   csrf: true,
     *   helmet: true,
     *   xss: true,
     *   bruteForce: true,
     *   authentication: {
     *     jwt: {
     *       secret: 'your-secret-key',
     *       expiresIn: '24h'
     *     }
     *   }
     * }
     * ```
     */
    security?: SecurityConfig & {
        /** Enable security middleware */
        enabled?: boolean;
    };
    workerPool?: {
        enabled?: boolean;
        config?: {
            cpu?: {
                min: number | "auto";
                max: number | "auto";
            };
            io?: {
                min: number | "auto";
                max: number | "auto";
            };
            maxConcurrentTasks?: number | "auto";
        };
    };
    logging?: {
        enabled?: boolean;
        level?: LogLevel$1;
        instanceName?: string;
        components?: {
            server?: boolean;
            cache?: boolean;
            cluster?: boolean;
            performance?: boolean;
            plugins?: boolean;
            security?: boolean;
            routes?: boolean;
            userApp?: boolean;
            console?: boolean;
            other?: boolean;
            middleware?: boolean;
            router?: boolean;
            typescript?: boolean;
            acpes?: boolean;
            ipc?: boolean;
            memory?: boolean;
            lifecycle?: boolean;
            routing?: boolean;
            xems?: boolean;
        };
        componentLevels?: Partial<Record<LogComponent, ComponentLogConfig | LogLevel$1>>;
        types?: {
            startup?: boolean;
            warnings?: boolean;
            errors?: boolean;
            performance?: boolean;
            debug?: boolean;
            hotReload?: boolean;
            portSwitching?: boolean;
            lifecycle?: boolean;
        };
        consoleInterception?: DeepPartial<ConsoleInterceptionConfig>;
        customLogger?: (level: LogLevel$1, component: LogComponent, message: string, ...args: any[]) => void;
        format?: {
            timestamps?: boolean;
            colors?: boolean;
            palette?: Partial<Record<string, string>>;
            componentColors?: Partial<Record<LogComponent, string>>;
            prefix?: boolean;
            compact?: boolean;
            includeMemory?: boolean;
            includeProcessId?: boolean;
            maxLineLength?: number;
        };
        buffer?: {
            enabled?: boolean;
            maxSize?: number;
            flushInterval?: number;
            autoFlush?: boolean;
        };
        errorHandling?: {
            maxErrorsPerMinute?: number;
            suppressRepeatedErrors?: boolean;
            suppressAfterCount?: number;
            resetSuppressionAfter?: number;
        };
        file?: {
            enabled?: boolean;
            path?: string;
            maxSize?: number;
            maxFiles?: number;
            rotateDaily?: boolean;
        };
        remote?: {
            enabled?: boolean;
            endpoint?: string;
            apiKey?: string;
            batchSize?: number;
            flushInterval?: number;
        };
    };
    /**
     * Response control configuration for when routes don't match.
     *
     * Allows customization of the response sent when no routes match the request.
     * Useful for multi-server setups where different servers need different behaviors.
     *
     * @example
     * ```typescript
     * responseControl: {
     *   enabled: true,
     *   statusCode: 404,
     *   content: "Custom not found message",
     *   contentType: "text/plain",
     *   headers: { "X-Custom-Header": "value" },
     *   handler: (req, res) => {
     *     res.status(404).json({ error: "Not found", path: req.path });
     *   }
     * }
     * ```
     */
    responseControl?: {
        /** Enable custom response control (default: false) */
        enabled?: boolean;
        /** HTTP status code to send (default: 404) */
        statusCode?: number;
        /** Response content or message */
        content?: string | object;
        /** Content type header (default: "text/plain") */
        contentType?: string;
        /** Custom headers to set */
        headers?: Record<string, string>;
        /** Custom response handler function */
        handler?: (req: XyPrisRequest$1, res: XyPrisResponse$1) => void | Promise<void>;
    };
    /**
     * Network plugin configuration for enhanced networking capabilities.
     *
     * Provides comprehensive control over connection management, compression,
     * rate limiting, and proxy functionality features.
     *
     * @example
     * ```typescript
     * network: {
     *   connection: {
     *     http2: { enabled: true, maxConcurrentStreams: 100 },
     *     keepAlive: { enabled: true, timeout: 30000 },
     *     connectionPool: { maxConnections: 1000, timeout: 5000 }
     *   },
     *   compression: {
     *     enabled: true,
     *     algorithms: ["gzip", "deflate"],
     *     level: 6,
     *     threshold: 1024
     *   },
     *   rateLimit: {
     *     enabled: true,
     *     strategy: "sliding-window",
     *     global: { requests: 1000, window: "1h" },
     *     perIP: { requests: 100, window: "1m" }
     *   },
     *   proxy: {
     *     enabled: true,
     *     upstreams: [
     *       { host: "backend1.example.com", port: 8080, weight: 1 },
     *       { host: "backend2.example.com", port: 8080, weight: 2 }
     *     ],
     *     loadBalancing: "weighted-round-robin"
     *   }
     * }
     * ```
     */
    network?: {
        /**
         * Connection management plugin configuration.
         *
         * Handles HTTP/2 server push, keep-alive connections, and connection pooling
         * with intelligent resource detection and proper cache control.
         */
        connection?: {
            /** Enable connection plugin */
            enabled?: boolean;
            /** HTTP/2 configuration */
            http2?: {
                /** Enable HTTP/2 support */
                enabled?: boolean;
                /** Maximum concurrent streams per connection */
                maxConcurrentStreams?: number;
                /** Initial window size for flow control */
                initialWindowSize?: number;
                /** Enable server push */
                serverPush?: boolean;
            };
            /** Keep-alive configuration */
            keepAlive?: {
                /** Enable keep-alive connections */
                enabled?: boolean;
                /** Keep-alive timeout in milliseconds */
                timeout?: number;
                /** Maximum requests per connection */
                maxRequests?: number;
            };
            /** Connection pool configuration */
            connectionPool?: {
                /** Maximum number of connections */
                maxConnections?: number;
                /** Connection timeout in milliseconds */
                timeout?: number;
                /** Idle timeout in milliseconds */
                idleTimeout?: number;
            };
        };
        /**
         * Firewall management plugin configuration.
         *
         * Provides automated port management and IP-based access control
         * via native system firewall managers (ufw, iptables).
         */
        firewall?: {
            /** Enable firewall management plugin */
            enabled?: boolean;
            /** Automatically open required ports (80, 443, and server port) */
            autoOpen?: boolean;
            /** List of explicitly allowed IPs or CIDR blocks */
            allowedIPs?: string[];
        };
        /**
         * Compression plugin configuration.
         *
         * Provides compression with multiple algorithms,
         * intelligent threshold detection, and proper content-type filtering.
         */
        compression?: {
            /** Enable compression plugin */
            enabled?: boolean;
            /** Supported compression algorithms */
            algorithms?: ("gzip" | "br" | "deflate" | "zstd")[];
            /** Compression level (1-9, higher = better compression, slower) */
            level?: number;
            /** Minimum response size to compress (bytes) */
            threshold?: number;
            /** Content types to compress */
            contentTypes?: string[];
            /** Memory level for compression (1-9) */
            memLevel?: number;
            /** Window size for compression */
            windowBits?: number;
        };
        /**
         * Rate limiting plugin configuration.
         *
         * Uses XyPriss cache system for distributed rate limiting with
         * secure key hashing and multiple limiting strategies.
         */
        rateLimit?: {
            /** Enable rate limiting plugin */
            enabled?: boolean;
            /** Rate limiting strategy */
            strategy?: "fixed-window" | "sliding-window" | "token-bucket";
            /** Global rate limits */
            global?: {
                /** Maximum requests per window */
                requests?: number;
                /** Time window (e.g., "1m", "1h", "1d") */
                window?: string;
            };
            /** Per-IP rate limits */
            perIP?: {
                /** Maximum requests per IP per window */
                requests?: number;
                /** Time window (e.g., "1m", "1h", "1d") */
                window?: string;
            };
            /** Per-user rate limits (requires authentication) */
            perUser?: {
                /** Maximum requests per user per window */
                requests?: number;
                /** Time window (e.g., "1m", "1h", "1d") */
                window?: string;
            };
            /** Custom rate limit headers */
            headers?: {
                /** Include rate limit headers in response */
                enabled?: boolean;
                /** Custom header prefix */
                prefix?: string;
            };
            /** Redis configuration for distributed rate limiting */
            redis?: {
                /** Redis host */
                host?: string;
                /** Redis port */
                port?: number;
                /** Redis password */
                password?: string;
                /** Redis database number */
                db?: number;
                /** Key prefix for rate limit data */
                keyPrefix?: string;
            };
        };
        /**
         * Proxy plugin configuration.
         *
         * Provides load balancing, health checks, and failover capabilities
         * with secure upstream selection and real HTTP health monitoring.
         */
        proxy?: {
            /** Enable proxy plugin */
            enabled?: boolean;
            /** Upstream servers configuration */
            upstreams?: Array<{
                /** Upstream server hostname */
                host: string;
                /** Upstream server port */
                port?: number;
                /** Server weight for load balancing */
                weight?: number;
                /** Maximum connections to this upstream */
                maxConnections?: number;
                /** Health check path */
                healthCheckPath?: string;
            }>;
            /** Load balancing strategy */
            loadBalancing?: "round-robin" | "weighted-round-robin" | "ip-hash" | "least-connections";
            /** Health check configuration */
            healthCheck?: {
                /** Enable health checks */
                enabled?: boolean;
                /** Health check interval in milliseconds */
                interval?: number;
                /** Health check timeout in milliseconds */
                timeout?: number;
                /** Health check path */
                path?: string;
                /** Unhealthy threshold (failed checks before marking unhealthy) */
                unhealthyThreshold?: number;
                /** Healthy threshold (successful checks before marking healthy) */
                healthyThreshold?: number;
            };
            /** Proxy timeout configuration */
            timeout?: number;
            /** Enable request/response logging */
            logging?: boolean;
            /** Custom error handling */
            onError?: (error: any, req: any, res: any) => void;
        };
    };
    /**
     * Native Data Conversion configuration (XHSC & XyPriss Hybrid).
     *
     * Enables high-performance, native conversion between different data formats
     * (XML, JSON, YAML) directly at the engine level.
     */
    conversion?: {
        /** Enable native conversion system (default: false) */
        enabled?: boolean;
        /**
         * Automatically convert incoming XML payloads to JSON.
         * The resulting JSON is accessible via `req.body`.
         */
        xmlToJson?: boolean;
        /**
         * Prefix for XML attributes when converted to JSON keys (default: "@").
         */
        attributePrefix?: string;
        /**
         * Key name for XML text content when a node has both attributes and text (default: "#text").
         */
        textContentKey?: string;
        /**
         * Maximum payload size for conversion in bytes or string (e.g. "10mb").
         */
        maxConversionSize?: number | string;
        /**
         * Automatically reply in the original format of the request.
         * For example, if the request was XML, the JSON response will be converted back to XML.
         */
        autoReply?: boolean;
        /**
         * Enable strict XML parsing. If true, malformed XML returns 400.
         * If false, the original body is forwarded to the handler.
         */
        strictParsing?: boolean;
        /**
         * Enable content sniffing for missing Content-Type headers.
         * If the body starts with '<', it will be treated as XML.
         */
        contentSniffing?: boolean;
    };
}

/**
 * @fileoverview Main export file for XyPriss integration types
 *
 * This file provides a centralized export point for all XyPriss integration
 * types, organized into modular categories for better maintainability.
 *
 * @version 4.5.11
 * @author XyPrissJS Team
 * @since 2025-01-06
 *
 * @example
 * ```typescript
 * // Import all types
 * import * as XyPrissTypes from './types';
 *
 * // Import specific categories
 * import { CacheConfig, SecurityConfig } from './types';
 *
 * // Import from specific modules
 * import { PerformanceMetrics } from './types/performance';
 * import { RouteConfig } from './types/routing';
 * ```
 */

declare global {
    /**
     * **XyPriss System Variables Manager (`__sys__`)**
     *
     * Provides centralized access to system-level variables, environment detection, and dynamic
     * configuration management. This global instance serves as a type-safe wrapper around
     * application metadata and environment utilities.
     *
     * @global
     * @type {XyPrissXHSC}
     *
     * @example
     * ```typescript
     * // Environment Detection
     * if (__sys__.__env__.isProduction()) {
     *   console.log("Running in production mode");
     * }
     *
     * // Dynamic Variable Management
     * __sys__.vars.set("appName", "MyXyPrissApp");
     * const version = __sys__.vars.get("version", "1.0.0");
     *
     * // Bulk Update
     * __sys__.vars.update({
     *   author: "Nehonix",
     *   debug: true
     * });
     * ```
     *
     * @see {@link https://xypriss.nehonix.com/docs/features/sys-globals?kw=the%20__sys__}
     */
    var __sys__: XyPrissXHSC;
    /**
     * **XyPriss Configuration Manager (`__cfg__`)**
     *
     * A singleton interface for managing the core XyPriss server configuration.
     * It handles deep merging of options, default values, and provides a single source
     * of truth for all server components (security, performance, routing, etc.).
     *
     * @global
     * @type {typeof Configs}
     *
     * @example
     * ```typescript
     * // Accessing Configuration
     * const serverPort = __cfg__.get("server")?.port;
     * const isSecurityEnabled = __cfg__.get("security")?.enabled;
     *
     * // Updating Configuration (Deep Merge)
     * __cfg__.update("performance", {
     *   slowRequestThreshold: 1000
     * });
     *
     * // Check Initialization State
     * if (__cfg__.isInitialized()) {
     *   console.log("Server configuration is ready");
     * }
     * ```
     *
     * @see {@link https://github.com/Nehonix-Team/XyPriss/blob/master/docs/CFG_API.md}
     */
    var __cfg__: typeof ConfigurationManager;
    /**
     * **XyPriss Immutable Constants (`__const__`)**
     *
     * A global registry for immutable application constants. Once a value is set
     * via `__const__.vars.set()`, it cannot be modified or redefined, ensuring
     * data integrity across the entire application lifecycle.
     *
     * @global
     * @type {XyPrissConst}
     * @version 3.0.0
     *
     * @example
     * ```typescript
     * // Defining a constant (only once)
     * __const__.vars.set('SERVER_PORT', 8080);
     *
     * // Attempting to redefine will throw an error
     * try {
     *   __const__.vars.set('SERVER_PORT', 9000);
     * } catch (e) {
     *   console.error(e.message); // Cannot redefine constant "SERVER_PORT"
     * }
     *
     * // Accessing a constant
     * const port = __const__.vars.get('SERVER_PORT');
     *
     * // Making an object deeply immutable
     * const config = __const__.vars.make({ port: 8080 });
     * config.port = 9000; // Throws error!
     * ```
     *@see {@link https://github.com/Nehonix-Team/XyPriss/blob/master/docs/CONST_API.md}
     * @see {@link https://github.com/Nehonix-Team/XyPriss/blob/master/docs/GLOBAL_APIS.md}
     */
    var __const__: XyPrissConst;
    /**
     * @fileoverview Comprehensive server options interface for XyPriss integration
     *
     * This interface provides complete configuration options for creating high-performance,
     * secure servers with advanced features including caching, clustering,
     * performance optimization, and Go integration.
     *
     * @interface ServerOptions
     * @version 4.5.11
     * @author XyPrissJS Team
     * @since 2025-01-06
     *
     * @example
     * ```typescript
     * import { createServer, ServerOptions } from 'xypriss';
     *
     * const serverOptions: ServerOptions = {
     *   env: 'production',
     *   cache: {
     *     strategy: 'hybrid',
     *     maxSize: 1024 * 1024 * 100, // 100MB
     *     ttl: 3600,
     *     enabled: true,
     *     enableCompression: true
     *   },
     *   security: {
     *     encryption: true,
     *     cors: true,
     *     helmet: true
     *   },
     *   performance: {
     *     optimizationEnabled: true,
     *     aggressiveCaching: true,
     *     parallelProcessing: true
     *   },
     *   server: {
     *     port: 3000,
     *     host: '0.0.0.0',
     *     autoPortSwitch: {
     *       enabled: true,
     *       maxAttempts: 5
     *     }
     *   }
     * };
     *
     * const app = createServer(serverOptions);
     * ```
     */
    type ServerOptions = XServerOptions;
}

/**
 * XyPriss Middleware API Types
 * Comprehensive types for the fluent middleware management API
 */
type MiddlewarePriority = "critical" | "high" | "normal" | "low";
interface SecurityMiddlewareConfig {
    helmet?: boolean | {
        contentSecurityPolicy?: boolean | object;
        crossOriginEmbedderPolicy?: boolean;
        crossOriginOpenerPolicy?: boolean;
        crossOriginResourcePolicy?: boolean;
        dnsPrefetchControl?: boolean;
        frameguard?: boolean | object;
        hidePoweredBy?: boolean;
        hsts?: boolean | object;
        ieNoOpen?: boolean;
        noSniff?: boolean;
        originAgentCluster?: boolean;
        permittedCrossDomainPolicies?: boolean;
        referrerPolicy?: boolean | object;
        xssFilter?: boolean;
    };
    cors?: boolean | {
        origin?: string | RegExp | (string | RegExp)[] | boolean;
        methods?: string | string[];
        allowedHeaders?: string | string[];
        exposedHeaders?: string | string[];
        credentials?: boolean;
        maxAge?: number;
        preflightContinue?: boolean;
        optionsSuccessStatus?: number;
    };
    rateLimit?: boolean | {
        windowMs?: number;
        max?: number;
        message?: string | {
            error?: string;
            message?: string;
            retryAfter?: number;
            [key: string]: any;
        };
        standardHeaders?: boolean;
        legacyHeaders?: boolean;
        store?: any;
        keyGenerator?: (req: any) => string;
        handler?: (req: any, res: any, next: any) => void;
        onLimitReached?: (req: any, res: any, options: any) => void;
    };
    csrf?: boolean | {
        secret?: string;
        cookie?: boolean | object;
        value?: (req: any) => string;
        ignoreMethods?: string[];
    };
    compression?: boolean | {
        level?: number;
        threshold?: number;
        filter?: (req: any, res: any) => boolean;
        chunkSize?: number;
        windowBits?: number;
        memLevel?: number;
        strategy?: number;
    };
}
/**
 * XyPriss Middleware API Interface
 * Simple, practical interface for middleware management
 * Extends the base MiddlewareAPIInterface for compatibility
 */
interface XyPrissMiddlewareAPI {
    /**
     * Register a custom middleware function
     */
    register(middleware: Function, options?: {
        name?: string;
        priority?: MiddlewarePriority;
        routes?: string[];
    }): XyPrissMiddlewareAPI;
    /**
     * Initialize default middleware with security configuration
     */
    initializeWithConfig(securityConfig?: SecurityConfig): void;
    /**
     * Configure security middleware bundle
     */
    security(config?: SecurityMiddlewareConfig): XyPrissMiddlewareAPI;
    /**
     * Configure CORS middleware
     */
    cors(config?: SecurityMiddlewareConfig["cors"]): XyPrissMiddlewareAPI;
    /**
     * Configure rate limiting middleware
     */
    rateLimit(config?: SecurityMiddlewareConfig["rateLimit"]): XyPrissMiddlewareAPI;
    /**
     * Configure helmet security headers
     */
    helmet(config?: SecurityMiddlewareConfig["helmet"]): XyPrissMiddlewareAPI;
    /**
     * Configure CSRF protection
     */
    csrf(config?: SecurityMiddlewareConfig["csrf"]): XyPrissMiddlewareAPI;
    /**
     * Configure compression middleware
     */
    compression(config?: SecurityMiddlewareConfig["compression"]): XyPrissMiddlewareAPI;
    /**
     * Get middleware statistics
     */
    stats(): {
        total: number;
        enabled: number;
        disabled: number;
        byType: {
            custom: number;
            builtin: number;
        };
        byPriority: {
            critical: number;
            high: number;
            normal: number;
            low: number;
        };
    };
    /**
     * List all registered middleware
     */
    list(): Array<{
        id: string;
        name: string;
        enabled: boolean;
        priority: MiddlewarePriority;
        type: "custom" | "builtin";
    }>;
    /**
     * Clear all middleware
     */
    clear(): XyPrissMiddlewareAPI;
    /**
     * Optimize middleware order by priority
     */
    optimize(): XyPrissMiddlewareAPI;
    unregister(id: string): XyPrissMiddlewareAPI;
    enable(id: string): XyPrissMiddlewareAPI;
    disable(id: string): XyPrissMiddlewareAPI;
    getInfo(id?: string): any;
    getStats(): any;
    getConfig(): any;
}

interface MultiServerInstance {
    id: string;
    app: XyPrissApp;
    config: MultiServerConfig;
    port: number;
    host: string;
}
declare class MultiServerManager {
    private logger;
    private baseConfig;
    private mainApp;
    private servers;
    constructor(baseConfig: ServerOptions$1, logger: Logger, mainApp?: any);
    /**
     * Create multiple server instances based on configuration
     */
    createServers(serverConfigs: MultiServerConfig[]): Promise<MultiServerInstance[]>;
    /**
     * Create a single server instance with merged configuration
     * Uses the centralized Configs class for proper configuration management
     */
    private createServerInstance;
    /**
     * Apply route filtering by copying and filtering routes from main app
     */
    private applyRouteFilteringFromMainApp;
    /**
     * Copy and filter router middleware from main app
     */
    private copyRouterMiddlewareFromMainApp;
    /**
     * Start all server instances
     */
    startAllServers(): Promise<void>;
    /**
     * Stop all server instances
     */
    stopAllServers(): Promise<void>;
    /**
     * Get all server instances
     */
    getAllServers(): MultiServerInstance[];
    /**
     * Get a specific server instance by ID
     */
    getServer(id: string): MultiServerInstance | undefined;
    /**
     * Stop a specific server instance by port
     */
    stopServer(port: number): Promise<boolean>;
    /**
     * Get server statistics
     */
    getStats(): any;
}

/**
 * XyPriss application interface with advanced features.
 *
 * Extends the standard application with high-performance caching,
 * performance optimization, security features, clustering, and
 * comprehensive monitoring capabilities.
 *
 * @interface XyPrissApp
 * @version 4.5.11
 * @author XyPrissJS Team
 * @since 2025-01-06
 *
 * @example
 * ```typescript
 * import { createServer } from 'xypriss';
 *
 * const app = createServer({
 *   cache: { strategy: 'hybrid' },
 *   performance: { optimizationEnabled: true }
 * });
 *
 * // Use enhanced route methods with caching
 * app.getWithCache('/api/users', {
 *   cache: { ttl: 300, tags: ['users'] },
 *   security: { auth: true }
 * }, async (req, res) => {
 *   const users = await getUsersFromDB();
 *   res.success(users);
 * });
 *
 * // Start the server
 * await app.start();
 * ```
 */
interface XyApp {
    get(path: string, ...handlers: RequestHandler[]): void;
    post(path: string, ...handlers: RequestHandler[]): void;
    put(path: string, ...handlers: RequestHandler[]): void;
    delete(path: string, ...handlers: RequestHandler[]): void;
    patch(path: string, ...handlers: RequestHandler[]): void;
    options(path: string, ...handlers: RequestHandler[]): void;
    head(path: string, ...handlers: RequestHandler[]): void;
    connect(path: string, ...handlers: RequestHandler[]): void;
    trace(path: string, ...handlers: RequestHandler[]): void;
    all(path: string, ...handlers: RequestHandler[]): void;
    /**
     * Register a route-level redirect from one path to another path or external URL.
     *
     * This is a convenience API for creating permanent (301) or temporary (302)
     * redirects at the route level. It is more efficient than registering a full
     * route handler for simple redirection use cases.
     *
     * @param from - The source path to redirect from (e.g., "/old-page").
     * @param to - The destination path or full URL (e.g., "/new-page" or "https://example.com").
     * @param statusCode - HTTP status code to use (default: 301). Accepts 301 or 302.
     *
     * @example
     * ```typescript
     * // Permanent redirect to a new internal path
     * app.redirect("/old-api", "/v2/api");
     *
     * // Temporary redirect to an external URL
     * app.redirect("/promo", "https://promo.example.com", 302);
     * ```
     */
    redirect(from: string, to: string, statusCode?: 301 | 302): void;
    use(...args: any[]): void;
    set(setting: string, val: any): void;
    getSetting(setting: string): any;
    enabled(setting: string): boolean;
    disabled(setting: string): boolean;
    enable(setting: string): void;
    disable(setting: string): void;
    engine(ext: string, fn: (path: string, options: object, callback: (e: any, rendered?: string) => void) => void): XyPrissApp;
    param(name: string, handler: (req: any, res: any, next: any, value: any, name: string) => void): void;
    path(): string;
    render(view: string, options?: object, callback?: (err: Error | null, html?: string) => void): void;
    route(path: string): any;
    locals: Record<string, any>;
    mountpath: string;
    settings: Record<string, any>;
    /**
     * Secure cache adapter for high-performance data access.
     *
     * Provides access to the underlying cache system with
     * encryption, compression, and intelligent strategies.
     */
    cache?: SecureCacheAdapter;
    /**
     * XyPriss Encrypted Memory Store (XEMS) runner for this instance.
     * Provides access to isolated or persistent memory storage.
     */
    xems?: any;
    /**
     * Server configuration options.
     *
     * Provides access to the configuration options passed to createServer.
     */
    configs?: ServerOptions$1;
    /**
     * Invalidate cache entries by pattern.
     *
     * @param pattern - Cache key pattern to invalidate
     * @returns Promise that resolves when invalidation is complete
     *
     * @example
     * ```typescript
     * // Invalidate all user-related cache entries
     * await app.invalidateCache('users:*');
     * ```
     */
    invalidateCache: (pattern: string) => Promise<void>;
    /**
     * Get comprehensive cache statistics.
     *
     * @returns Promise that resolves to cache statistics
     *
     * @example
     * ```typescript
     * const stats = await app.getCacheStats();
     * console.log(`Hit rate: ${stats.hitRate * 100}%`);
     * ```
     */
    getCacheStats: () => Promise<any>;
    /**
     * Warm up cache with predefined data.
     *
     * @param data - Array of cache entries to preload
     * @returns Promise that resolves when warmup is complete
     *
     * @example
     * ```typescript
     * await app.warmUpCache([
     *   { key: 'config:app', value: appConfig, ttl: 3600 },
     *   { key: 'users:popular', value: popularUsers, ttl: 1800 }
     * ]);
     * ```
     */
    warmUpCache: (data: Array<{
        key: string;
        value: any;
        ttl?: number;
    }>) => Promise<void>;
    /**
     * Start the XyPriss application server.
     *
     * @param callback - Callback function called when server starts (optional)
     * @returns Promise that resolves to HTTP server instance or server instance directly
     *
     * @example
     * ```typescript
     * // Start with auto port detection
     * const server = await app.start();
     *
     * // Start on specific port with callback
     * app.start(async () => {
     *   console.log('Server started on port 3000');
     * });
     * ```
     */
    start: (callback?: () => void) => Promise<Server> | Server | Promise<void> | void;
    /**
     * Stop the XyPriss server.
     *
     * @returns Promise that resolves when server is stopped
     *
     * @example
     * ```typescript
     * await app.stop();
     * console.log('Server stopped');
     * ```
     */
    stop?: () => Promise<void>;
    /**
     * Wait for server to be fully ready.
     *
     * @returns Promise that resolves when server is ready to accept requests
     *
     * @example
     * ```typescript
     * await app.start(3000);
     * await app.waitForReady();
     * console.log('Server is ready!');
     * ```
     */
    waitForReady: () => Promise<void>;
    /**
     * Get the current server port.
     *
     * @returns The port number the server is listening on
     *
     * @example
     * ```typescript
     * const currentPort = app.getPort();
     * console.log(`Server running on port ${currentPort}`);
     * ```
     */
    getPort: () => number;
    /**
     * Get the HTTP server instance.
     *
     * @returns The underlying HTTP server instance
     *
     * @example
     * ```typescript
     * const httpServer = app.getHttpServer();
     * console.log(`Server address: ${httpServer.address()}`);
     * ```
     */
    getHttpServer?: () => any;
    /**
     * Force close a specific port.
     *
     * @param port - Port number to force close
     * @returns Promise that resolves to true if port was closed successfully
     *
     * @example
     * ```typescript
     * const closed = await app.forceClosePort(3000);
     * if (closed) {
     *   console.log('Port 3000 closed successfully');
     * }
     * ```
     */
    forceClosePort: (port: number) => Promise<boolean>;
    /**
     * Create a redirect from one port to another.
     *
     * @param fromPort - Source port to redirect from
     * @param toPort - Target port to redirect to
     * @param options - Redirect configuration options
     * @returns Promise that resolves to redirect instance or boolean
     *
     * @example
     * ```typescript
     * // Redirect HTTP to HTTPS
     * const redirect = await app.redirectFromPort(80, 443, {
     *   mode: 'redirect',
     *   redirectStatusCode: 301,
     *   enableLogging: true
     * });
     * ```
     */
    redirectFromPort: (fromPort: number, toPort: number, options?: RedirectOptions) => Promise<RedirectServerInstance | boolean>;
    /**
     * Get a specific redirect instance.
     *
     * @param fromPort - Source port of the redirect
     * @returns Redirect instance or null if not found
     *
     * @example
     * ```typescript
     * const redirect = app.getRedirectInstance(80);
     * if (redirect) {
     *   console.log(`Redirecting from ${redirect.fromPort} to ${redirect.toPort}`);
     * }
     * ```
     */
    getRedirectInstance: (fromPort: number) => RedirectServerInstance | null;
    /**
     * Get the server plugin manager for route optimization and maintenance.
     *
     * @returns Server plugin manager instance or undefined if not initialized
     *
     * @example
     * ```typescript
     * const pluginManager = app.getServerPluginManager();
     * if (pluginManager) {
     *   const routeStats = pluginManager.getRouteOptimizationPlugin()?.getRouteStats();
     *   const healthMetrics = pluginManager.getServerMaintenancePlugin()?.getHealthMetrics();
     * }
     * ```
     */
    getServerPluginManager?: () => any;
    /**
     * Server plugin manager instance (for internal use).
     * Provides access to route optimization and server maintenance plugins.
     */
    serverPluginManager?: any;
    /**
     * Get all active redirect instances.
     *
     * @returns Array of all redirect instances
     *
     * @example
     * ```typescript
     * const redirects = app.getAllRedirectInstances();
     * redirects.forEach(redirect => {
     *   console.log(`${redirect.fromPort} -> ${redirect.toPort}`);
     * });
     * ```
     */
    getAllRedirectInstances: () => RedirectServerInstance[];
    /**
     * Disconnect a specific redirect.
     *
     * @param fromPort - Source port of the redirect to disconnect
     * @returns Promise that resolves to true if disconnected successfully
     *
     * @example
     * ```typescript
     * const disconnected = await app.disconnectRedirect(80);
     * if (disconnected) {
     *   console.log('Redirect from port 80 disconnected');
     * }
     * ```
     */
    disconnectRedirect: (fromPort: number) => Promise<boolean>;
    /**
     * Disconnect all active redirects.
     *
     * @returns Promise that resolves to true if all redirects were disconnected
     *
     * @example
     * ```typescript
     * const allDisconnected = await app.disconnectAllRedirects();
     * console.log(`All redirects disconnected: ${allDisconnected}`);
     * ```
     */
    disconnectAllRedirects: () => Promise<boolean>;
    /**
     * Get statistics for a specific redirect.
     *
     * @param fromPort - Source port of the redirect
     * @returns Redirect statistics or null if not found
     *
     * @example
     * ```typescript
     * const stats = app.getRedirectStats(80);
     * if (stats) {
     *   console.log(`Requests redirected: ${stats.totalRequests}`);
     * }
     * ```
     */
    getRedirectStats: (fromPort: number) => RedirectStats | null;
    getConsoleInterceptor: () => any;
    enableConsoleInterception: () => Promise<void>;
    disableConsoleInterception: () => Promise<void>;
    getConsoleStats: () => Promise<any>;
    updateConsoleConfig: (config: Partial<ConsoleInterceptionConfig>) => Promise<void>;
    enableConsoleEncryption: (key?: string) => void;
    disableConsoleEncryption: () => void;
    getRouterStats?: () => any;
    getRouterInfo?: () => any;
    warmUpRoutes?: () => Promise<void>;
    resetRouterStats?: () => void;
    /**
     * Access the middleware management API.
     *
     * @param config - Optional middleware configuration
     * @returns Middleware API interface for fluent middleware management
     *
     * @example
     * ```typescript
     * app.middleware()
     *   .register(authMiddleware, { priority: 'critical' })
     *   .register(loggingMiddleware, { priority: 'high' })
     *   .enable('auth-middleware')
     *   .optimize();
     * ```
     */
    middleware: () => XyPrissMiddlewareAPI;
    /**
     * Internal upload manager instance for file uploads
     */
    upload?: any;
    /**
     * Create single file upload middleware
     *
     * @param fieldname - Name of the form field
     * @returns Middleware for single file upload
     *
     * @example
     * ```typescript
     * app.post('/upload', app.uploadSingle('file'), (req, res) => {
     *   console.log(req.file);
     *   res.send('File uploaded');
     * });
     * ```
     */
    uploadSingle: (fieldname: string) => any;
    /**
     * Create array file upload middleware
     *
     * @param fieldname - Name of the form field
     * @param maxCount - Maximum number of files (optional)
     * @returns Middleware for array file upload
     *
     * @example
     * ```typescript
     * app.post('/upload', app.uploadArray('files', 5), (req, res) => {
     *   console.log(req.files);
     *   res.send('Files uploaded');
     * });
     * ```
     */
    uploadArray?: (fieldname: string, maxCount?: number) => any;
    /**
     * Create fields file upload middleware
     *
     * @param fields - Array of field configurations
     * @returns Middleware for multiple fields upload
     *
     * @example
     * ```typescript
     * app.post('/upload', app.uploadFields([
     *   { name: 'avatar', maxCount: 1 },
     *   { name: 'gallery', maxCount: 8 }
     * ]), (req, res) => {
     *   console.log(req.files);
     *   res.send('Files uploaded');
     * });
     * ```
     */
    uploadFields?: (fields: any[]) => any;
    /**
     * Create any file upload middleware
     *
     * @returns Middleware that accepts any files
     *
     * @example
     * ```typescript
     * app.post('/upload', app.uploadAny(), (req, res) => {
     *   console.log(req.files);
     *   res.send('Files uploaded');
     * });
     * ```
     */
    uploadAny?: () => any;
    /**
     * Scale up the cluster by adding workers.
     *
     * @param count - Number of workers to add (optional, defaults to optimal count)
     * @returns Promise that resolves when scaling is complete
     *
     * @example
     * ```typescript
     * // Add 2 workers
     * await app.scaleUp?.(2);
     *
     * // Add optimal number of workers
     * await app.scaleUp?.();
     * ```
     */
    scaleUp?: (count?: number) => Promise<void>;
    /**
     * Scale down the cluster by removing workers.
     *
     * @param count - Number of workers to remove (optional)
     * @returns Promise that resolves when scaling is complete
     *
     * @example
     * ```typescript
     * // Remove 1 worker
     * await app.scaleDown?.(1);
     * ```
     */
    scaleDown?: (count?: number) => Promise<void>;
    /**
     * Automatically scale the cluster based on current load.
     *
     * @returns Promise that resolves when auto-scaling is complete
     *
     * @example
     * ```typescript
     * await app.autoScale?.();
     * ```
     */
    autoScale?: () => Promise<void>;
    /**
     * Get comprehensive cluster metrics.
     *
     * @returns Promise that resolves to cluster metrics
     *
     * @example
     * ```typescript
     * const metrics = await app.getClusterMetrics?.();
     * console.log(`Active workers: ${metrics.activeWorkers}`);
     * ```
     */
    getClusterMetrics?: () => Promise<any>;
    /**
     * Get cluster health status.
     *
     * @returns Promise that resolves to cluster health information
     *
     * @example
     * ```typescript
     * const health = await app.getClusterHealth?.();
     * console.log(`Cluster status: ${health.status}`);
     * ```
     */
    getClusterHealth?: () => Promise<any>;
    /**
     * Get all worker processes.
     *
     * @returns Array of worker process information
     *
     * @example
     * ```typescript
     * const workers = app.getAllWorkers?.();
     * workers?.forEach(worker => {
     *   console.log(`Worker ${worker.id}: ${worker.status}`);
     * });
     * ```
     */
    getAllWorkers?: () => any[];
    /**
     * Get the optimal worker count for current system.
     *
     * @returns Promise that resolves to optimal worker count
     *
     * @example
     * ```typescript
     * const optimal = await app.getOptimalWorkerCount?.();
     * console.log(`Optimal worker count: ${optimal}`);
     * ```
     */
    getOptimalWorkerCount?: () => Promise<number>;
    /**
     * Restart the entire cluster.
     *
     * @returns Promise that resolves when cluster restart is complete
     *
     * @example
     * ```typescript
     * await app.restartCluster?.();
     * console.log('Cluster restarted successfully');
     * ```
     */
    restartCluster?: () => Promise<void>;
    /**
     * Stop the cluster.
     *
     * @param graceful - Whether to perform graceful shutdown
     * @returns Promise that resolves when cluster is stopped
     *
     * @example
     * ```typescript
     * // Graceful shutdown
     * await app.stopCluster?.(true);
     *
     * // Force shutdown
     * await app.stopCluster?.(false);
     * ```
     */
    stopCluster?: (graceful?: boolean) => Promise<void>;
    /**
     * Broadcast message to all workers.
     *
     * @param message - Message to broadcast
     * @returns Promise that resolves when message is sent
     *
     * @example
     * ```typescript
     * await app.broadcastToWorkers?.({
     *   type: 'config-update',
     *   data: newConfig
     * });
     * ```
     */
    broadcastToWorkers?: (message: any) => Promise<void>;
    /**
     * Send message to a random worker.
     *
     * @param message - Message to send
     * @returns Promise that resolves when message is sent
     *
     * @example
     * ```typescript
     * await app.sendToRandomWorker?.({
     *   type: 'task',
     *   data: taskData
     * });
     * ```
     */
    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>;
    startAllServers?: () => Promise<void>;
    stopAllServers?: () => Promise<void>;
    getServers?: () => MultiServerInstance[];
    getServer?: (id: string) => MultiServerInstance | undefined;
    /**
     * Set the custom response control configuration for this server instance.
     * Allows customizing 404 responses, headers, and handlers.
     *
     * @param config - Response control configuration
     */
    setResponseControl(config: ServerOptions$1["responseControl"]): void;
    /**
     * Get the registry of all registered routes in the application.
     * Consolidates routes from mounted routers and direct app methods.
     *
     * @returns Array of route registry entries
     */
    getRouteRegistry?: () => any[];
}

interface XemsCommand {
    action: string;
    key?: string;
    value?: string;
    sandbox?: string;
    ttl?: string;
    rotate?: boolean;
    grace_period?: number;
}
interface XemsOptions {
    persistPath?: string;
    cacheSize?: number;
    secret?: string;
    gracePeriod?: number;
}
interface XemsResponse {
    status: string;
    data?: string;
    new_token?: string;
    error?: string;
}
/**
 * XEMS Runner (Long-running process manager)
 * Manages the persistent Rust process for in-memory storage.
 */
declare class XemsRunner {
    private process;
    private queue;
    private isReady;
    private binaryPath;
    private options;
    private logger;
    constructor(options?: XemsOptions);
    /**
     * Enables hardware-bound persistent storage for XEMS.
     */
    private static runnersByPath;
    /**
     * Internal factory for getting or creating a runner for a specific path.
     * This ensures only one process exists for a given file in the entire process.
     */
    static getInstance(pathStr: string, options?: XemsOptions): XemsRunner;
    enablePersistence(pathStr: string, secret: string, resources?: {
        cacheSize?: number;
    }): void;
    /**
     * Finds the XEMS binary location.
     * Starts with development paths, falls back to production locations.
     */
    /**
     * Strategic discovery of the xems binary across different environments.
     * Robust logic handling dev, prod, and installed contexts.
     */
    private discoverBinary;
    private init;
    private handleResponse;
    execute(cmd: XemsCommand): Promise<XemsResponse>;
    ping(): Promise<string>;
    /**
     * Set a value in a sandbox with optional TTL.
     */
    private set;
    /**
     * Get a value from a sandbox.
     */
    private get;
    /**
     * Delete/Invalidate a key in a sandbox.
     */
    private del;
    /**
     * [SESSION LAYER] Creates a new session entry.
     * Generates a random opaque token, stores `data` under it, and returns the token.
     * Use this when you don't care about the key — you just want a session handle.
     *
     * @param sandbox - The isolated namespace to store the session in
     * @param data    - Any serializable data to associate with the session
     * @param options - Optional TTL and rotation settings
     * @returns The generated session token (opaque handle)
     */
    createSession(sandbox: string, data: any, options?: {
        ttl?: string;
        rotate?: boolean;
    }): Promise<string>;
    /**
     * [SESSION LAYER] Resolves a session token back to its data.
     * Optionally rotates the token (invalidates old one, issues a new one) to
     * prevent replay attacks.
     *
     * USES ATOMIC ROTATION with Grace Period to prevent race conditions on
     * simultaneous requests.
     *
     * @param token   - The opaque session token previously returned by createSession
     * @param options - sandbox, optional rotation, optional new TTL, optional custom grace period
     * @returns `{ data, newToken? }` or `null` if the token is expired/unknown
     */
    resolveSession(token: string, options: {
        sandbox: string;
        rotate?: boolean;
        ttl?: string;
        gracePeriod?: number;
    }): Promise<{
        data: any;
        newToken?: string;
    } | null>;
    /**
     * Fluent API entry point. Returns a context for a specific sandbox.
     * @example xems.from("auth").set("user:1", data)
     */
    from(sandbox: string): XemsSandboxContext;
    /**
     * Alias for from()
     * Fluent API entry point. Returns a context for a specific sandbox.
     * @example xems.select("auth").set("user:1", data)
     */
    select(sandbox: string): XemsSandboxContext;
    /**
     * Contextual retrieval for multi-server environments.
     * Returns the XEMS instance attached to the provided app object if available,
     * otherwise returns this instance.
     */
    forApp(app: XyAppInternal | XyApp): XemsRunner;
    /**
     * Forcefully stops the XEMS process and cleans up resources.
     */
    destroy(): void;
}
/**
 * Contextual wrapper for XEMS operations within a specific sandbox.
 * Provides a cleaner, fluent API for advanced operations.
 */
declare class XemsSandboxContext {
    private runner;
    private sandbox;
    constructor(runner: XemsRunner, sandbox: string);
    /** Set a value in this sandbox */
    set(key: string, value: string, ttl?: string): Promise<boolean>;
    /** Get a value from this sandbox */
    get(key: string): Promise<string | null>;
    /** Remove a key from this sandbox */
    del(key: string): Promise<boolean>;
    /**
     * Perform an atomic rotation of a token in this sandbox.
     * Returns the original data and the new rotated token.
     */
    rotate(token: string, options?: {
        ttl?: string;
        gracePeriod?: number;
    }): Promise<{
        data: any;
        newToken?: string;
    } | null>;
    /**
     * Create a new session in this sandbox.
     */
    createSession(data: any, options?: {
        ttl?: string;
    }): Promise<string>;
}
declare const xems: XemsRunner;

/***************************************************************************
 * XyPriss - Fast And Secure
 *
 * @author Nehonix
 * @license Nehonix OSL (NOSL)
 *
 * Copyright (c) 2025 Nehonix. All rights reserved.
 *
 * This License governs the use, modification, and distribution of software
 * provided by NEHONIX under its open source projects.
 * NEHONIX is committed to fostering collaborative innovation while strictly
 * protecting its intellectual property rights.
 * Violation of any term of this License will result in immediate termination of all granted rights
 * and may subject the violator to legal action.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
 * AND NON-INFRINGEMENT.
 * IN NO EVENT SHALL NEHONIX BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * OR CONSEQUENTIAL DAMAGES ARISING FROM THE USE OR INABILITY TO USE THE SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 ***************************************************************************** */

interface XyAppInternal {
    get: (key: string) => any;
    set: (key: string, value: any) => void;
    pluginManager?: any;
    xems?: XemsRunner;
    [key: string]: any;
}
interface IFile {
    fieldname: string;
    originalname: string;
    encoding: "7bit" | "8bit" | "binary" | string;
    mimetype: `${string}/${string}`;
    destination: string;
    filename: string;
    path: string;
    size: number;
    [key: string]: any;
}
interface XyPrisRecord extends Record<string, any> {
    /**
     * Retrieves the value for the specified key. If the key does not exist or its value is undefined,
     * returns the provided defaultValue.
     *
     * @param key - The key to look up.
     * @param defaultValue - The fallback value if the key is missing.
     * @returns The value from the record, or the default value.
     */
    _get<T = any>(key: string, defaultValue?: T): T;
}
/**
 * XyPriss Request interface (Express-compatible)
 */
interface XyPrisRequest extends IncomingMessage {
    params: XyPrisRecord;
    query: XyPrisRecord;
    body: any;
    files?: IFile[];
    file?: IFile;
    csrfToken?: () => string;
    path: string;
    originalUrl: string;
    baseUrl: string;
    route?: any;
    session?: any;
    user?: any;
    headers: IncomingMessage["headers"];
    method: string;
    url: string;
    ip: string;
    ips: string[];
    cookies: Record<string, string>;
    app: XyAppInternal;
    protocol: string;
    secure: boolean;
    hostname: string;
    subdomains: string[];
    fresh: boolean;
    stale: boolean;
    xhr: boolean;
    get: (name: string) => string | undefined;
    /**
     * Redirect the current request to another URL.
     * This is a DX (Developer Experience) convenience alias for `res.redirect()`.
     *
     * **Difference between `req.redirect` and `res.redirect`:**
     * - `res.redirect()`: Standard HTTP way to respond with a redirect.
     * - `req.redirect()`: Utility alias to trigger a redirect when you only have access
     *   to the request object, or for semantic consistency with `req.forward()`.
     *
     * Both methods perform the exact same action: sending a 301/302 response and ending it.
     *
     * @param url - The target URL (relative or absolute).
     * @param status - HTTP status code (default: 302).
     *
     * @example
     * ```typescript
     * // Using req as a controller shortcut
     * if (!user.isAdmin) return req.redirect("/login");
     * ```
     */
    redirect(url: string): void;
    redirect(status: number, url: string): void;
    /**
     * **Server-Side Forward (req.forward)**
     *
     * Asynchronously forwards the current request to another endpoint (internal path or external URL)
     * and returns the response data. This is NOT a browser-side redirect; the operation
     * happens entirely on the server.
     *
     * **Features:**
     * - **Data Continuity**: By default, it inherits method, body, and headers from the original request.
     * - **Auto-resolution**: Paths like `/api/v1` are automatically resolved against `localhost:[current_port]`.
     * - **Auto-parsing**: Automatically parses JSON responses if the `Content-Type` is `application/json`.
     *
     * @param url - Target path (e.g., "/internal-api") or full URL.
     * @param options - Optional overrides (method, headers, body, or any `fetch` option).
     * @returns Promise resolving to the parsed body (Object for JSON, string for text).
     *
     * @example
     * ```typescript
     * app.get("/profile", async (req, res) => {
     *    // Forward request to an internal auth service to get user details
     *    const user = await req.forward("/internal/auth/check");
     *
     *    if (user.isBlocked) return res.status(403).send("Blocked");
     *    res.render("profile", { user });
     * });
     * ```
     */
    forward<T = any>(url: string, options?: any): Promise<T>;
}
interface SendFileOptions {
    maxAge?: number;
    headers?: Record<string, string>;
    root?: string;
    /**
     * "inline"     → browser renders the file (default)
     * "attachment" → browser downloads the file
     * string       → treated as custom filename, forces attachment
     */
    disposition?: "inline" | "attachment" | string;
    /** Override or extend the built-in MIME map for this request. */
    mimeOverrides?: Record<string, string>;
}
/**
 * XyPriss Response interface (Express-compatible)
 */
interface XyPrisResponse extends ServerResponse {
    /**
     * Serializes `data` to JSON and sends it as the response body with
     * `Content-Type: application/json`.
     *
     * @param data - The value to serialize. Must be JSON-serializable.
     *               Use {@link xJson} instead if `data` may contain circular references.
     *
     * @typeParam T - The type of the value being serialized.
     *
     * @example
     * res.json({ id: 1, name: "Alice" });
     */
    json<T>(data: T): void;
    /**
     * Sends an HTML response to the client.
     * @param htmlString - The HTML string to send.
     */
    html(htmlString: string): void;
    /**
     * Sends a response to the client.
     * @param data - The data to send.
     */
    send<T>(data: T): void;
    /**
     * Sends a file to the client.
     * @param filePath - The path to the file to send.
     * @param options - Optional send file options.
     */
    sendFile(filePath: string, options?: SendFileOptions): Promise<void> | void;
    /**
     * Sets the HTTP status code for the response.
     * @param code - The HTTP status code.
     */
    status(code: number): XyPrisResponse;
    /**
     * Sets a response header.
     * @param name - The header name.
     * @param value - The header value.
     */
    setHeader(name: string, value: string | number | readonly string[]): this;
    /**
     * Gets a response header.
     * @param name - The header name.
     * @returns The header value.
     */
    getHeader(name: string): string | number | string[] | undefined;
    removeHeader(name: string): void;
    set(field: string | Record<string, any>, value?: string | number | readonly string[]): XyPrisResponse;
    redirect(url: string): void;
    redirect(status: number, url: string): void;
    cookie(name: string, value: string, options?: any): void;
    clearCookie(name: string, options?: any): void;
    locals: Record<string, any>;
    headersSent: boolean;
    get: (name: string) => string | number | string[] | undefined;
    /**
     * The XJson API is an advanced JSON response handler
     * designed to solve serialization issues and handle
     * large data responses without limitations. It provides
     * enhanced JSON serialization capabilities that overcome
     * common problems with standard JSON responses, particularly
     * for complex data structures and large payloads.
     * @see {@link https://xypriss.nehonix.com/docs/XJSON_API?kw=XJson%20API}
     */
    xJson<T>(data: T): void;
    /**
     * Initializes a secure XEMS session and links it to the response.
     * This automatically generates a token, stores the data in the "XEMS" core,
     * and sets the necessary security headers and cookies.
     * @param data The data to store in the session
     * @param sandbox Optional sandbox name to use (defaults to configuration)
     */
    xLink<T>(data: T, options?: {
        sandbox?: string;
        attachTo?: string;
        ttl?: string;
    } | string): Promise<string>;
    xUnlink(options?: {
        sandbox?: string;
        attachTo?: string;
    } | string): Promise<void>;
    /**
     * Sends a successful JSON response with a message and optional data.
     * @param message - Success message.
     * @param data - Optional data payload.
     */
    success(message: string, data?: any): void;
}
/**
 * Middleware function type
 */
/**
 * Middleware function type
 */
type MiddlewareFunction = (...args: any[]) => void | Promise<void>;
/**
 * Next function type
 */
type NextFunction = (error?: any) => void;
/**
 * Route handler type
 */
type RouteHandler = (req: XyPrisRequest, res: XyPrisResponse, next?: NextFunction) => void | Promise<void>;

/**
 * XyPrissJS Types - Main Export File
 *
 * This file serves as the main entry point for all XyPriss integration types.
 * Types are now organized into MOD files for better maintainability.
 *
 * @fileoverview Main type export file for XyPriss integration
 * @version 4.5.11
 * @author XyPrissJS Team
 * @since 2025-01-06
 *
 * @example
 * ```typescript
 * import { ServerOptions, XyPrissApp } from './types';
 * // or import specific modules
 * import { CacheConfig } from './types/cache';
 * import { SecurityConfig } from './types/security';
 * ```
 */

type RequestHandler = (req: XyPrisRequest, res: XyPrisResponse, next?: NextFunction) => void | Promise<void>;

/**
 * Configuration for individual servers in multi-server mode
 *
 * @interface MultiServerConfig
 * @version 4.5.11
 * @author XyPrissJS Team
 * @since 2025-01-06
 */
interface MultiServerConfig extends Omit<Partial<ServerOptions$1>, "server"> {
    /** Unique identifier for this server instance */
    id: string;
    /** Port number for this server (replaces server.port) */
    port: number;
    /** Host for this server (replaces server.host) */
    host?: string;
    /** Server-specific configuration overrides (e.g. xems, etc.) */
    server?: Omit<NonNullable<ServerOptions$1["server"]>, "port" | "host">;
    /** Route prefix that this server should handle */
    routePrefix?: string;
    /**
     * Strategy for handling route prefixes:
     * - "auto-inject" (default): Automatically prepends the prefix to all routes if they don't have it.
     * - "strict-match": Legacy behavior. Only registers routes that explicitly start with the prefix.
     * - "both": Registers both the prefixed version and the original version of the route.
     */
    routePrefixStrategy?: "auto-inject" | "strict-match" | "both";
    /** Array of allowed route patterns for this server */
    allowedRoutes?: string[];
    /** Response control configuration for when routes don't match */
    responseControl?: {
        /** Enable custom response control (default: false) */
        enabled?: boolean;
        /** HTTP status code to send (default: 404) */
        statusCode?: number;
        /** Response content or message */
        content?: string | object;
        /** Content type header (default: "text/plain") */
        contentType?: string;
        /** Custom headers to set */
        headers?: Record<string, string>;
        /** Custom response handler function */
        handler?: (req: XyPrisRequest, res: XyPrisResponse) => void | Promise<void>;
    };
}
type ServerOptions$1 = XServerOptions;
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;
}
type XyPrissApp = XyApp;

/**
 * XyPriss Configuration Manager
 *
 * Provides a safe way to access and update XyPriss configurations
 * without encountering "cannot access before initialization" errors.
 *
 * This class acts as a singleton configuration store that can be used
 * in modular structures where accessing `app.configs` directly might
 * cause initialization timing issues.
 *
 * **IMPORTANT**: This is the SINGLE SOURCE OF TRUTH for all XyPriss configurations.
 * All components should use `Configs.get()` to access configuration values
 * instead of copying values during initialization.
 *
 * @example
 * ```typescript
 * import { Configs } from 'xypriss';
 *
 * // Set configuration
 * Configs.set({
 *   fileUpload: {
 *     enabled: true,
 *     maxFileSize: 5 * 1024 * 1024
 *   }
 * });
 *
 * // Get configuration
 * const fileUploadConfig = Configs.get('fileUpload');
 *
 * // Get entire config
 * const allConfigs = Configs.getAll();
 *
 * // Update specific config (updates the source of truth)
 * Configs.update('fileUpload', { maxFileSize: 10 * 1024 * 1024 });
 * ```
 */

/**
 * Configuration Manager Class
 * Singleton pattern for managing XyPriss configurations
 */
declare class ConfigurationManager {
    private static instance;
    private config;
    private initialized;
    /**
     * Private constructor to enforce singleton pattern
     * Initializes with default configuration
     */
    private constructor();
    /**
     * Get the singleton instance
     */
    private static getInstance;
    /**
     * Set the entire configuration
     * @param config - XP Server configuration options
     */
    static set(config: ServerOptions$1): void;
    /**
     * Get a specific configuration section
     * @param key - Configuration key (e.g., 'fileUpload', 'security', 'cache')
     * @returns The configuration value for the specified key
     */
    static get<K extends keyof ServerOptions$1>(key: K): ServerOptions$1[K];
    /**
     * Get the entire configuration object
     * @returns Complete XyPriss Server Configuration (XPSC)
     */
    static getAll(): ServerOptions$1;
    /**
     * Update a specific XyPriss configuration section (deep merge)
     * @param key - Configuration key to update
     * @param value - Partial value to merge with existing configuration
     */
    static update<K extends keyof ServerOptions$1>(key: K, value: Partial<ServerOptions$1[K]>): void;
    /**
     * Deep merge helper function
     * @param target - Target object
     * @param source - Source object to merge
     * @returns Merged object
     */
    /**
     * Deeply merge two configuration objects
     * @param target - Target object to merge into
     * @param source - Source object to merge from
     * @returns Merged object
     */
    private static deepMerge;
    /**
     * Merge configuration with existing config (deep merge)
     * @param config - Partial configuration to merge
     */
    static merge(config: Partial<ServerOptions$1>): void;
    /**
     * Check if configuration has been initialized
     * @returns true if configuration has been set, false otherwise
     */
    static isInitialized(): boolean;
    /**
     * Reset configuration to empty state
     * Useful for testing or reinitializing
     */
    static reset(): void;
    /**
     * Check if a specific configuration section exists
     * @param key - Configuration key to check
     * @returns true if the configuration section exists
     */
    static has<K extends keyof ServerOptions$1>(key: K): boolean;
    /**
     * Get configuration with a default value if not set
     * @param key - Configuration key
     * @param defaultValue - Default value to return if key doesn't exist
     * @returns Configuration value or default value
     */
    static getOrDefault<K extends keyof ServerOptions$1>(key: K, defaultValue: ServerOptions$1[K]): ServerOptions$1[K];
    /**
     * Delete a specific configuration section
     * @param key - Configuration key to delete
     */
    static delete<K extends keyof ServerOptions$1>(key: K): void;
    /**
     * Validates XEMS configuration strictly
     * @param config - Current server configuration
     * @throws Error if XEMS persistence is enabled but secret is invalid
     */
    /**
     * General configuration validation
     * @param config - Current server configuration
     */
    private static validateGeneralConfig;
    private static validateXemsConfig;
    /**
     * Calcule l'entropie de Shannon en bits par caractère
     * Une clé aléatoire de 32 chars ASCII aura ~4.5-5 bits/char
     * "a_very_secret_32_chars_key_12345" aura ~3.2 bits/char → rejeté
     */
    private static shannonEntropy;
    /**
     * Détecte si une string contient un pattern qui se répète
     * ex: "abcdabcdabcdabcdabcdabcdabcdabcd" → true
     */
    private static hasRepetitivePattern;
}

/**
 * Default instance for easy access
 */
declare const __cfg__: typeof ConfigurationManager;

/**
 * Initialize the global file upload manager (legacy)
 * This is called automatically when the server starts with file upload enabled
 *
 * @param configManager - The Configs class for accessing configuration
 * @param logger - Logger instance
 */
declare function initializeFileUpload(configManager: typeof ConfigurationManager, logger: Logger): void;
/**
 * Create a middleware for uploading a single file (legacy)
 */
declare function uploadSingle(fieldname: string): (req: any, res: any, next: any) => any;
/**
 * Create a middleware for uploading multiple files with the same field name (legacy)
 */
declare function uploadArray(fieldname: string, maxCount?: number): (req: any, res: any, next: any) => any;
/**
 * Create a middleware for uploading multiple files with different field names (legacy)
 */
declare function uploadFields(fields: Array<{
    name: string;
    maxCount?: number;
}>): (req: any, res: any, next: any) => any;
/**
 * Create a middleware for uploading any files (legacy)
 */
declare function uploadAny(): (req: any, res: any, next: any) => any;

/**
 * XyPriss File Upload API
 *
 * This module provides file upload middleware functions that can be used
 * independently of the app instance initialization timing.
 *
 * Usage:
 * ```typescript
 * import { FileUploadAPI } from 'xypriss';
 *
 * const fileUpload = new FileUploadAPI();
 * router.post('/upload', fileUpload.single('file'), (req, res) => {
 *   console.log(req.file);
 *   res.json({ success: true });
 * });
 * ```
 */

/**
 * File Upload API Class
 * Provides a clean, class-based interface for file upload middleware
 */
declare class FileUploadAPI {
    private manager;
    private logger;
    private initialized;
    constructor(config?: FileUploadConfig);
    /**
     * Internal auto-initialization method.
     * Called lazily by middleware methods if not already initialized.
     */
    private autoInitialize;
    /**
     * Manually initialize the file upload API (legacy support)
     */
    initialize(configManager?: any): Promise<void>;
    /**
     * Check if the file upload API is enabled
     */
    isEnabled(): boolean;
    /**
     * Handle upload errors and convert them to proper HTTP responses
     */
    private handleUploadError;
    /**
     * Create a middleware for uploading a single file
     *
     * @param fieldname - The name of the form field containing the file
     * @returns Middleware function
     */
    single(fieldname: string): (req: any, res: any, next: any) => Promise<any>;
    /**
     * Create a middleware for uploading multiple files with the same field name
     *
     * @param fieldname - The name of the form field containing the files
     * @param maxCount - Maximum number of files to accept (optional)
     * @returns Middleware function
     */
    array(fieldname: string, maxCount?: number): (req: any, res: any, next: any) => Promise<any>;
    /**
     * Create a middleware for uploading multiple files with different field names
     *
     * @param fields - Array of field configurations
     * @returns Middleware function
     */
    fields(fields: Array<{
        name: string;
        maxCount?: number;
    }>): (req: any, res: any, next: any) => Promise<any>;
    /**
     * Create a middleware for uploading any files (accepts all files)
     *
     * @returns Middleware function
     */
    any(): (req: any, res: any, next: any) => Promise<any>;
}

declare const Upload: FileUploadAPI;

/**
 * MultiServerApp provides an XyPrissApp compatible interface
 * that manages multiple underlying server instances.
 */
declare class MultiServerApp implements XyPrissApp {
    private manager;
    private serverConfigs;
    private logger;
    private globalRouter;
    private globalPlugins;
    settings: Record<string, any>;
    locals: Record<string, any>;
    mountpath: string;
    cache?: any;
    configs?: ServerOptions$1;
    private engineConfigs;
    private paramHandlers;
    constructor(manager: MultiServerManager, serverConfigs: MultiServerConfig[], logger: Logger);
    get(path: string, ...handlers: RequestHandler[]): void;
    post(path: string, ...handlers: RequestHandler[]): void;
    put(path: string, ...handlers: RequestHandler[]): void;
    delete(path: string, ...handlers: RequestHandler[]): void;
    patch(path: string, ...handlers: RequestHandler[]): void;
    options(path: string, ...handlers: RequestHandler[]): void;
    head(path: string, ...handlers: RequestHandler[]): void;
    connect(path: string, ...handlers: RequestHandler[]): void;
    trace(path: string, ...handlers: RequestHandler[]): void;
    all(path: string, ...handlers: RequestHandler[]): void;
    use(...args: any[]): void;
    start(callback?: () => void): Promise<void>;
    stop(): Promise<void>;
    waitForReady(): Promise<void>;
    private distributeConfigurations;
    private shouldRegisterRouteOnServer;
    getServers(): MultiServerInstance[];
    getServer(id: string): MultiServerInstance | undefined;
    getStats(): any;
    middleware(): any;
    set(setting: string, val: any): void;
    getSetting(setting: string): any;
    enabled(setting: string): boolean;
    disabled(setting: string): boolean;
    enable(setting: string): void;
    disable(setting: string): void;
    engine(ext: string, fn: any): any;
    param(name: string, handler: any): void;
    path(): string;
    render(view: string, options?: any, callback?: any): void;
    route(path: string): any;
    getPort(): number;
    forceClosePort(port: number): Promise<boolean>;
    invalidateCache(pattern: string): Promise<void>;
    getCacheStats(): Promise<any>;
    warmUpCache(data: Array<{
        key: string;
        value: any;
        ttl?: number;
    }>): Promise<void>;
    redirectFromPort(options: any): Promise<boolean>;
    getRedirectInstance(): any;
    getAllRedirectInstances(): any[];
    disconnectRedirect(): Promise<boolean>;
    disconnectAllRedirects(): Promise<boolean>;
    getRedirectStats(): any;
    redirect(from: string, to: string, statusCode?: 301 | 302 | 307 | 308): void;
    getRequestPreCompiler(): any;
    getConsoleInterceptor(): any;
    enableConsoleInterception(): Promise<void>;
    disableConsoleInterception(): Promise<void>;
    updateConsoleConfig(options: any): Promise<void>;
    getConsoleStats(): any;
    resetConsoleStats(): void;
    getFileWatcherStatus(): any;
    getFileWatcherStats(): any;
    stopFileWatcher(): Promise<void>;
    getFileWatcherManager(): any;
    checkTypeScript(): Promise<any[]>;
    getTypeScriptStatus(): any;
    enableTypeScriptChecking(): void;
    disableTypeScriptChecking(): void;
    enableConsoleEncryption(): void;
    disableConsoleEncryption(): void;
    encrypt(): void;
    setConsoleEncryptionKey(): void;
    setConsoleEncryptionDisplayMode(): void;
    getEncryptedLogs(): any[];
    restoreConsoleFromEncrypted(): Promise<any[]>;
    isConsoleEncryptionEnabled(): boolean;
    getConsoleEncryptionStatus(): any;
    getRouterStats(): any;
    getRouterInfo(): any;
    warmUpRoutes(): Promise<void>;
    resetRouterStats(): void;
    getHttpServer(): any;
    enableConsoleTracing(): void;
    disableConsoleTracing(): void;
    onConsoleTrace(): void;
    getConsoleTraceBuffer(): any[];
    resetConsoleTraceBuffer(): void;
    clearConsoleTraceBuffer(): void;
    getConsoleTracingStatus(): any;
    upload: any;
    uploadSingle(): any;
    uploadArray(): any;
    uploadFields(): any;
    uploadAny(): any;
    scaleUp(): Promise<void>;
    scaleDown(): Promise<void>;
    autoScale(): Promise<void>;
    getClusterMetrics(): Promise<any>;
    getClusterHealth(): Promise<any>;
    getAllWorkers(): any[];
    getOptimalWorkerCount(): Promise<number>;
    restartCluster(): Promise<void>;
    stopCluster(): Promise<void>;
    broadcastToWorkers(): Promise<void>;
    sendToRandomWorker(): Promise<void>;
    serverPluginManager: any;
    registerPlugin(plugin: any): Promise<void>;
    unregisterPlugin(pluginId: string): Promise<void>;
    getPlugin(id: string): any;
    getAllPlugins(): any[];
    getPluginsByType(type: any): any[];
    getPluginStats(): any;
    getPluginRegistryStats(): any;
    getPluginEngineStats(): any;
    initializeBuiltinPlugins(): Promise<void>;
    getServerPluginManager(): any;
    registerRouteTemplate(): void;
    unregisterRouteTemplate(): void;
    registerOptimizationPattern(): void;
    getOptimizerStats(): any;
}

/***************************************************************************
 * XyPrissJS - Fast And Secure
 *
 * @author Nehonix
 * @license Nehonix OSL (NOSL)
 *
 * Copyright (c) 2025 Nehonix. All rights reserved.
 *
 * This License governs the use, modification, and distribution of software
 * provided by NEHONIX under its open source projects.
 * NEHONIX is committed to fostering collaborative innovation while strictly
 * protecting its intellectual property rights.
 * Violation of any term of this License will result in immediate termination of all granted rights
 * and may subject the violator to legal action.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
 * AND NON-INFRINGEMENT.
 * IN NO EVENT SHALL NEHONIX BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * OR CONSEQUENTIAL DAMAGES ARISING FROM THE USE OR INABILITY TO USE THE SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 ***************************************************************************** */

/**
 * ## createServer — XyPriss Unified Server Factory
 *
 * Creates and returns a fully configured XyPriss HighPerformance (UF) server instance.
 * The factory handles all internal bootstrapping synchronously — the returned `app`
 * is ready for route registration and `.start()` immediately.
 *
 * **Capabilities:**
 * - Zero-async initialization: routes can be registered right after creation.
 * - Automatic configuration loading from `xypriss.config.jsonc` (if present).
 * - Built-in support for **single-server** and **multi-server (XMS)** modes.
 * - Optional security middleware, XEMS session management, XHSC engine bridging,
 *   file upload handling, caching, worker pools, and more — all driven by `options`.
 *
 * @param {ServerOptions} [options={}] - Server configuration object. All fields are optional;
 *   sensible defaults are applied automatically. Key sections include:
 *   - `server` — Port, host, trust-proxy, XEMS, XHSC settings.
 *   - `security` — Enable/configure CSRF, Helmet, XSS, rate-limiting, etc.
 *   - `logging` — Logger level, console interception, and formatting.
 *   - `cache` — In-memory caching configuration.
 *   - `performance` — Request pre-compilation, compression, and profiling.
 *   - `multiServer` — XMS (XyPriss Multi-Server) configuration for running
 *     multiple isolated server instances within a single process.
 *
 * @returns {XyApp} A fully-initialized HighPerformance application instance with methods:
 *   `get`, `post`, `put`, `delete`, `patch`, `use`, `start`, `middleware`, and more.
 *
 * @throws {Error} If `multiServer.enabled` is `true` but `multiServer.servers` is
 *   missing or empty.
 *
 * @example
 * ```typescript
 * // Basic server
 * import { createServer } from "xypriss";
 *
 * const app = createServer({ server: { port: 3000 } });
 *
 * app.get("/", (req, res) => res.json({ status: "ok" }));
 * app.start();
 * ```
 *
 * @example
 * ```typescript
 * // Server with security and XEMS sessions
 * const app = createServer({
 *     server: {
 *         port: 8080,
 *         xems: {
 *             enable: true,
 *             persistence: { enabled: true, path: "./store/app.xems", secret: "..." },
 *         },
 *     },
 *     security: {
 *         enabled: true,
 *         level: "enhanced",
 *         csrf: true,
 *         helmet: true,
 *     },
 * });
 * ```
 *
 * @see {@link https://xypriss.nehonix.com/docs/getting-started} Getting Started Guide
 * @see {@link https://xypriss.nehonix.com/docs/configuration} Configuration Reference
 */
declare function createServer(options?: ServerOptions$1): XyApp;

/**
 * XyPrissJS Cache Factory
 *@version 4.1.8
 * Factory for creating optimized cache instances based on configuration.
 * Automatically selects the best strategy for high-performance performance.
 */

/**
 * Auto-detect best cache strategy based on environment
 */
declare function createOptimalCache(config?: CacheConfig): SecureCacheAdapter;

/**
 * XyPriss Security Middleware
 * Comprehensive security middleware using BuiltInMiddleware as single source of truth
 */

/**
 * Security middleware class implementing comprehensive protection
 * Implements SecurityConfig interface to ensure type safety
 */
declare class SecurityMiddleware {
    level: SecurityLevel;
    csrf: boolean | CSRFConfig;
    helmet: boolean | HelmetConfig;
    xss: boolean | XSSConfig;
    sqlInjection: boolean | SQLInjectionConfig;
    pathTraversal: boolean | PathTraversalConfig;
    commandInjection: boolean | CommandInjectionConfig;
    xxe: boolean | XXEConfig;
    ldapInjection: boolean | LDAPInjectionConfig;
    rateLimit: boolean | RateLimitConfig;
    cors: boolean | CORSConfig;
    compression: boolean | CompressionConfig;
    hpp: boolean | HPPConfig;
    slowDown: boolean | SlowDownConfig;
    browserOnly: boolean | BrowserOnlyConfig;
    terminalOnly: boolean | TerminalOnlyConfig;
    requestSignature: boolean | RequestSignatureConfig;
    routeConfig?: SecurityConfig["routeConfig"];
    maliciousUrlScanner: SecurityConfig["maliciousUrlScanner"];
    private _ignore;
    private _ignoreAll;
    private helmetMiddleware;
    private corsMiddleware;
    private rateLimitMiddleware;
    private csrfMiddleware;
    private browserOnlyMiddleware;
    private terminalOnlyMiddleware;
    private requestSignatureMiddleware;
    private hppMiddleware;
    private compressionMiddleware;
    private maliciousUrlScannerMiddleware;
    private logger;
    constructor(config?: SecurityConfig, logger?: Logger);
    /**
     * Initialize all security middleware instances using BuiltInMiddleware
     * BuiltInMiddleware is the single source of truth for all middleware wrappers
     */
    private initializeMiddleware;
    /**
     * Get the main security middleware stack
     * Returns a single middleware function that applies all security measures
     */
    getMiddleware(): (req: XyPrisRequest, res: XyPrisResponse, next: NextFunction) => void;
    /**
     * Apply all security middleware in the correct order
     */
    private applySecurityStack;
    /**
     * Execute middleware stack sequentially with proper async handling
     */
    private executeMiddlewareStack;
    /**
     * Get CSRF token for client-side usage
     */
    generateCsrfToken(req: XyPrisRequest): string | null;
    /**
     * Check if browser-only protection is enabled
     */
    private isBrowserOnlyEnabled;
    /**
     * Check if terminal-only protection is enabled
     */
    private isTerminalOnlyEnabled;
    /**
     * Check if a route matches a pattern
     */
    private matchesRoute;
    /**
     * Evaluates if a security module should be applied to the current request.
     *
     * @param req The incoming request
     * @param moduleConfig Optional route-specific configuration for the module
     * @param absoluteBypassOnly If true, only checks against _ignoreAll (used for access control/signatures)
     * @returns boolean True if the security module should be applied
     */
    private shouldApplySecurityModule;
}

/**
 * XJsonResponseHandler - Advanced JSON Response Handler
 * Handles large data serialization without limits
 */

interface XJsonOptions {
    /**
     * Maximum depth for object serialization
     * @default 20
     */
    maxDepth?: number;
    /**
     * Maximum string length before truncation
     * @default 10000
     */
    truncateStrings?: number;
    /**
     * Include non-enumerable properties
     * @default false
     */
    includeNonEnumerable?: boolean;
    /**
     * Enable streaming for very large responses
     * @default true
     */
    enableStreaming?: boolean;
    /**
     * Chunk size for streaming responses (in bytes)
     * @default 1024 * 64 (64KB)
     */
    chunkSize?: number;
}
declare class XJsonResponseHandler {
    private options;
    constructor(options?: XJsonOptions);
    /**
     * Main method to handle XJson responses
     */
    xJson(res: XyPrisResponse, data: any): void;
    /**
     * Serialize data using safe serialization
     */
    private serializeData;
    /**
     * Handle BigInt serialization by converting BigInt to string
     */
    private handleBigIntSerialization;
    /**
     * Stream large responses in chunks
     */
    private streamResponse;
    /**
     * Handle serialization errors
     */
    private handleSerializationError;
    /**
     * Create middleware to override res.xJson
     */
    static createMiddleware(options?: XJsonOptions): (req: any, res: XyPrisResponse, next: () => void) => void;
    /**
     * Utility method for direct XJson serialization
     */
    static stringify(data: any, options?: XJsonOptions): string;
    /**
     * Ultra-powerful and robust JSON parser with automatic error recovery
     */
    static parse(data: string): any;
}

/**
 * Plugin API
 * Public API for plugin management as documented in PLUGIN_SYSTEM_GUIDE.md
 */

declare class PluginAPI {
    /**
     * Reads and returns the project manifest (`package.json`) associated with the provided system core.
     *
     * This method is cryptographically and logically bound to the system instance to ensure
     * that plugins only access the metadata of their authorized environment.
     *
     * @template T - The expected structure of the manifest file.
     * @param sys - The XyPriss Hyper-System Core (`__sys__`) instance.
     * @returns The parsed JSON content of the `package.json` file.
     * @throws {Error} If the system instance is invalid, lacks a root path, or the manifest cannot be read.
     *
     * @example
     * ```typescript
     * const pkg = Plugin.manifest<MyPackageJson>(__sys__);
     * console.log(`Running in ${pkg.name}@${pkg.version}`);
     * ```
     */
    manifest<T>(sys: XyPrissXHSC): T;
    /**
     * @private — Internal registration. Never call this directly.
     * Use `exec()` instead.
     */
    private register;
    /**
     * Register a plugin — the sole public entry point for plugin registration.
     *
     * @example
     * ```typescript
     * Plugin.exec(Plugin.create({
     *   name: "test",
     *   version: "1.0.0",
     *   onServerStart(server) {
     *     console.log("Server started");
     *   },
     * }, __sys__.__root__));
     * ```
     */
    exec(plugin: XyPrissPlugin | PluginCreator, config?: any): void;
    /**
     * Get a registered plugin by name.
     *
     * @example
     * ```typescript
     * const plugin = Plugin.get("my-plugin");
     * if (plugin) {
     *   console.log(`Found plugin: ${plugin.name}@${plugin.version}`);
     * }
     * ```
     */
    get(name: string): {
        name: string;
        version: string;
        __root__: string;
    } | undefined;
    /**
     * Create a type-safe plugin instance with a validated root.
     *
     * @example
     * ```typescript
     * const myPlugin = Plugin.create({
     *   name: "my-plugin",
     *   version: "1.0.0",
     *   onServerStart: (server) => console.log("Plugin started!"),
     * }, __sys__.__root__);
     * ```
     */
    create(plugin: XyPrissPlugin, Sys: string): XyPrissPlugin;
    /**
     * Create a typed plugin factory with a pre-assigned root.
     *
     * @example
     * ```typescript
     * const myFactory = Plugin.factory(
     *   (config: MyConfig) => ({ name: "my-plugin", version: "1.0.0" }),
     *   __sys__.__root__
     * );
     * ```
     */
    factory<TConfig = any>(creator: (config: TConfig) => XyPrissPlugin, rootOrSys: string | {
        __root__: string;
    }): PluginCreator;
    /**
     * Create a no-op placeholder plugin.
     * Useful for testing or conditional plugin slots.
     */
    void(): XyPrissPlugin;
    /**
     * Performs a deep inspection of a plugin instance to identify and list all required
     * cryptographic permissions based on implemented hooks.
     *
     * This utility is designed for developers to use during the preparation of their
     * `package.json` manifest (`xfpm.permissions` field).
     *
     * @param plugin - The XyPriss plugin instance to inspect.
     *
     * @example
     * ```typescript
     * const myPlugin = Plugin.create({ ... }, __sys__.__root__);
     * Plugin.inspect(myPlugin);
     * ```
     */
    inspect(plugin: XyPrissPlugin): void;
}
declare const Plugin: Readonly<Omit<PluginAPI, "register">>;

/**
 * XyPrissJS Quick Start
 * Pre-configured server instances for rapid development (tests with limited configs)
 */
/**
 * Quick development server with sensible defaults
 */
declare function quickServer(port?: number): XyApp;

type GuardResolver = (req: XyPrisRequest$1, options?: any) => boolean | string | Promise<boolean | string>;
/**
 * XyGuard - Global registry for built-in guard resolvers.
 * This allows XyPriss to handle declarative guards like 'authenticated' or 'roles'
 * without being opinionated about the underlying implementation (session, JWT, etc.).
 *
 * @example
 * ```typescript
 * import { XyGuard } from "xypriss";
 *
 * XyGuard.define('authenticated', (req) => !!req.user);
 * XyGuard.define('roles', (req, required) => required.includes(req.user?.role));
 * ```
 */
declare class XyGuard {
    private static resolvers;
    /**
     * Define a resolver for the 'authenticated' guard.
     */
    static define(name: "authenticated", resolver: (req: XyPrisRequest$1) => boolean | string | Promise<boolean | string>): void;
    /**
     * Define a resolver for 'roles' or 'permissions' guards.
     */
    static define(name: "roles" | "permissions", resolver: (req: XyPrisRequest$1, required: string[]) => boolean | string | Promise<boolean | string>): void;
    /**
     * Define a resolver for any custom guard.
     */
    static define(name: string & {}, resolver: GuardResolver): void;
    /**
     * Get an existing resolver by name.
     * @internal
     */
    static get(name: string): GuardResolver | undefined;
}

/**
 * Plugin Hook Identifiers
 *
 * Defines the unique identifiers for all plugin hooks used in the permission system.
 * These IDs are used in the server configuration to allow/deny specific hooks.
 */
declare const PluginHookIds: {
    readonly ON_REGISTER: "XHS.HOOK.LIFECYCLE.REGISTER";
    readonly ON_SERVER_START: "XHS.HOOK.LIFECYCLE.SERVER_START";
    readonly ON_SERVER_READY: "XHS.HOOK.LIFECYCLE.SERVER_READY";
    readonly ON_SERVER_STOP: "XHS.HOOK.LIFECYCLE.SERVER_STOP";
    readonly ON_REQUEST: "XHS.HOOK.HTTP.REQUEST";
    readonly ON_RESPONSE: "XHS.HOOK.HTTP.RESPONSE";
    readonly ON_ERROR: "XHS.HOOK.HTTP.ERROR";
    readonly ON_SECURITY_ATTACK: "XHS.HOOK.SECURITY.ATTACK";
    readonly ON_RATE_LIMIT: "XHS.HOOK.SECURITY.RATE_LIMIT";
    readonly ACCESS_CONFIGS: "XHS.PERM.SECURITY.CONFIGS";
    readonly ACCESS_SENSITIVE_DATA: "XHS.PERM.SECURITY.SENSITIVE_DATA";
    readonly ON_RESPONSE_TIME: "XHS.HOOK.METRICS.RESPONSE_TIME";
    readonly ON_ROUTE_ERROR: "XHS.HOOK.METRICS.ROUTE_ERROR";
    readonly REGISTER_ROUTES: "XHS.PERM.ROUTING.REGISTER_ROUTES";
    readonly MIDDLEWARE: "XHS.PERM.HTTP.MIDDLEWARE";
    readonly BYPASS_NAMESPACE: "XHS.PERM.ROUTING.BYPASS_NAMESPACE";
    readonly OVERWRITE_PROTECTED: "XHS.PERM.ROUTING.OVERWRITE_PROTECTED";
    readonly GLOBAL_MIDDLEWARE: "XHS.PERM.HTTP.GLOBAL_MIDDLEWARE";
    readonly MANAGE_PLUGINS: "PLG.MANAGEMENT.MANAGE_PLUGINS";
    readonly ON_AUXILIARY_SERVER_DEPLOY: "XHS.PERM.OPS.AUXILIARY_SERVER";
    readonly ON_CONSOLE_INTERCEPT: "XHS.PERM.LOGGING.CONSOLE_INTERCEPT";
};

/***************************************************************************
 * XyPrissJS - Fast And Secure
 *
 * @author Nehonix
 * @license Nehonix OSL (NOSL)
 *
 * Copyright (c) 2025 Nehonix. All rights reserved.
 *
 * This License governs the use, modification, and distribution of software
 * provided by NEHONIX under its open source projects.
 * NEHONIX is committed to fostering collaborative innovation while strictly
 * protecting its intellectual property rights.
 * Violation of any term of this License will result in immediate termination of all granted rights
 * and may subject the violator to legal action.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
 * AND NON-INFRINGEMENT.
 * IN NO EVENT SHALL NEHONIX BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * OR CONSEQUENTIAL DAMAGES ARISING FROM THE USE OR INABILITY TO USE THE SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 ***************************************************************************** */
type ArrayStrategy = "replace" | "concat" | "merge";
interface MergeOptions {
    /**
     * How to handle arrays when both `defaults` and `userOptions` have an
     * array at tme key.
     * - `"replace"` (default) — user array wins entirely.
     * - `"concat"`            — `[...defaultArray, ...userArray]`.
     * - `"merge"`             — element-wise: recurse for plain-object items,
     *                           otherwise use the user element (or the default
     *                           element when the user array is shorter).
     */
    arrayStrategy?: ArrayStrategy;
}
/**
 * mergeWithDefaults — Smart config merge utility
 *
 * Unlike `{ ...defaults, ...userOptions }` (shallow spread), this utility:
 *
 * 1. **User-provided keys always win** — a key present in `userOptions` (even
 *    if its value is `false`, `null`, `0`, or `""`) is NEVER overridden by a
 *    default. Only truly absent keys fall back to the default.
 *
 * 2. **Deep merge for plain objects** — nested objects are merged recursively
 *    at any depth, so that `userOptions.rateLimit.max` doesn't wipe out
 *    `defaults.rateLimit.windowMs`.
 *
 * 3. **No mutation** — returns a new object; inputs are untouched.
 *
 * 4. **Circular reference protection** — cycles are detected and broken
 *    (the circular reference is replaced by `undefined`).
 *
 * 5. **Prototype pollution protection** — dangerous keys (`__proto__`,
 *    `constructor`, `prototype`) are silently ignored.
 *
 * 6. **Array strategy** — configurable via `options.arrayStrategy`:
 *    - `"replace"` (default) — user array fully replaces the default array.
 *    - `"concat"`            — arrays are concatenated (defaults first).
 *    - `"merge"`             — elements are merged index-by-index (plain
 *                              objects recurse, primitives use user value).
 *
 * 7. **Symbol keys** — included in the merge alongside string keys.
 *
 * ### Example
 * ```ts
 * const defaults = {
 *   origin: true,
 *   credentials: false,
 *   maxAge: 86400,
 *   rateLimit: { max: 100, windowMs: 60_000 },
 * };
 * const user = {
 *   credentials: true,
 *   origin: ["http://localhost:5173"],
 *   rateLimit: { max: 50 },          // windowMs falls back to default
 * };
 *
 * mergeWithDefaults(defaults, user);
 * // → {
 * //     origin: ["http://localhost:5173"],
 * //     credentials: true,
 * //     maxAge: 86400,
 * //     rateLimit: { max: 50, windowMs: 60_000 },
 * //   }
 * ```
 */
declare function mergeWithDefaults<T extends Record<string | symbol, any>>(defaults: T, userOptions: Partial<T> | undefined | null, options?: MergeOptions, 
/** @internal — tracks visited objects to break circular refs */
_seen?: WeakSet<object>): T;

/***************************************************************************
 * XyPrissJS - Fast And Secure
 *
 * @author Nehonix
 * @license Nehonix OSL (NOSL)
 *
 * Copyright (c) 2025 Nehonix. All rights reserved.
 *
 * This License governs the use, modification, and distribution of software
 * provided by NEHONIX under its open source projects.
 * NEHONIX is committed to fostering collaborative innovation while strictly
 * protecting its intellectual property rights.
 * Violation of any term of this License will result in immediate termination of all granted rights
 * and may subject the violator to legal action.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
 * AND NON-INFRINGEMENT.
 * IN NO EVENT SHALL NEHONIX BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * OR CONSEQUENTIAL DAMAGES ARISING FROM THE USE OR INABILITY TO USE THE SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 ***************************************************************************** */

/** Result enriched with metadata for observability / debugging. */
interface GetIpResult {
    /** Resolved IP address (IPv4 or IPv6, normalised). */
    ip: string;
    /** Header / source that provided the IP. */
    source: IpSource;
}
type IpSource = "cf-connecting-ip" | "true-client-ip" | "x-real-ip" | "x-forwarded-for" | "forwarded" | "x-client-ip" | "x-cluster-client-ip" | "req.ip" | "socket" | "fallback";
/**
 * Robustly extracts the **real** client IP from a request.
 *
 * Resolution order (most-specific / trustworthy first):
 *  1. `CF-Connecting-IP`     – Cloudflare; single, authoritative value
 *  2. `True-Client-IP`       – Akamai / Cloudflare enterprise
 *  3. `X-Real-IP`            – Nginx single-proxy setups
 *  4. `X-Client-IP`          – Some load balancers / Apache mod_remoteip
 *  5. `X-Cluster-Client-IP`  – Rackspace, some Nginx configs
 *  6. `Forwarded`            – RFC 7239 standard header
 *  7. `X-Forwarded-For`      – De-facto standard (picks first public IP)
 *  8. `req.ip`               – XyPrisRequest parsed value
 *  9. `socket.remoteAddress` – Raw TCP socket
 * 10. `"127.0.0.1"`          – Ultimate fallback (never throws)
 *
 * @param req       - The request object (XyPrisRequest-compatible).
 * @param enriched  - When `true`, returns `{ ip, source }` for observability.
 */
declare function getIp(req: XyPrisRequest): string;
declare function getIp(req: XyPrisRequest, enriched: true): GetIpResult;

/**
 * All HTTP status keys supported by the `Send` helper.
 * Each key maps to a standard HTTP status code.
 *
 * — 2xx  Success
 * — 3xx  Redirection
 * — 4xx  Client errors
 * — 5xx  Server errors
 */
type SupportedStatus = "OK" | "CREATED" | "ACCEPTED" | "NO_CONTENT" | "MOVED_PERMANENTLY" | "FOUND" | "NOT_MODIFIED" | "BAD_REQUEST" | "UNAUTHORIZED" | "FORBIDDEN" | "NOT_FOUND" | "METHOD_NOT_ALLOWED" | "NOT_ACCEPTABLE" | "CONFLICT" | "GONE" | "UNPROCESSABLE_ENTITY" | "LOCKED" | "TOO_MANY_REQUEST" | "PAYLOAD_TOO_LARGE" | "UNSUPPORTED_MEDIA_TYPE" | "REQUEST_TIMEOUT" | "PRECONDITION_FAILED" | "EXPECTATION_FAILED" | "IM_A_TEAPOT" | "INTERNAL_SERVER_ERR" | "NOT_IMPLEMENTED" | "BAD_GATEWAY" | "SERVICE_UNAVAILABLE" | "GATEWAY_TIMEOUT";
/**
 * Maps every {@link SupportedStatus} key to its corresponding HTTP status code.
 */
type ISeConfigs = Record<SupportedStatus, number>;
/**
 * Signature shared by all public dispatch methods.
 *
 * @param message - Human-readable description shown to the API consumer.
 * @param data    - Optional payload to attach to the response body.
 */
type TSendPropsFn = (message?: string, data?: unknown) => void;
/**
 * Contract that the {@link Send} class must satisfy.
 */
interface ISeResponder {
    ok: TSendPropsFn;
    created: TSendPropsFn;
    accepted: TSendPropsFn;
    noContent: () => void;
    movedPermanently: TSendPropsFn;
    found: TSendPropsFn;
    notModified: () => void;
    badRequest: TSendPropsFn;
    unauthorized: TSendPropsFn;
    forbidden: TSendPropsFn;
    notFound: TSendPropsFn;
    methodNotAllowed: TSendPropsFn;
    notAcceptable: TSendPropsFn;
    conflict: TSendPropsFn;
    gone: TSendPropsFn;
    unprocessableEntity: TSendPropsFn;
    locked: TSendPropsFn;
    tooManyRequest: TSendPropsFn;
    payloadTooLarge: TSendPropsFn;
    unsupportedMediaType: TSendPropsFn;
    requestTimeout: TSendPropsFn;
    preconditionFailed: TSendPropsFn;
    expectationFailed: TSendPropsFn;
    imATeapot: TSendPropsFn;
    internalError: TSendPropsFn;
    notImplemented: TSendPropsFn;
    badGateway: TSendPropsFn;
    serviceUnavailable: TSendPropsFn;
    gatewayTimeout: TSendPropsFn;
}

/**
 * @file Send.ts
 * @description Structured HTTP error & success response helper for the XyPriss framework.
 *
 * @copyright Copyright © 2025–2026 NEHONIX. All Rights Reserved.
 * @license NEHONIX Open Source License v2.0 (NOSL v2)
 *          https://dll.nehonix.com/licenses/NOSL/v2
 *
 * This file is part of a NEHONIX open source project.
 * You may use, modify, and redistribute it freely — including for commercial
 * purposes — provided that NEHONIX is always credited as the original author.
 *
 * @author NEHONIX
 */

/**
 * A structured HTTP response helper that standardises all responses across
 * the application — both success and error paths.
 *
 * Every method sends a JSON body conforming to {@link IResTemplate}, ensuring
 * consistent shapes for API consumers regardless of where the response
 * originates.
 *
 * @example
 * ```ts
 * const send = new Send(res);
 *
 * // ── 2xx ──────────────────────────────────────────────────────────────────
 * send.ok("User fetched.", { id: 1, name: "Alice" });
 * send.created("User created.", { id: 42 });
 * send.accepted("Your export is being processed.");
 * send.noContent();
 *
 * // ── 4xx ──────────────────────────────────────────────────────────────────
 * send.badRequest("The 'email' field is required.");
 * send.unauthorized("Please log in to continue.");
 * send.forbidden("You do not have permission to access this resource.");
 * send.notFound("User not found.", { userId: 42 });
 * send.methodNotAllowed("POST is not allowed on this endpoint.");
 * send.conflict("A user with this email already exists.");
 * send.gone("This resource has been permanently deleted.");
 * send.unprocessableEntity("Validation failed.", { fields: { email: "Invalid format" } });
 * send.tooManyRequest("Rate limit reached. Try again in 60 seconds.");
 * send.payloadTooLarge("File exceeds the 10 MB limit.");
 * send.unsupportedMediaType("Only application/json is accepted.");
 *
 * // ── 5xx ──────────────────────────────────────────────────────────────────
 * send.internalError("An unexpected error occurred.");
 * send.notImplemented("This feature is not yet available.");
 * send.serviceUnavailable("The server is temporarily down for maintenance.");
 * send.gatewayTimeout("The upstream service did not respond in time.");
 * ```
 */
declare class Send implements ISeResponder {
    private readonly res;
    private readonly configs;
    private readonly serverName;
    private readonly includeServerName;
    /**
     * Creates a new `Send` instance bound to the given response object.
     *
     * @param res     - The active `XyPrisResponse` to write into.
     * @param configs - Optional overrides for the default status-code registry
     *                  and display options.
     */
    constructor(res: XyPrisResponse$1, configs?: Partial<{
        statusCode: Partial<ISeConfigs>;
        includeServerName: boolean;
    }>);
    /**
     * Resolves the status code, builds the full response body, and flushes it.
     *
     * @param statusKey  - One of the {@link SupportedStatus} keys.
     * @param label      - Human-readable short label for the status type.
     * @param success    - Whether this is a success response.
     * @param message    - Optional caller-supplied message; falls back to `label`.
     * @param data       - Optional payload to attach to the response body.
     */
    private dispatch;
    /**
     * Sends a **200 OK** response.
     *
     * The standard success response for GET, PUT, PATCH, or DELETE requests
     * that return a body.
     *
     * @param message - Human-readable confirmation.
     * @param data    - Payload to return to the client.
     *
     * @example
     * send.ok("User fetched successfully.", { id: 1, name: "Alice" });
     */
    ok: TSendPropsFn;
    /**
     * Sends a **201 Created** response.
     *
     * Use after successfully creating a new resource.
     * Consider also setting a `Location` header pointing to the new resource.
     *
     * @param message - Human-readable confirmation.
     * @param data    - The newly created resource or its identifier.
     *
     * @example
     * send.created("User created.", { id: 42 });
     */
    created: TSendPropsFn;
    /**
     * Sends a **202 Accepted** response.
     *
     * Use when the request has been accepted but processing will happen
     * asynchronously (e.g. background jobs, email dispatch, report generation).
     *
     * @param message - Human-readable explanation of what will happen.
     * @param data    - Optional tracking info (e.g. job ID).
     *
     * @example
     * send.accepted("Your export is being processed.", { jobId: "abc-123" });
     */
    accepted: TSendPropsFn;
    /**
     * Sends a **204 No Content** response.
     *
     * Use after a successful DELETE or an action that produces no body.
     * RFC 7231 forbids a body for 204 — this method sends status only.
     *
     * @example
     * send.noContent();
     */
    noContent: () => void;
    /**
     * Sends a **301 Moved Permanently** response.
     *
     * Use when a resource has been permanently relocated. Clients and search
     * engines should update their references.
     *
     * @param message - Optional explanation or the new URL.
     * @param data    - Optional payload (e.g. `{ location: "https://…" }`).
     *
     * @example
     * send.movedPermanently("This endpoint has moved.", { location: "/v2/users" });
     */
    movedPermanently: TSendPropsFn;
    /**
     * Sends a **302 Found** response.
     *
     * Use for temporary redirects. The client should continue using the
     * original URL for future requests.
     *
     * @param message - Optional explanation or the temporary URL.
     * @param data    - Optional payload (e.g. `{ location: "https://…" }`).
     *
     * @example
     * send.found("Redirecting to login.", { location: "/auth/login" });
     */
    found: TSendPropsFn;
    /**
     * Sends a **304 Not Modified** response.
     *
     * Use with conditional requests (`If-None-Match`, `If-Modified-Since`).
     * Tells the client its cached version is still valid.
     *
     * @example
     * send.notModified();
     */
    notModified: () => void;
    /**
     * Sends a **400 Bad Request** response.
     *
     * Use when the client submits a malformed or invalid request
     * (e.g. missing required fields, invalid format, constraint violation).
     *
     * @param message - Human-readable explanation of why the request was rejected.
     * @param data    - Optional payload (e.g. a list of validation errors per field).
     *
     * @example
     * send.badRequest("The 'username' field must be at least 3 characters.");
     * send.badRequest("Validation failed.", { fields: { email: "Invalid format" } });
     */
    badRequest: TSendPropsFn;
    /**
     * Sends a **401 Unauthorized** response.
     *
     * Use when the request lacks valid authentication credentials.
     * Despite the name, this is an *authentication* failure — not authorisation.
     *
     * @param message - Human-readable explanation (avoid leaking token details).
     * @param data    - Optional payload (e.g. `{ authScheme: "Bearer" }`).
     *
     * @example
     * send.unauthorized("Authentication token is missing or expired.");
     */
    unauthorized: TSendPropsFn;
    /**
     * Sends a **403 Forbidden** response.
     *
     * Use when the client is authenticated but lacks permission to access
     * the resource. Unlike 401, re-authenticating will not help.
     *
     * @param message - Human-readable explanation of the permission boundary.
     * @param data    - Optional payload (e.g. required role/scope info).
     *
     * @example
     * send.forbidden("You do not have permission to delete this resource.");
     * send.forbidden("Admin role required.", { requiredRole: "admin" });
     */
    forbidden: TSendPropsFn;
    /**
     * Sends a **404 Not Found** response.
     *
     * Use when the requested resource does not exist or has been permanently removed.
     *
     * @param message - Human-readable explanation of what could not be found.
     * @param data    - Optional payload (e.g. the identifier that was looked up).
     *
     * @example
     * send.notFound("No user found with id '42'.");
     * send.notFound("Resource not found.", { id: "42" });
     */
    notFound: TSendPropsFn;
    /**
     * Sends a **405 Method Not Allowed** response.
     *
     * Use when the HTTP method used is not supported on the target endpoint.
     * Always pair this with an `Allow` header listing permitted methods.
     *
     * @param message - Human-readable explanation of the allowed methods.
     * @param data    - Optional payload (e.g. `{ allowedMethods: ["GET", "POST"] }`).
     *
     * @example
     * send.methodNotAllowed("Only GET and POST are allowed on this route.");
     * send.methodNotAllowed("Method not allowed.", { allowedMethods: ["GET", "POST"] });
     */
    methodNotAllowed: TSendPropsFn;
    /**
     * Sends a **406 Not Acceptable** response.
     *
     * Use when the server cannot produce a response matching the client's
     * `Accept` header (content-type negotiation failure).
     *
     * @param message - Human-readable explanation of supported content types.
     * @param data    - Optional payload (e.g. `{ supportedTypes: ["application/json"] }`).
     *
     * @example
     * send.notAcceptable("This API only serves application/json.");
     */
    notAcceptable: TSendPropsFn;
    /**
     * Sends a **408 Request Timeout** response.
     *
     * Use when the server times out waiting for the client to complete its
     * request within the allowed time window.
     *
     * @param message - Human-readable explanation of the timeout.
     * @param data    - Optional payload (e.g. `{ timeoutMs: 5000 }`).
     *
     * @example
     * send.requestTimeout("The request took too long. Please try again.");
     */
    requestTimeout: TSendPropsFn;
    /**
     * Sends a **409 Conflict** response.
     *
     * Use when the request conflicts with the current state of the resource
     * (e.g. duplicate entry, optimistic-lock violation, concurrent edit clash).
     *
     * @param message - Human-readable explanation of the conflict.
     * @param data    - Optional payload (e.g. the conflicting resource).
     *
     * @example
     * send.conflict("A user with this email already exists.");
     * send.conflict("Edit conflict detected.", { existingVersion: 3, yourVersion: 2 });
     */
    conflict: TSendPropsFn;
    /**
     * Sends a **410 Gone** response.
     *
     * Use when a resource has been *permanently* deleted and will not return.
     * Prefer 404 when you don't want to reveal whether the resource ever existed.
     *
     * @param message - Human-readable explanation of the permanent removal.
     * @param data    - Optional payload (e.g. deletion date).
     *
     * @example
     * send.gone("This account has been permanently deleted.");
     */
    gone: TSendPropsFn;
    /**
     * Sends a **412 Precondition Failed** response.
     *
     * Use when a conditional request (`If-Match`, `If-Unmodified-Since`) fails
     * because the precondition evaluated to false on the server.
     *
     * @param message - Human-readable explanation of the failed precondition.
     * @param data    - Optional payload (e.g. current ETag or last-modified date).
     *
     * @example
     * send.preconditionFailed("ETag mismatch — resource was modified since your last fetch.");
     */
    preconditionFailed: TSendPropsFn;
    /**
     * Sends a **413 Payload Too Large** response.
     *
     * Use when the request body exceeds the server's or route's size limit.
     *
     * @param message - Human-readable explanation including the size limit when safe.
     * @param data    - Optional payload (e.g. `{ maxBytes: 10_485_760 }`).
     *
     * @example
     * send.payloadTooLarge("File exceeds the 10 MB limit.");
     * send.payloadTooLarge("Request body too large.", { maxBytes: 10_485_760 });
     */
    payloadTooLarge: TSendPropsFn;
    /**
     * Sends a **415 Unsupported Media Type** response.
     *
     * Use when the `Content-Type` or encoding sent by the client is not
     * supported by the endpoint.
     *
     * @param message - Human-readable explanation of accepted media types.
     * @param data    - Optional payload (e.g. `{ acceptedTypes: ["application/json"] }`).
     *
     * @example
     * send.unsupportedMediaType("Only application/json payloads are accepted.");
     */
    unsupportedMediaType: TSendPropsFn;
    /**
     * Sends a **417 Expectation Failed** response.
     *
     * Use when the `Expect` request-header field could not be satisfied by
     * the server.
     *
     * @param message - Human-readable explanation of the unmet expectation.
     * @param data    - Optional payload.
     *
     * @example
     * send.expectationFailed("The 'Expect: 100-continue' header could not be satisfied.");
     */
    expectationFailed: TSendPropsFn;
    /**
     * Sends a **418 I'm a Teapot** response.
     *
     * An April Fools' joke defined in RFC 2324. Occasionally used as a
     * catch-all for intentionally refused requests (e.g. blocking bots).
     *
     * @param message - Whatever you want. The world is your teapot.
     * @param data    - Optional payload.
     *
     * @example
     * send.imATeapot("I refuse to brew coffee because I am, permanently, a teapot.");
     */
    imATeapot: TSendPropsFn;
    /**
     * Sends a **422 Unprocessable Entity** response.
     *
     * Use when the request is well-formed but contains semantic errors that
     * prevent it from being processed (e.g. domain validation failures,
     * business rule violations). Preferred over 400 for schema-valid but
     * logically invalid payloads.
     *
     * @param message - Human-readable explanation of why processing failed.
     * @param data    - Optional payload (e.g. structured validation errors per field).
     *
     * @example
     * send.unprocessableEntity("The 'birthDate' must be in the past.");
     * send.unprocessableEntity("Validation errors.", { fields: { age: "Must be ≥ 18" } });
     */
    unprocessableEntity: TSendPropsFn;
    /**
     * Sends a **423 Locked** response.
     *
     * Use when the resource being accessed is locked (e.g. being edited by
     * another user, or under an administrative hold).
     *
     * @param message - Human-readable explanation of why the resource is locked.
     * @param data    - Optional payload (e.g. lock owner, estimated unlock time).
     *
     * @example
     * send.locked("This document is currently being edited by another user.");
     * send.locked("Resource is locked.", { lockedBy: "alice@example.com", until: "2025-06-01T12:00:00Z" });
     */
    locked: TSendPropsFn;
    /**
     * Sends a **429 Too Many Requests** response.
     *
     * Use when the client has exceeded an allowed request rate or quota.
     * Consider pairing this with a `Retry-After` header at the middleware level.
     *
     * @param message - Human-readable explanation of the rate limit breach.
     * @param data    - Optional payload (e.g. retry delay, remaining quota).
     *
     * @example
     * send.tooManyRequest("Rate limit reached. Try again in 60 seconds.");
     * send.tooManyRequest("Quota exceeded.", { retryAfter: 60 });
     */
    tooManyRequest: TSendPropsFn;
    /**
     * Sends a **500 Internal Server Error** response.
     *
     * Use for unexpected, unhandled server-side failures.
     * Avoid leaking internal stack traces or sensitive details in the message.
     *
     * @param message - Human-readable explanation safe to expose to the client.
     * @param data    - Optional payload (use sparingly — never expose raw stack traces).
     *
     * @example
     * send.internalError("An unexpected error occurred. Please try again later.");
     */
    internalError: TSendPropsFn;
    /**
     * Sends a **501 Not Implemented** response.
     *
     * Use when the server does not support the functionality required to
     * fulfil the request (e.g. an HTTP method that is recognised but not
     * implemented on this server, or a feature under development).
     *
     * @param message - Human-readable explanation of what is not implemented.
     * @param data    - Optional payload (e.g. planned availability date).
     *
     * @example
     * send.notImplemented("The PATCH method is not yet supported on this resource.");
     */
    notImplemented: TSendPropsFn;
    /**
     * Sends a **502 Bad Gateway** response.
     *
     * Use when this server, acting as a gateway or proxy, received an invalid
     * response from an upstream server.
     *
     * @param message - Human-readable explanation safe to expose to the client.
     * @param data    - Optional payload (e.g. upstream service identifier).
     *
     * @example
     * send.badGateway("The payment provider returned an unexpected response.");
     */
    badGateway: TSendPropsFn;
    /**
     * Sends a **503 Service Unavailable** response.
     *
     * Use when the server is temporarily unable to handle the request due to
     * maintenance, overload, or a dependency outage. Pair with a
     * `Retry-After` header when the downtime window is known.
     *
     * @param message - Human-readable explanation including estimated recovery time when available.
     * @param data    - Optional payload (e.g. `{ retryAfter: "2025-06-01T06:00:00Z" }`).
     *
     * @example
     * send.serviceUnavailable("Scheduled maintenance until 06:00 UTC.");
     * send.serviceUnavailable("Server overloaded.", { retryAfter: "2025-06-01T06:00:00Z" });
     */
    serviceUnavailable: TSendPropsFn;
    /**
     * Sends a **504 Gateway Timeout** response.
     *
     * Use when this server, acting as a gateway or proxy, did not receive a
     * timely response from an upstream server.
     *
     * @param message - Human-readable explanation of which upstream timed out.
     * @param data    - Optional payload (e.g. upstream service name, timeout duration).
     *
     * @example
     * send.gatewayTimeout("The database did not respond within the allowed time.");
     * send.gatewayTimeout("Upstream timeout.", { service: "payments-api", timeoutMs: 5000 });
     */
    gatewayTimeout: TSendPropsFn;
}

/**
 * Identifies the project root for a given caller path by traversing up the filesystem.
 */
declare function identifyProjectRoot(filePath: string): string | undefined;
/**
 * Retrieves the project root of the code currently executing by analyzing the stack trace.
 */
declare function getCallerProjectRoot(): string | undefined;

/***************************************************************************
 * XyPriss - Fast And Secure
 *
 * @author Nehonix
 * @license Nehonix OSL (NOSL)
 *
 * Copyright (c) 2025 Nehonix. All rights reserved.
 ****************************************************************************/
/**
 * Resolves a single MIME type from a file extension.
 *
 * @param ext - The file extension (e.g., '.png' or 'jpg').
 * @returns The corresponding MIME type or 'application/octet-stream' if unknown.
 */
declare const getMime: (ext: string) => string;
/**
 * Advanced utility to resolve multiple MIME types from file extensions.
 *
 * This helper is designed to simplify server configurations, particularly for
 * 'fileUpload' and security policies, by allowing developers to specify
 * human-readable extensions instead of complex MIME strings.
 *
 * FEATURES:
 * - Supports single extensions or arrays.
 * - Automatically normalizes extensions (handles missing dots).
 * - Deduplicates results to ensure a clean MIME array.
 * - Can fall back to global 'fileUpload.allowedExtensions' if no argument is provided.
 *
 * @param extensions - A single extension (e.g., '.png') or an array (e.g., ['.jpg', '.pdf']).
 *                     If omitted, the function attempts to read from global configuration.
 * @returns A unique array of resolved MIME types.
 *
 * @example
 * // 1. Map an array of extensions for file upload configuration
 * const uploadConfig = {
 *   allowedMimeTypes: getMimes(['.png', '.jpg', '.jpeg', '.webp'])
 * };
 * // Result: ['image/png', 'image/jpeg', 'image/webp']
 *
 * @example
 * // 2. Map a single extension
 * const mimes = getMimes('.pdf');
 * // Result: ['application/pdf']
 *
 * @example
 * // 3. Automatic detection from xypriss.config.json
 * // If config has: { "fileUpload": { "allowedExtensions": [".zip", ".rar"] } }
 * const mimes = getMimes();
 * // Result: ['application/zip', 'application/vnd.rar']
 */
declare const getMimes: (extensions?: string | string[]) => string[];

/***************************************************************************
 * XyPriss - Fast And Secure
 *
 * XStatic - High-Performance, Sandboxed Static File Serving.
 * Optimized with Meta-Cache (LRU) and XHSC (Go) Zero-Copy delegation.
 ***************************************************************************/

/**
 * **XStatic** — High-performance, sandboxed static file server for XyPriss.
 *
 * XStatic handles static asset delivery through a two-layer architecture:
 *
 * 1. **TypeScript layer** — responsible for URI normalization, dotfile/sandbox
 *    security enforcement, and LRU meta-cache (anti-DDoS I/O shield).
 * 2. **XHSC (Go) layer** — takes over once the request is validated, streaming
 *    the file directly from disk to the TCP socket using zero-copy (`sendfile`),
 *    native ETags, `304 Not Modified`, and `206 Partial Content` (Range requests).
 *
 * ### Architectural Flow
 * ```
 * Request
 *   → URI Normalization
 *   → Dotfile / Restricted File Check
 *   → Sandbox Enforcement (Project Root + Directory Jail)
 *   → LRU Meta-Cache (negative cache — blocks repeated 404 storms)
 *   → Filesystem Existence Check
 *   → XHSC Zero-Copy Delegation (Go)
 *   → Response
 * ```
 *
 * ### Basic Usage
 * ```typescript
 * import { XStatic } from "xypriss";
 *
 * const app  = createServer(options);
 * const xs   = new XStatic(app, __sys__);
 *
 * xs.define("/assets", "./public");
 * xs.define("/docs",   "./documentation");
 *
 * // Explicit opt-out of sandbox (e.g. user-upload directory)
 * xs.define("/avatars", "/var/www/uploads/avatars", {
 *   allowOutsideRoot: true,
 *   unsafe: true,
 * });
 * ```
 *
 * ### Global Configuration (via `createServer`)
 * ```typescript
 * const app = createServer({
 *   static: {
 *     zeroCopy:       true,   // Enable sendfile() syscall in XHSC
 *     ConcurrencyPool: 1024,  // Max goroutines for disk I/O
 *     lruCacheSize:   5000,   // Entries kept in negative meta-cache
 *     dotfiles:       "deny", // Block .env, .git, etc.
 *     defaultMaxAge:  86400,  // Default Cache-Control max-age (seconds)
 *   },
 * });
 * ```
 *
 * @remarks
 * XStatic is **instance-scoped** by design. Avoid singleton patterns when
 * running under XMS (XyPriss MultiServer) to prevent cross-instance route
 * leakage and memory pressure.
 *
 * @see {@link StaticOptions}  for per-route configuration.
 * @see {@link IXStatic}       for global configuration shape.
 * @see {@link XStaticMetaCache} for LRU cache implementation details.
 */
declare class XStatic {
    private app;
    private sys;
    private metaCache;
    private pendingStats;
    private logger;
    private qLog;
    private globalConfig;
    /**
     * Creates a new `XStatic` instance bound to the given server and system API.
     *
     * Reads the `"static"` key from the application config (`Configs.get`),
     * initialises the LRU meta-cache with the configured size (default: **5 000**
     * entries), and wires up internal loggers.
     *
     * @param app - The XyPriss application instance to register middleware on.
     * @param sys - The XHSC system handle (`__sys__`), which exposes the sandboxed
     *   `fs` and `path` APIs as well as the project root (`__root__`).
     *
     * @throws {Error} If the global `"static"` configuration block fails Zod schema
     *   validation (see {@link validateConfigs}).
     *
     * @example
     * ```typescript
     * const xs = new XStatic(app, __sys__);
     * ```
     */
    constructor(app: XyApp, sys: XyPrissXHSC);
    /**
     * Validates the global static configuration block at startup.
     *
     * Performs two sequential checks:
     *
     * 1. **Dotfiles type guard** — ensures `dotfiles` is either `"allow"` or
     *    `"deny"` when provided as a plain string.
     * 2. **Zod schema validation** — runs `IXStaticSchem.safeParse` against the
     *    full config object to catch unknown or malformed fields.
     *
     * @throws {Error} `"Invalid configuration for 'dotfiles'"` — if `dotfiles` is
     *   present but not a string.
     * @throws {Error} `"Invalid dotfiles mode. Expected one of 'allow' or 'deny',
     *   but got: '<value>'"` — if the dotfiles string is not a recognised mode.
     * @throws {Error} Zod validation message — if the config object fails the
     *   `IXStaticSchem` schema.
     *
     * @internal
     */
    private validateConfigs;
    /**
     * Registers a static file route on the application.
     *
     * Mounts an async middleware on `route` that handles the full request
     * lifecycle: URI normalization → dotfile/restricted-file protection →
     * sandbox enforcement → LRU cache lookup → filesystem check →
     * XHSC zero-copy delegation.
     *
     * ---
     *
     * ### Security Layers
     *
     * **1 — Dotfile & Restricted File Protection**
     *
     * Controlled by `globalConfig.dotfiles` (default: `"deny"`). When in deny
     * mode, any file whose name starts with `"."` (e.g. `.env`, `.git`) or
     * appears in a custom restricted list is rejected with `403 Forbidden` before
     * any disk access occurs.
     *
     * **2 — Sandbox Enforcement** *(skipped when `options.unsafe` or
     * `options.allowOutsideRoot` is `true`)*
     *
     * - **Project Root Check** — the resolved `dir` must be inside the project
     *   root (`sys.__root__`). Prevents accidentally serving system directories.
     * - **Directory Jail** — the resolved request path must be strictly inside
     *   `dir`. Blocks path-traversal attacks (`../../etc/passwd`).
     *
     * **3 — LRU Meta-Cache (Anti-DDoS I/O Shield)**
     *
     * Paths that have previously resolved to `"not found"` are cached in memory.
     * Subsequent requests for the same missing path are rejected at the cache
     * layer — zero disk I/O, pure RAM response — protecting against flood
     * attacks that enumerate non-existent files.
     *
     * ---
     *
     * ### Zero-Copy Delegation to XHSC (Go)
     *
     * Once a request passes all validation steps, TypeScript sends a single IPC
     * signal to the XHSC worker: `"request #<id> may read <absolutePath>"`.
     * XHSC then streams the file directly from disk to the client TCP socket
     * using `sendfile()`, bypassing the V8/Node.js heap entirely. HTTP-level
     * concerns (ETag generation, `304 Not Modified`, `206 Partial Content` for
     * Range requests) are all handled natively by Go's `http.ServeContent`.
     *
     * ---
     *
     * @param route - The URL prefix to mount (e.g. `"/assets"`). Automatically
     *   normalised via {@link UriNormalizer.normalizePath}.
     * @param dir   - The filesystem directory to serve from (e.g. `"./public"`).
     *   Relative paths are resolved against the process working directory.
     * @param options - Optional per-route overrides. See {@link StaticOptions}.
     *
     * @returns `void` — the middleware is registered as a side effect.
     *
     * @throws This method does not throw. Internal errors are caught, logged via
     *   the application logger, and forwarded to `next()` so the request chain
     *   can continue (or fall through to a global error handler).
     *
     * @example
     * ```typescript
     * // Serve ./public under /assets (fully sandboxed, dotfiles denied)
     * xs.define("/assets", "./public");
     *
     * // Custom Cache-Control for long-lived build artefacts (1 week)
     * xs.define("/dist", "./build", { maxAge: 604800 });
     *
     * // User-uploaded content outside the project root (explicit opt-out)
     * xs.define("/uploads", "/var/www/uploads", {
     *   allowOutsideRoot: true,
     *   unsafe: true,
     * });
     * ```
     *
     * @see {@link StaticOptions} for the full list of per-route options.
     * @see {@link serve} for the deprecated alias.
     */
    define(route: string, dir: string, options?: StaticOptions): void;
    /**
     * @deprecated Use {@link define} instead. Will be removed in a future release.
     *
     * Alias for {@link define} — kept for beta compatibility only.
     *
     * @param route   - The URL prefix to mount (e.g. `"/assets"`).
     * @param dir     - The filesystem directory to serve from.
     * @param options - Optional per-route overrides. See {@link StaticOptions}.
     *
     * @example
     * ```typescript
     * // ❌ Deprecated — avoid in new code
     * xs.serve("/assets", "./public");
     *
     * // ✅ Preferred
     * xs.define("/assets", "./public");
     * ```
     */
    serve(_route: string, _dir: string, _options?: StaticOptions): void;
}

/***************************************************************************
 * XyPrissJS - Fast And Secure
 *
 * @author Nehonix
 * @license Nehonix OSL (NOSL)
 *
 * Copyright (c) 2025 Nehonix. All rights reserved.
 *
 * This License governs the use, modification, and distribution of software
 * provided by NEHONIX under its open source projects.
 * NEHONIX is committed to fostering collaborative innovation while strictly
 * protecting its intellectual property rights.
 * Violation of any term of this License will result in immediate termination of all granted rights
 * and may subject the violator to legal action.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
 * AND NON-INFRINGEMENT.
 * IN NO EVENT SHALL NEHONIX BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * OR CONSEQUENTIAL DAMAGES ARISING FROM THE USE OR INABILITY TO USE THE SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 ***************************************************************************** */

/**
 * Default router instance for quick start
 */
declare function Router(): XyPrissRouter;

export { ConfigurationManager as CM, ConfigurationManager as Configs, FileUploadAPI as FLA, FileUploadAPI, Plugin, PluginHookIds, Router, SecurityMiddleware, Send, Upload, XJsonResponseHandler, XStatic, XyGuard, MultiServerApp as XyPMS, XyPrissRouter, XyPrissXHSC, __cfg__, __const__, __sys__, createOptimalCache, createServer, getCallerProjectRoot, getIp, getMime, getMimes, identifyProjectRoot, initializeFileUpload, mergeWithDefaults, mergeWithDefaults as mwdef, quickServer, uploadAny, uploadArray, uploadFields, uploadSingle, xems };
export type { ArchiveOptions, BatchRenameChange, CacheConfig, FileUploadConfig as FiUpConfig, FileUploadConfig, GetIpResult, IpSource, MonitorSnapshot, MultiServerConfig, NetworkStats, NextFunction, PerformanceConfig, PluginCreator, PluginServer, ProcessInfo, ProcessMonitorSnapshot, XyPrisRequest as Request, RequestHandler, XyPrisResponse as Response, RoutRateLimit, RouteConfig, RouteGuard, RouteMeta, RouteOptions, ParamType as RouteParamType, SecurityConfig, ServerOptions$1 as ServerOptions, XyPrisRequest$1 as XRequest, XyPrisResponse$1 as XResponse, XemsTypes, XyPrisRequest$1 as XyPrisRequest, XyPrisResponse$1 as XyPrisResponse, XyPrissApp, XyPrissPlugin };
