import { Platform, SerializableFunction, ThreadOptions, ThreadResult, WorkerAdapter, WorkerInstance } from '../types'; /** * Configuration options for base worker instance. * These options control common behavior across all platforms. */ export interface BaseWorkerConfig { /** Maximum time in ms to wait for worker initialization */ initTimeout?: number; /** Whether to automatically cleanup on error */ autoCleanupOnError?: boolean; /** Whether to track execution metrics */ trackMetrics?: boolean; } /** * Execution metrics collected during worker operation. * Useful for monitoring and debugging performance issues. */ export interface WorkerExecutionMetrics { /** Start timestamp of the execution */ startTime: number; /** End timestamp of the execution */ endTime: number; /** Total execution duration in milliseconds */ duration: number; /** Whether the execution was successful */ success: boolean; /** Error message if execution failed */ errorMessage?: string; } /** * Abstract base class for worker instances across all platforms. * * Implements common functionality like: * - Execution state tracking * - Timeout handling * - Abort signal management * - Metrics collection * * Subclasses must implement platform-specific worker creation and cleanup. * * @abstract * @implements {WorkerInstance} * * @example * ```typescript * class MyWorkerInstance extends AbstractWorkerInstance { * protected async createPlatformWorker(script: string): Promise { * // Platform-specific worker creation * } * * protected async cleanupPlatformWorker(): Promise { * // Platform-specific cleanup * } * * protected async postMessageToWorker(data: unknown): Promise> { * // Platform-specific message passing * } * } * ``` */ export declare abstract class AbstractWorkerInstance implements WorkerInstance { protected readonly platform: Platform; /** Unique identifier for this worker instance */ readonly id: string; /** Whether the worker has been terminated */ protected isTerminated: boolean; /** Whether the worker is currently executing a task */ protected isExecuting: boolean; /** Collection of execution metrics for monitoring */ protected executionHistory: WorkerExecutionMetrics[]; /** Configuration for this worker instance */ protected config: Required; /** * Creates a new abstract worker instance. * * @param platform - The platform identifier (browser, node, deno, bun) * @param config - Optional configuration overrides */ constructor(platform: Platform, config?: BaseWorkerConfig); /** * Executes a function in the worker thread. * * This method handles common concerns like: * - State validation (terminated, already executing) * - Timeout management * - Abort signal handling * - Metrics collection * * @template T - The expected return type * @param fn - The function to execute in the worker * @param data - The data to pass to the function * @param options - Execution options (timeout, signal, etc.) * @returns Promise resolving to the execution result * @throws {WorkerError} If worker is terminated or already executing */ execute(fn: SerializableFunction, data: unknown, options?: ThreadOptions): Promise>; /** * Terminates the worker and releases resources. * * After termination, the worker instance cannot be reused. * This method is idempotent - calling it multiple times is safe. */ terminate(): Promise; /** * Checks if the worker is currently idle (not executing and not terminated). * * @returns true if the worker can accept new tasks */ isIdle(): boolean; /** * Gets the execution history for this worker. * Useful for monitoring and debugging. * * @param limit - Maximum number of records to return (default: 10) * @returns Array of execution metrics in chronological order (oldest first) */ getExecutionHistory(limit?: number): WorkerExecutionMetrics[]; /** * Gets the average execution time for this worker. * * @returns Average execution time in milliseconds, or 0 if no history */ getAverageExecutionTime(): number; /** * Gets the success rate for this worker. * * @returns Success rate as a decimal (0.0 to 1.0), or 1.0 if no history */ getSuccessRate(): number; /** * Validates that the worker is in a valid state for execution. * * @throws {WorkerError} If worker is terminated or already executing */ protected validateState(): void; /** * Executes with timeout and abort signal handling. * Wraps the platform-specific execution with common controls. * * @template T - The expected return type * @param workerScript - The serialized worker script * @param data - The data to pass to the worker * @param options - Execution options * @param startTime - The execution start timestamp * @returns Promise resolving to the execution result */ protected executeWithControls(workerScript: string, data: unknown, options: ThreadOptions, startTime: number): Promise>; /** * Creates a promise that rejects when the abort signal is triggered. * * @template T - The expected return type * @param signal - The abort signal to monitor * @returns Promise that rejects on abort */ protected createAbortPromise(signal: AbortSignal): Promise>; /** * Creates a promise that rejects after the specified timeout. * * @template T - The expected return type * @param timeout - Timeout in milliseconds * @returns Promise that rejects on timeout */ protected createTimeoutPromise(timeout: number): Promise>; /** * Records execution metrics for monitoring. * * @param startTime - The execution start timestamp * @param success - Whether the execution was successful * @param errorMessage - Error message if execution failed */ protected recordMetrics(startTime: number, success: boolean, errorMessage?: string): void; /** * Handles cleanup after an error occurs. * Called when autoCleanupOnError is enabled. */ protected cleanupOnError(): Promise; /** * Performs the platform-specific worker execution. * * @template T - The expected return type * @param workerScript - The serialized worker script * @param data - The data to pass to the worker * @param options - Execution options * @param startTime - The execution start timestamp * @returns Promise resolving to the execution result * * @abstract */ protected abstract performPlatformExecution(workerScript: string, data: unknown, options: ThreadOptions, startTime: number): Promise>; /** * Cleans up platform-specific worker resources. * * @abstract */ protected abstract cleanupPlatformWorker(): Promise; } /** * Abstract base class for worker adapters. * * Provides common factory pattern implementation for creating workers. * Subclasses implement platform-specific worker creation. * * @abstract * @implements {WorkerAdapter} */ export declare abstract class AbstractWorkerAdapter implements WorkerAdapter { /** The platform this adapter supports */ abstract readonly platform: Platform; /** * Creates a new worker instance for this platform. * * @param script - Initial script (may be empty, actual script provided during execution) * @returns Promise resolving to the new worker instance */ abstract createWorker(script: string): Promise; /** * Terminates a worker instance and releases resources. * * @param worker - The worker instance to terminate */ terminateWorker(worker: WorkerInstance): Promise; /** * Checks if this adapter is supported in the current environment. * * @returns true if workers can be created in this environment */ abstract isSupported(): boolean; /** * Gets the recommended number of workers for this platform. * Uses the optimal thread count from platform utilities for * cross-platform consistency. * * @returns Recommended worker count based on hardware and platform */ getRecommendedWorkerCount(): number; } /** * Creates a standardized error message for worker operations. * Ensures consistent error formatting across all adapters. * * @param operation - The operation that failed * @param platform - The platform where the error occurred * @param originalError - The original error if available * @returns Formatted error message */ export declare function createWorkerErrorMessage(operation: string, platform: Platform, originalError?: Error): string; /** * Type guard to check if an object is a WorkerInstance. * * @param obj - The object to check * @returns true if the object implements WorkerInstance */ export declare function isWorkerInstance(obj: unknown): obj is WorkerInstance; /** * Configuration for Web-API-based workers (Browser, Deno, Bun). * * This configuration extends the base configuration with * web-worker-specific options. */ export interface WebWorkerConfig extends BaseWorkerConfig { /** Worker name for debugging (optional) */ workerName?: string; /** Worker type: 'classic' or 'module' */ workerType?: 'classic' | 'module'; } /** * Abstract base class for Web-API-based workers. * * This class implements the shared logic for Browser, Deno, * and Bun workers, all of which use the Web Worker API. It abstracts: * * - Blob URL creation and cleanup * - Event handler setup (message, error, messageerror) * - Timeout and abort-signal handling * - Transferable objects support * * Subclasses only need to implement worker creation with platform-specific * options. * * @abstract * @extends AbstractWorkerInstance * * @example * ```typescript * class MyPlatformWorkerInstance extends AbstractWebWorkerInstance { * protected createPlatformWorkerOptions(): WorkerOptions { * return { type: 'module', name: this.id }; * } * } * ``` */ export declare abstract class AbstractWebWorkerInstance extends AbstractWorkerInstance { /** The active web worker */ protected worker: Worker | null; /** The blob URL of the worker script */ protected workerUrl: string | null; /** Web-worker-specific configuration */ protected readonly webConfig: Required; /** * Creates a new web worker instance. * * @param platform - The platform id * @param config - Optional configuration */ constructor(platform: Platform, config?: WebWorkerConfig); /** * Performs the platform-specific worker execution. * * Implements the Template Method pattern: shared logic * (blob creation, event handling) is implemented here, while * subclasses only adjust the worker options. * * @template T - The expected return type * @param workerScript - The serialized worker script * @param data - The data to pass * @param options - Execution options * @param startTime - Execution start timestamp * @returns Promise with the execution result */ protected performPlatformExecution(workerScript: string, data: unknown, options: ThreadOptions, startTime: number): Promise>; /** * Creates platform-specific worker options. * * Subclasses override this method to add platform-specific * options such as Deno permissions or Bun credentials. * * @returns Worker options for new Worker() * @abstract */ protected abstract createPlatformWorkerOptions(): WorkerOptions; /** * Sends a message to the worker. * * Can be overridden by subclasses for platform-specific * behavior (e.g. optimized transferables). * * @param data - The data to send * @param transferable - Optional transferable objects */ protected postMessageToWorker(data: unknown, transferable?: Transferable[]): void; /** * Cleans up web worker resources. * * @param timeoutId - Optional timeout id to clear */ protected cleanupWebWorker(timeoutId?: ReturnType): void; /** * Cleans up platform-specific worker resources. * * Implementation of the abstract method from AbstractWorkerInstance. */ protected cleanupPlatformWorker(): Promise; } //# sourceMappingURL=base.d.ts.map