import { EventEmitter } from 'events';
import type { Context } from 'aws-lambda';
import type { RuntimeAwakeErrorDetails } from '../../../lib/runtime-web/runtime-awake';
/**
 * Default inspector port for debugger attachment.
 */
export declare const DEFAULT_INSPECTOR_PORT = 9229;
/**
 * Default timeout for worker operations in milliseconds.
 */
export declare const DEFAULT_WORKER_TIMEOUT_MS = 30000;
/**
 * Timeout warning threshold as a percentage (0.0 to 1.0).
 * Warning is emitted when elapsed time exceeds this percentage of the timeout.
 *
 * @see Requirements 16.3
 */
export declare const TIMEOUT_WARNING_THRESHOLD = 0.8;
/**
 * Error classification for distinguishing error sources.
 *
 * @see Requirements 17.5
 */
export type ErrorClassification = 'handler-error' | 'infrastructure-error';
/**
 * Worker message types for IPC communication.
 */
export type WorkerMessageType = 'execute' | 'reload' | 'shutdown' | 'ping';
/**
 * Message sent from main process to worker.
 */
export interface WorkerMessage {
    /** Message type */
    readonly type: WorkerMessageType;
    /** Unique message ID for correlation */
    readonly id: string;
    /** Message payload */
    readonly payload: unknown;
}
/**
 * Execute message payload.
 */
export interface ExecutePayload {
    /** Handler function code or reference */
    readonly handlerCode: string;
    /** Export name of the handler */
    readonly exportName: string;
    /** Lambda event */
    readonly event: unknown;
    /** Lambda context */
    readonly context: Context;
    /** Environment variables to set */
    readonly environment: Record<string, string>;
    /** Microservice name */
    readonly microserviceName: string;
    /** Handler hash key */
    readonly handlerHashKey: string;
}
/**
 * Result from worker process.
 */
export interface WorkerResult {
    /** Correlation ID matching the request */
    readonly id: string;
    /** Whether execution succeeded */
    readonly success: boolean;
    /** Handler return value (if success) */
    readonly result?: unknown;
    /** Error details (if failure) */
    readonly error?: WorkerErrorDetails;
    /** Execution duration in milliseconds */
    readonly durationMs: number;
    /** Error classification */
    readonly errorClassification?: ErrorClassification;
}
/**
 * Error details captured from worker.
 *
 * @see Requirements 17.1, 17.2
 */
export interface WorkerErrorDetails {
    /** Error type/class name */
    readonly name: string;
    /** Error message */
    readonly message: string;
    /** Stack trace */
    readonly stack: string;
}
/**
 * Worker manager configuration.
 */
export interface WorkerManagerConfig {
    /** Inspector port for debugger attachment (default: 9229) */
    readonly inspectorPort?: number;
    /** Enable inspector (default: true) */
    readonly inspectorEnabled?: boolean;
    /** Worker script path (default: built-in worker) */
    readonly workerScriptPath?: string;
    /** Timeout for worker operations in milliseconds */
    readonly timeoutMs?: number;
}
/**
 * Worker state.
 */
export type WorkerState = 'idle' | 'initializing' | 'ready' | 'executing' | 'reloading' | 'shutdown';
/**
 * Events emitted by WorkerManager.
 */
export interface WorkerManagerEvents {
    'state-change': (state: WorkerState) => void;
    'error': (error: Error) => void;
    'execution-complete': (result: WorkerResult) => void;
    'worker-exit': (code: number | null, signal: string | null) => void;
    'timeout-warning': (warning: TimeoutWarning) => void;
}
/**
 * Timeout warning information.
 *
 * Emitted when handler execution time exceeds 80% of the configured timeout.
 *
 * @see Requirements 16.3
 */
export interface TimeoutWarning {
    /** Request/operation ID for correlation */
    readonly requestId: string;
    /** Function/handler name */
    readonly functionName: string;
    /** Configured timeout in milliseconds */
    readonly configuredTimeoutMs: number;
    /** Elapsed time in milliseconds */
    readonly elapsedMs: number;
    /** Remaining time in milliseconds */
    readonly remainingMs: number;
    /** Warning threshold percentage (0.0 to 1.0) */
    readonly thresholdPercent: number;
    /** Human-readable warning message */
    readonly message: string;
    /** ISO timestamp when warning was generated */
    readonly timestamp: string;
}
/**
 * Create a timeout warning object.
 *
 * @param requestId - Request/operation ID
 * @param functionName - Function/handler name
 * @param configuredTimeoutMs - Configured timeout in milliseconds
 * @param elapsedMs - Elapsed time in milliseconds
 * @param thresholdPercent - Warning threshold percentage (default: 0.8)
 * @returns TimeoutWarning object
 *
 * @see Requirements 16.3, 16.5
 */
export declare function createTimeoutWarning(requestId: string, functionName: string, configuredTimeoutMs: number, elapsedMs: number, thresholdPercent?: number): TimeoutWarning;
/**
 * Check if elapsed time exceeds the timeout warning threshold.
 *
 * @param elapsedMs - Elapsed time in milliseconds
 * @param timeoutMs - Total timeout in milliseconds
 * @param threshold - Warning threshold percentage (default: 0.8)
 * @returns True if elapsed time exceeds threshold
 *
 * @see Requirements 16.3
 */
export declare function shouldEmitTimeoutWarning(elapsedMs: number, timeoutMs: number, threshold?: number): boolean;
/**
 * Calculate the time until warning threshold is reached.
 *
 * @param timeoutMs - Total timeout in milliseconds
 * @param threshold - Warning threshold percentage (default: 0.8)
 * @returns Time until warning threshold in milliseconds
 */
export declare function calculateTimeUntilWarning(timeoutMs: number, threshold?: number): number;
/**
 * Capture error details from an Error object.
 *
 * Extracts errorType, errorMessage, and stackTrace from thrown errors.
 *
 * @param error - The error to capture
 * @returns Captured error details
 *
 * @see Requirements 17.1, 17.2
 */
export declare function captureErrorDetails(error: unknown): WorkerErrorDetails;
/**
 * Convert WorkerErrorDetails to RuntimeAwakeErrorDetails format.
 *
 * @param details - Worker error details
 * @returns RuntimeAwakeErrorDetails format
 */
export declare function toRuntimeAwakeErrorDetails(details: WorkerErrorDetails): RuntimeAwakeErrorDetails;
/**
 * Parse a stack trace string into an array of frame strings.
 *
 * @param stack - Stack trace string
 * @returns Array of stack frame strings
 */
export declare function parseStackTrace(stack: string): string[];
/**
 * Classify an error as handler error or infrastructure error.
 *
 * Handler errors are thrown by user code (the Lambda handler).
 * Infrastructure errors are caused by the Live Dev system itself
 * (MQTT failures, S3 failures, timeouts, etc.).
 *
 * @param error - The error to classify
 * @param context - Additional context about where the error occurred
 * @returns Error classification
 *
 * @see Requirements 17.5
 */
export declare function classifyError(error: unknown, context?: 'handler' | 'infrastructure' | 'unknown'): ErrorClassification;
/**
 * Check if an error is a known infrastructure error type.
 *
 * @param errorName - Error name/type
 * @returns True if infrastructure error
 */
export declare function isInfrastructureErrorType(errorName: string): boolean;
/**
 * Error class for worker manager failures.
 */
export declare class WorkerManagerError extends Error {
    readonly classification: ErrorClassification;
    readonly cause?: Error | undefined;
    constructor(message: string, classification?: ErrorClassification, cause?: Error | undefined);
}
/**
 * Error class for worker timeout.
 */
export declare class WorkerTimeoutError extends WorkerManagerError {
    readonly operationId: string;
    readonly timeoutMs: number;
    readonly elapsedMs: number;
    constructor(operationId: string, timeoutMs: number, elapsedMs: number);
}
/**
 * Error class for worker communication failures.
 */
export declare class WorkerCommunicationError extends WorkerManagerError {
    constructor(message: string, cause?: Error);
}
/**
 * Worker Process Manager for Awake Lambda Development.
 *
 * Manages a child process for executing Lambda handlers with debugger support.
 * Uses IPC for communication between main process and worker.
 *
 * Architecture:
 * - Main process: Holds MQTT connection, receives requests
 * - Worker process: Executes handlers with inspector enabled
 *
 * @see Requirements 4.9
 *
 * @example
 * ```typescript
 * const manager = new WorkerManager({ inspectorPort: 9229 });
 * await manager.initialize();
 *
 * const result = await manager.executeHandler(
 *   handlerCode,
 *   'handler',
 *   event,
 *   context,
 *   environment,
 *   'payments',
 *   'abc123'
 * );
 *
 * if (result.success) {
 *   console.log('Result:', result.result);
 * } else {
 *   console.error('Error:', result.error);
 * }
 *
 * await manager.shutdown();
 * ```
 */
export declare class WorkerManager extends EventEmitter {
    /** Worker process */
    private worker;
    /** Current worker state */
    private state;
    /** Pending operations waiting for response */
    private pendingOperations;
    /** Configuration */
    private readonly config;
    /** Initialization promise */
    private initPromise;
    /**
     * Create a new WorkerManager.
     *
     * @param config - Worker manager configuration
     */
    constructor(config?: WorkerManagerConfig);
    /**
     * Get current worker state.
     */
    getState(): WorkerState;
    /**
     * Check if worker is ready for execution.
     */
    isReady(): boolean;
    /**
     * Initialize the worker process.
     *
     * Forks a new Node.js process with inspector enabled for debugger attachment.
     *
     * @throws WorkerManagerError if initialization fails
     *
     * @see Requirements 4.9
     */
    initialize(): Promise<void>;
    private doInitialize;
    private setupWorkerEventHandlers;
    private waitForWorkerReady;
    private handleWorkerMessage;
    private sendMessage;
    private setState;
    /**
     * Execute a handler in the worker process.
     *
     * Sends the handler to the worker for execution and waits for the result.
     * Captures return value or thrown error, and tracks execution duration.
     *
     * @param handlerCode - Handler function code or module path
     * @param exportName - Export name of the handler function
     * @param event - Lambda event object
     * @param context - Lambda context object
     * @param environment - Environment variables to set
     * @param microserviceName - Microservice name for logging
     * @param handlerHashKey - Handler hash key for identification
     * @returns Worker result with success/error and duration
     *
     * @see Requirements 4.7, 4.8
     *
     * @example
     * ```typescript
     * const result = await manager.executeHandler(
     *   './handlers/payments.js',
     *   'chargeHandler',
     *   { httpMethod: 'POST', body: '{}' },
     *   context,
     *   { STRIPE_KEY: 'sk_test_...' },
     *   'payments',
     *   'abc123'
     * );
     * ```
     */
    executeHandler(handlerCode: string, exportName: string, event: unknown, context: Context, environment: Record<string, string>, microserviceName: string, handlerHashKey: string): Promise<WorkerResult>;
    /**
     * Reload handler in the worker process.
     *
     * Clears the require cache for the specified handler path,
     * allowing fresh module loading on next execution.
     *
     * @param handlerPath - Path to the handler module to reload
     *
     * @see Requirements 5.4, 5.5
     */
    reloadHandler(handlerPath: string): Promise<void>;
    /**
     * Shutdown the worker process.
     *
     * Sends shutdown signal and waits for graceful termination.
     * Force kills after timeout if worker doesn't exit.
     */
    shutdown(): Promise<void>;
    /**
     * Get the inspector port.
     */
    getInspectorPort(): number;
    /**
     * Check if inspector is enabled.
     */
    isInspectorEnabled(): boolean;
    /**
     * Get the number of pending operations.
     */
    getPendingOperationCount(): number;
}
