/*!
 * harmony-plugin-manager v1.0.0
 * A comprehensive TypeScript library for generating harmonious color palettes with WCAG 2.1 accessibility compliance
 * 
 * Copyright (c) 2025 Khaled Sameer <khaled.smq@hotmail.com>
 * Licensed under MIT
 * 
 * Repository: https://github.com/KhaledSMQ/harmony-plugin-manager.git
 * 
 * Built: 2025-06-13T17:20:53.178Z
 */
/**
 * Plugin Type/**
 * Plugin Type Definitions
 *
 * Core types for plugin identification and configuration. These types form
 * the foundation of the plugin system's type safety and provide the structure
 * for plugin metadata, settings, and runtime configuration.
 *
 * ## Key Concepts
 *
 * - **PluginMetadata**: Immutable plugin identity and relationship information
 * - **PluginSettings**: Mutable runtime configuration and execution control
 * - **Type Safety**: Compile-time validation of plugin configurations
 * - **Semantic Versioning**: Standard version management for compatibility
 *
 * ## Usage Examples
 *
 * ### Basic Plugin Metadata
 * ```typescript
 * const metadata: PluginMetadata = {
 *   name: 'user-validator',
 *   version: '1.2.3',
 *   description: 'Validates user data according to business rules'
 * };
 * ```
 *
 * ### Plugin with Dependencies
 * ```typescript
 * const metadata: PluginMetadata = {
 *   name: 'user-enricher',
 *   version: '2.1.0',
 *   description: 'Enriches user data with external information',
 *   dependencies: ['user-validator', 'cache-manager'],
 *   tags: ['enrichment', 'user-management', 'external-api']
 * };
 * ```
 *
 * ### Runtime Settings Configuration
 * ```typescript
 * const settings: PluginSettings = {
 *   enabled: true,
 *   priority: 50,
 *   config: {
 *     apiUrl: 'https://api.example.com',
 *     timeout: 5000,
 *     retryAttempts: 3,
 *     enableCaching: true
 *   }
 * };
 * ```

 // ═══════════════════════════════════════════════════════════════════════════════════════════
 // Plugin Metadata Types
 // ═══════════════════════════════════════════════════════════════════════════════════════════

 /**
 * Plugin metadata for identification and dependency management
 *
 * Metadata provides immutable information about a plugin's identity, capabilities,
 * and relationships with other plugins. This information is used throughout the
 * plugin system for registration, dependency resolution, and documentation.
 *
 * @example
 * ```typescript
 * // Simple plugin metadata
 * const basicMetadata: PluginMetadata = {
 *   name: 'text-formatter',
 *   version: '1.0.0',
 *   description: 'Formats text according to specified rules'
 * };
 * ```
 *
 * @example
 * ```typescript
 * // Complex plugin with dependencies and tags
 * const advancedMetadata: PluginMetadata = {
 *   name: 'user-notification-sender',
 *   version: '2.3.1',
 *   description: 'Sends notifications to users via multiple channels',
 *   dependencies: [
 *     'user-validator',       // Must run after user validation
 *     'notification-formatter', // Must run after formatting
 *     'rate-limiter'         // Must respect rate limits
 *   ],
 *   tags: [
 *     'notification',         // Functional category
 *     'user-management',      // Domain area
 *     'external-service',     // Integration type
 *     'async-processing'      // Processing characteristic
 *   ]
 * };
 * ```
 *
 * @example
 * ```typescript
 * // Plugin metadata for different environments
 * const createMetadata = (environment: string): PluginMetadata => ({
 *   name: `analytics-${environment}`,
 *   version: '1.5.0',
 *   description: `Analytics plugin configured for ${environment}`,
 *   dependencies: environment === 'production'
 *     ? ['data-validator', 'performance-monitor']
 *     : ['data-validator'],
 *   tags: [
 *     'analytics',
 *     'data-processing',
 *     environment
 *   ]
 * });
 *
 * const prodMetadata = createMetadata('production');
 * const devMetadata = createMetadata('development');
 * ```
 */
interface PluginMetadata {
    /**
     * Unique plugin identifier within the manager
     *
     * The name serves as the primary identifier for the plugin and must be
     * unique within a single plugin manager instance. It's used for dependency
     * references, configuration lookup, and error reporting.
     *
     * **Naming Guidelines:**
     * - Use kebab-case (lowercase with hyphens)
     * - Be descriptive but concise
     * - Include functional purpose
     * - Avoid generic names like "plugin" or "processor"
     *
     * @example
     * ```typescript
     * // Good names
     * name: 'user-validator'
     * name: 'payment-processor'
     * name: 'email-notification-sender'
     * name: 'data-encryption-handler'
     *
     * // Avoid
     * name: 'plugin1'
     * name: 'processor'
     * name: 'handler'
     * ```
     */
    readonly name: string;
    /**
     * Semantic version string following semver specification
     *
     * Version information is used for compatibility checking, dependency
     * resolution, and change management. Must follow semantic versioning
     * format: MAJOR.MINOR.PATCH with optional pre-release and build metadata.
     *
     * **Version Guidelines:**
     * - MAJOR: Breaking changes to plugin interface
     * - MINOR: New features, backward compatible
     * - PATCH: Bug fixes, backward compatible
     * - Use pre-release for beta/alpha versions
     *
     * @example
     * ```typescript
     * // Standard versions
     * version: '1.0.0'        // Initial stable release
     * version: '1.2.3'        // Patch update
     * version: '2.0.0'        // Major breaking change
     *
     * // Pre-release versions
     * version: '1.0.0-alpha.1'    // Alpha release
     * version: '1.0.0-beta.2'     // Beta release
     * version: '1.0.0-rc.1'       // Release candidate
     *
     * // With build metadata
     * version: '1.0.0+20231201'   // With build identifier
     * ```
     */
    readonly version: string;
    /**
     * Human-readable description of plugin functionality
     *
     * Provides clear, concise documentation of what the plugin does.
     * Used for documentation generation, plugin catalogs, and developer
     * understanding. Should focus on the plugin's purpose and value.
     *
     * @example
     * ```typescript
     * // Good descriptions
     * description: 'Validates user input against defined schema rules'
     * description: 'Processes payment transactions through secure gateway'
     * description: 'Sends email notifications with templating support'
     * description: 'Compresses and optimizes image files for web delivery'
     *
     * // More detailed description
     * description: 'Advanced user authentication plugin supporting OAuth2, SAML, and JWT tokens with automatic session management and security monitoring'
     * ```
     */
    readonly description?: string;
    /**
     * Array of plugin names this plugin depends on
     *
     * Dependencies define the execution order requirements for this plugin.
     * All listed dependencies must be registered and enabled for this plugin
     * to execute. Dependencies are resolved through topological sorting.
     *
     * **Dependency Guidelines:**
     * - List only direct dependencies
     * - Use exact plugin names as registered
     * - Keep dependency chains minimal
     * - Avoid circular dependencies
     * - Consider optional vs required dependencies
     *
     * @example
     * ```typescript
     * // Simple dependency chain
     * // validation -> transformation -> output
     *
     * // Validation plugin (no dependencies)
     * dependencies: undefined
     *
     * // Transformation plugin (depends on validation)
     * dependencies: ['input-validator']
     *
     * // Output plugin (depends on transformation)
     * dependencies: ['data-transformer']
     *
     * // Complex plugin with multiple dependencies
     * dependencies: [
     *   'authentication-handler',    // Must authenticate first
     *   'rate-limiter',             // Must check rate limits
     *   'input-sanitizer',          // Must sanitize input
     *   'cache-manager'             // Must initialize cache
     * ]
     * ```
     *
     * @example
     * ```typescript
     * // Conditional dependencies based on configuration
     * const createDependencies = (config: PluginConfig): string[] => {
     *   const deps = ['core-validator'];
     *
     *   if (config.enableCaching) {
     *     deps.push('cache-manager');
     *   }
     *
     *   if (config.enableAnalytics) {
     *     deps.push('analytics-collector');
     *   }
     *
     *   return deps;
     * };
     *
     * dependencies: createDependencies(pluginConfig)
     * ```
     */
    readonly dependencies?: readonly string[] | undefined;
    /**
     * Categorical tags for organization and filtering
     *
     * Tags provide a flexible way to categorize and group plugins for
     * management, filtering, and organizational purposes. They enable
     * querying plugins by functionality, domain, or characteristics.
     *
     * **Tag Categories:**
     * - **Functional**: validation, transformation, output, monitoring
     * - **Domain**: user-management, payment, notification, security
     * - **Technical**: async, caching, external-api, database
     * - **Environment**: development, production, testing
     * - **Performance**: high-priority, background, real-time
     *
     * @example
     * ```typescript
     * // Functional categorization
     * tags: ['validation', 'input-processing', 'security']
     *
     * // Domain-based tagging
     * tags: ['user-management', 'authentication', 'session-handling']
     *
     * // Technical characteristics
     * tags: ['async-processing', 'external-api', 'caching', 'retry-logic']
     *
     * // Multi-dimensional tagging
     * tags: [
     *   'payment',              // Domain
     *   'transaction',          // Function
     *   'external-service',     // Integration
     *   'high-priority',        // Performance
     *   'production-ready'      // Maturity
     * ]
     * ```
     *
     * @example
     * ```typescript
     * // Environment-specific tags
     * const createTags = (environment: string): string[] => {
     *   const baseTags = ['data-processing', 'transformation'];
     *
     *   if (environment === 'development') {
     *     return [...baseTags, 'debug', 'verbose-logging'];
     *   } else if (environment === 'production') {
     *     return [...baseTags, 'optimized', 'monitoring'];
     *   }
     *
     *   return baseTags;
     * };
     *
     * tags: createTags(process.env.NODE_ENV)
     * ```
     */
    readonly tags?: readonly string[];
}
/**
 * Runtime configuration settings for plugin execution
 *
 * Settings control how plugins behave during execution and can be modified
 * between registrations and builds. They provide runtime flexibility while
 * maintaining type safety and validation.
 *
 * @example
 * ```typescript
 * // Basic settings
 * const settings: PluginSettings = {
 *   enabled: true,
 *   priority: 50,
 *   config: {}
 * };
 * ```
 *
 * @example
 * ```typescript
 * // Detailed configuration for API plugin
 * const apiSettings: PluginSettings = {
 *   enabled: true,
 *   priority: 75,
 *   config: {
 *     apiUrl: 'https://api.example.com/v1',
 *     timeout: 5000,
 *     retryAttempts: 3,
 *     retryDelay: 1000,
 *     enableCaching: true,
 *     cacheSize: 100,
 *     cacheTtl: 300000,
 *     headers: {
 *       'User-Agent': 'MyApp/1.0',
 *       'Accept': 'application/json'
 *     },
 *     authentication: {
 *       type: 'bearer',
 *       tokenProvider: 'oauth2'
 *     }
 *   }
 * };
 * ```
 *
 * @example
 * ```typescript
 * // Environment-specific settings
 * const createSettings = (env: string): PluginSettings => ({
 *   enabled: true,
 *   priority: env === 'production' ? 100 : 50,
 *   config: {
 *     logLevel: env === 'development' ? 'debug' : 'info',
 *     enableMetrics: env === 'production',
 *     batchSize: env === 'production' ? 100 : 10,
 *     timeout: env === 'production' ? 30000 : 10000
 *   }
 * });
 * ```
 */
interface PluginSettings {
    /**
     * Whether the plugin is enabled for execution
     *
     * Controls plugin participation in the execution pipeline. Disabled
     * plugins are registered but skipped during execution. This allows
     * for dynamic plugin activation based on runtime conditions.
     *
     * **Use Cases:**
     * - Feature flags and A/B testing
     * - Environment-specific activation
     * - Conditional feature enablement
     * - Maintenance mode handling
     * - User preference-based activation
     *
     * @example
     * ```typescript
     * // Always enabled
     * enabled: true
     *
     * // Environment-based enabling
     * enabled: process.env.NODE_ENV === 'production'
     *
     * // Feature flag-based enabling
     * enabled: featureFlags.enableAdvancedProcessing
     *
     * // User tier-based enabling
     * enabled: userTier === 'premium' || userTier === 'enterprise'
     *
     * // Configuration-driven enabling
     * enabled: config.features.includes('data-enrichment')
     * ```
     */
    readonly enabled: boolean;
    /**
     * Execution priority determining plugin order within dependency levels
     *
     * Higher priority values execute before lower priority values within
     * the same dependency level. Priority doesn't override dependencies
     * but provides fine-grained control over execution order for plugins
     * at the same dependency depth.
     *
     * **Priority Guidelines:**
     * - Use ranges for logical grouping (100-90: critical, 50-40: normal, 10-0: cleanup)
     * - Leave gaps for future insertions (use 100, 90, 80 instead of 100, 99, 98)
     * - Consider functional priority over arbitrary numbers
     * - Document priority ranges in your application
     *
     * @example
     * ```typescript
     * // Priority ranges example:
     *
     * // Critical security and validation (100-90)
     * priority: 100  // Authentication
     * priority: 95   // Authorization
     * priority: 90   // Rate limiting
     *
     * // Core business logic (80-60)
     * priority: 80   // Input validation
     * priority: 70   // Data transformation
     * priority: 60   // Business rules
     *
     * // Data processing (50-30)
     * priority: 50   // Enrichment
     * priority: 40   // Calculation
     * priority: 30   // Aggregation
     *
     * // Output and cleanup (20-0)
     * priority: 20   // Response formatting
     * priority: 10   // Compression
     * priority: 0    // Cleanup
     * ```
     *
     * @example
     * ```typescript
     * // Dynamic priority based on configuration
     * const getPriority = (pluginType: string, config: AppConfig): number => {
     *   const basePriorities = {
     *     'security': 100,
     *     'validation': 80,
     *     'processing': 50,
     *     'output': 20
     *   };
     *
     *   const base = basePriorities[pluginType] || 50;
     *
     *   // Adjust based on configuration
     *   if (config.enableHighPriorityProcessing) {
     *     return base + 10;
     *   }
     *
     *   return base;
     * };
     *
     * priority: getPriority('validation', appConfig)
     * ```
     */
    readonly priority: number;
    /**
     * Plugin-specific configuration object
     *
     * Provides flexible, type-safe configuration storage for plugin-specific
     * settings. The structure is defined by individual plugins and can contain
     * any serializable data needed for plugin operation.
     *
     * **Configuration Guidelines:**
     * - Use clear, descriptive property names
     * - Provide sensible defaults in plugin code
     * - Validate configuration in plugin initialization
     * - Document expected configuration structure
     * - Consider environment-specific configurations
     *
     * @example
     * ```typescript
     * // Database plugin configuration
     * config: {
     *   connectionString: 'postgresql://user:pass@localhost:5432/db',
     *   poolSize: 10,
     *   timeout: 30000,
     *   retryAttempts: 3,
     *   enableSSL: true,
     *   migrationPath: './migrations',
     *   queryLogging: process.env.NODE_ENV === 'development'
     * }
     * ```
     *
     * @example
     * ```typescript
     * // API client configuration
     * config: {
     *   baseUrl: 'https://api.example.com',
     *   apiKey: process.env.API_KEY,
     *   timeout: 5000,
     *   retryConfig: {
     *     attempts: 3,
     *     delay: 1000,
     *     backoff: 'exponential'
     *   },
     *   headers: {
     *     'User-Agent': 'MyApp/1.0.0',
     *     'Accept': 'application/json'
     *   },
     *   rateLimiting: {
     *     requestsPerSecond: 10,
     *     burstSize: 20
     *   }
     * }
     * ```
     *
     * @example
     * ```typescript
     * // Processing pipeline configuration
     * config: {
     *   batchSize: 50,
     *   parallelProcessing: true,
     *   maxConcurrency: 5,
     *   processingRules: [
     *     { field: 'email', validation: 'email', required: true },
     *     { field: 'age', validation: 'number', min: 0, max: 120 },
     *     { field: 'country', validation: 'string', allowedValues: ['US', 'CA', 'UK'] }
     *   ],
     *   outputFormat: 'json',
     *   compressionEnabled: true,
     *   errorHandling: {
     *     strategy: 'continue',
     *     maxErrors: 10,
     *     logErrors: true
     *   }
     * }
     * ```
     *
     * @example
     * ```typescript
     * // Environment-aware configuration
     * config: {
     *   ...baseConfig,
     *   ...(process.env.NODE_ENV === 'production' ? {
     *     logLevel: 'warn',
     *     enableMetrics: true,
     *     cacheEnabled: true,
     *     performanceMode: 'optimized'
     *   } : {
     *     logLevel: 'debug',
     *     enableMetrics: false,
     *     cacheEnabled: false,
     *     performanceMode: 'development'
     *   })
     * }
     * ```
     */
    readonly config: Record<string, unknown>;
}

/*!
 * harmony-pipeline v1.0.1
 * A robust TypeScript pipeline execution library with stage-based processing, dependency resolution, and comprehensive error handling
 * 
 * Copyright (c) 2025 Khaled Sameer <khaled.smq@hotmail.com>
 * Licensed under MIT
 * 
 * Repository: https://github.com/KhaledSMQ/harmony-pipeline.git
 * 
 * Built: 2025-06-12T11:21:14.416Z
 */
/**
 * Logging interface for pipeline operations.
 * Provides structured logging capabilities with optional metadata attachment.
 */
interface Logger {
    /**
     * Log debug information for development and troubleshooting.
     * @param message - Human-readable debug message
     * @param data - Optional structured data for context
     */
    debug(message: string, data?: unknown): void;
    /**
     * Log informational messages about normal operations.
     * @param message - Human-readable information message
     * @param data - Optional structured data for context
     */
    info(message: string, data?: unknown): void;
    /**
     * Log warning messages for recoverable issues.
     * @param message - Human-readable warning message
     * @param data - Optional structured data for context
     */
    warn(message: string, data?: unknown): void;
    /**
     * Log error messages for critical issues.
     * @param message - Human-readable error message
     * @param data - Optional structured data for context
     */
    error(message: string, data?: unknown): void;
}

/**
 * Represents a non-fatal warning emitted during pipeline execution.
 * Warnings allow processors to report issues without stopping execution.
 */
interface PipelineWarning {
    /** Unique identifier for the warning type */
    readonly code: string;
    /** Human-readable description of the warning */
    readonly message: string;
    /** Optional structured data providing additional context */
    readonly details?: unknown;
    /** Timestamp when the warning was created (milliseconds since epoch) */
    readonly timestamp: number;
}
/**
 * Execution context shared across all processors in a pipeline run.
 * Provides access to metadata, logging, and warning collection.
 *
 * @template M - Shape of the metadata object for type safety
 */
interface PipelineContext<M extends Record<string, unknown> = Record<string, unknown>> {
    /** Unique identifier for this pipeline execution */
    readonly executionId: string;
    /** Timestamp when the pipeline execution started */
    readonly startTime: number;
    /** Immutable metadata available to all processors */
    readonly metadata: Readonly<M>;
    /** Logger instance bound to this pipeline execution */
    readonly logger: Logger;
    /**
     * Records a non-fatal warning without stopping execution.
     * The warning is logged and stored for inclusion in the final result.
     *
     * @param code - Unique identifier for the warning type
     * @param message - Human-readable description
     * @param details - Optional structured data for additional context
     */
    addWarning(code: string, message: string, details?: unknown): void;
    /**
     * @internal
     * Returns all warnings collected during execution.
     * This method is intended for internal use by the pipeline executor.
     */
    _getWarnings(): ReadonlyArray<PipelineWarning>;
}

/**
 * Represents a stage in the pipeline execution graph.
 * Stages form a Directed Acyclic Graph (DAG) where dependencies define execution order.
 * Each stage can contain multiple processors that execute within that stage.
 *
 * @template TCtx - Type of the pipeline context
 */
interface PipelineStage<TCtx extends PipelineContext = PipelineContext> {
    /** Unique name identifying this stage */
    readonly name: string;
    /**
     * Names of other stages that must complete before this stage can execute.
     * Used to build the execution DAG and ensure proper ordering.
     */
    readonly dependencies?: ReadonlyArray<string>;
    /**
     * Optional predicate to determine if this stage should execute.
     * When this function returns false, the stage is skipped entirely.
     * Useful for conditional execution based on context or metadata.
     *
     * @param context - The current pipeline execution context
     * @returns true if the stage should execute, false to skip
     */
    canExecute(context: TCtx): boolean;
}
/**
 * Configuration options for creating a pipeline stage.
 *
 * @template TCtx - Type of the pipeline context
 */
interface StageOptions<TCtx extends PipelineContext = PipelineContext> {
    /** Names of stages that must complete before this stage can run */
    dependencies?: ReadonlyArray<string>;
    /** Optional predicate to conditionally execute this stage */
    canExecute?(context: TCtx): boolean;
}
/**
 * Creates a new pipeline stage with the specified name and options.
 * This is a convenience function for creating stage objects without
 * implementing the interface directly.
 *
 * @template TCtx - Type of the pipeline context
 * @param name - Unique name for the stage
 * @param options - Configuration options for the stage
 * @returns A new pipeline stage instance
 *
 * @example
 * ```typescript
 * const validationStage = createStage('validation', {
 *   dependencies: ['preprocessing'],
 *   canExecute: (ctx) => ctx.metadata.enableValidation
 * });
 * ```
 */
declare function createStage<TCtx extends PipelineContext = PipelineContext>(name: string, options?: StageOptions<TCtx>): PipelineStage<TCtx>;

/**
 * A processor performs a single unit of work within a stage.
 */
interface PipelineProcessor<I = unknown, O = unknown, TCtx extends PipelineContext = PipelineContext> {
    readonly name: string;
    /** Semantic‑version for change tracking. */
    readonly version: `${number}.${number}.${number}`;
    readonly stage: PipelineStage<TCtx>;
    /** Unit of work. May be async. Honour the AbortSignal. */
    process(input: I, context: TCtx, signal?: AbortSignal): O | Promise<O>;
    setup?(context: TCtx): void | Promise<void>;
    teardown?(context: TCtx): void | Promise<void>;
    onError?(error: Error, context: TCtx): void | Promise<void>;
}

/**
 * Configuration options that control pipeline execution behavior.
 * These options provide fine-grained control over how the pipeline runs,
 * including error handling, concurrency, timeouts, and logging.
 */
interface ExecutionOptions {
    /**
     * Whether to stop pipeline execution immediately when any processor fails.
     * When true, the first error stops the entire pipeline.
     * When false, the pipeline continues executing remaining stages even after errors.
     *
     * @default true
     */
    readonly stopOnError?: boolean | undefined;
    /**
     * Maximum number of processors that can execute concurrently within a single stage.
     * Values greater than 1 only make sense when processors within a stage are independent.
     * Use with caution as concurrent execution may complicate error handling and debugging.
     *
     * @default 1
     */
    readonly concurrency?: number | undefined;
    /**
     * AbortSignal for externally cancelling the pipeline execution.
     * When the signal is aborted, the pipeline will stop processing and reject with an error.
     * This allows integration with user cancellation, request timeouts, etc.
     */
    readonly signal?: AbortSignal | undefined;
    /**
     * Maximum time in milliseconds the pipeline is allowed to run.
     * When exceeded, the pipeline execution is cancelled and rejects with a timeout error.
     * Set to undefined to disable timeout (pipeline runs until completion or error).
     *
     * @default undefined (no timeout)
     */
    readonly timeoutMs?: number | undefined;
    /**
     * Logger instance for recording pipeline execution events.
     * The logger receives debug, info, warning, and error messages throughout execution.
     * Use NullLogger to disable logging entirely.
     *
     * @default undefined (uses NullLogger internally)
     */
    readonly logger?: Logger | undefined;
}

/**
 * Plugin Context Type Definitions
 *
 * The PluginContext extends the base pipeline context with plugin-specific features
 * for managing execution state, shared data, and plugin settings. It serves as the
 * primary communication interface between the plugin system and individual plugins.
 *
 * ## Key Concepts
 *
 * - **Execution Context**: Provides execution metadata, timing, and unique identification
 * - **Shared State**: Enables secure data sharing between plugins in the same execution
 * - **Settings Access**: Gives plugins access to their configuration and other plugin settings
 * - **Logging Integration**: Provides structured logging with execution context
 * - **Warning Management**: Allows plugins to add non-fatal warnings to execution results
 *
 * ## Context Lifecycle
 *
 * 1. **Creation**: Context is created for each execution with fresh state
 * 2. **Initialization**: Plugins can share initial data during setup
 * 3. **Execution**: Plugins access settings, log events, and share data
 * 4. **Cleanup**: Context is disposed after execution completes
 *
 * ## Usage Examples
 *
 * ### Basic Context Usage
 * ```typescript
 * async execute(input: UserData, context: PluginContext): Promise<ProcessedUser> {
 *   // Access plugin settings
 *   const settings = context.getSettings(this.metadata.name);
 *   const apiUrl = settings?.config.apiUrl as string;
 *
 *   // Log with context
 *   context.logger.info(`Processing user: ${input.id}`, {
 *     executionId: context.executionId,
 *     startTime: context.startTime
 *   });
 *
 *   // Process data
 *   const result = await processUser(input, apiUrl);
 *
 *   // Share results for other plugins
 *   context.share(`processed-user-${input.id}`, result);
 *
 *   return result;
 * }
 * ```
 *
 * ### Advanced Shared State Management
 * ```typescript
 * async execute(input: BatchData, context: PluginContext): Promise<BatchResult> {
 *   // Check if database connection exists from previous plugin
 *   let db = context.retrieve<Database>('database-connection');
 *
 *   if (!db) {
 *     // Create and share connection for other plugins
 *     db = await createDatabaseConnection();
 *     context.share('database-connection', db);
 *     context.logger.info('Database connection created and shared');
 *   }
 *
 *   // Access shared cache from caching plugin
 *   const cache = context.retrieve<Map<string, any>>('shared-cache');
 *
 *   // Process with shared resources
 *   const results = await processBatch(input, db, cache);
 *
 *   // Update shared statistics
 *   const stats = context.retrieve<ProcessingStats>('batch-stats') || {
 *     totalProcessed: 0,
 *     totalErrors: 0
 *   };
 *   stats.totalProcessed += results.length;
 *   context.share('batch-stats', stats);
 *
 *   return results;
 * }
 * ```
 *
 * ### Cross-Plugin Communication
 * ```typescript
 * // Plugin A - Data Collector
 * async execute(input: CollectionRequest, context: PluginContext): Promise<CollectedData> {
 *   const data = await collectData(input);
 *
 *   // Share collected data for downstream plugins
 *   context.share('collected-data', data);
 *   context.share('collection-metadata', {
 *     timestamp: Date.now(),
 *     source: input.source,
 *     recordCount: data.length
 *   });
 *
 *   return data;
 * }
 *
 * // Plugin B - Data Processor (depends on Plugin A)
 * async execute(input: CollectedData, context: PluginContext): Promise<ProcessedData> {
 *   // Retrieve metadata from previous plugin
 *   const metadata = context.retrieve<CollectionMetadata>('collection-metadata');
 *
 *   if (!metadata) {
 *     context.addWarning('MISSING_METADATA', 'Collection metadata not available');
 *   }
 *
 *   // Process with context awareness
 *   const processed = await processData(input, {
 *     timestamp: metadata?.timestamp,
 *     optimizeFor: metadata?.recordCount > 1000 ? 'batch' : 'single'
 *   });
 *
 *   return processed;
 * }
 * ```
 */

/**
 * Plugin execution context with shared state and settings access
 *
 * The PluginContext provides plugins with everything they need for execution:
 * access to configuration, logging facilities, shared state management, and
 * execution metadata. It ensures type safety while providing flexibility
 * for complex plugin interactions.
 *
 * @template T - Type of execution metadata provided by the caller
 *
 * @example
 * ```typescript
 * // Basic plugin with context usage
 * class UserValidatorPlugin extends BasePlugin<UserData, ValidatedUser> {
 *   async execute(input: UserData, context: PluginContext): Promise<ValidatedUser> {
 *     // Access plugin-specific settings
 *     const settings = context.getSettings(this.metadata.name);
 *     const strictMode = settings?.config.strictMode as boolean;
 *
 *     // Log with execution context
 *     context.logger.info(`Validating user: ${input.id}`, {
 *       executionId: context.executionId,
 *       strictMode
 *     });
 *
 *     // Validate based on settings
 *     const result = await validateUser(input, { strict: strictMode });
 *
 *     // Share validation results for other plugins
 *     context.share(`validation-result-${input.id}`, {
 *       isValid: result.isValid,
 *       errors: result.errors,
 *       timestamp: Date.now()
 *     });
 *
 *     if (!result.isValid && strictMode) {
 *       throw new Error(`Strict validation failed: ${result.errors.join(', ')}`);
 *     }
 *
 *     return result.user;
 *   }
 * }
 * ```
 *
 * @example
 * ```typescript
 * // Advanced context usage with metadata typing
 * interface ApiExecutionMetadata {
 *   requestId: string;
 *   userId: string;
 *   clientIp: string;
 *   userAgent: string;
 * }
 *
 * class ApiRateLimiterPlugin extends BasePlugin<ApiRequest, ApiRequest, PluginContext<ApiExecutionMetadata>> {
 *   async execute(input: ApiRequest, context: PluginContext<ApiExecutionMetadata>): Promise<ApiRequest> {
 *     // Access typed execution metadata
 *     const { requestId, userId, clientIp } = context.metadata;
 *
 *     // Check rate limits using shared state
 *     const rateLimiter = context.retrieve<RateLimiter>('rate-limiter') || new RateLimiter();
 *
 *     const isAllowed = await rateLimiter.checkLimit(userId, clientIp);
 *
 *     if (!isAllowed) {
 *       context.addWarning('RATE_LIMIT_EXCEEDED',
 *         `Rate limit exceeded for user ${userId}`, {
 *         requestId,
 *         clientIp,
 *         userId
 *       });
 *       throw new Error('Rate limit exceeded');
 *     }
 *
 *     // Update shared rate limiter state
 *     context.share('rate-limiter', rateLimiter);
 *
 *     return input;
 *   }
 * }
 * ```
 */
interface PluginContext<T extends Record<string, unknown> = Record<string, unknown>> extends PipelineContext<T> {
    /**
     * Read-only access to all plugin settings by name
     *
     * Provides access to the configuration settings for all registered plugins
     * in the current manager. This allows plugins to access not only their own
     * settings but also coordinate with other plugins based on their configuration.
     *
     * **Security Note**: Settings are read-only to prevent plugins from modifying
     * each other's configuration during execution.
     *
     * @example
     * ```typescript
     * async execute(input: Data, context: PluginContext): Promise<ProcessedData> {
     *   // Access own settings
     *   const mySettings = context.settings.get(this.metadata.name);
     *   const timeout = mySettings?.config.timeout as number || 5000;
     *
     *   // Check if caching plugin is enabled
     *   const cacheSettings = context.settings.get('cache-plugin');
     *   const isCacheEnabled = cacheSettings?.enabled || false;
     *
     *   // Coordinate behavior based on other plugin settings
     *   if (isCacheEnabled) {
     *     const cacheKey = `processed:${input.id}`;
     *     const cached = context.retrieve(cacheKey);
     *     if (cached) return cached;
     *   }
     *
     *   const result = await processData(input, { timeout });
     *
     *   if (isCacheEnabled) {
     *     context.share(`processed:${input.id}`, result);
     *   }
     *
     *   return result;
     * }
     * ```
     */
    readonly settings: ReadonlyMap<string, PluginSettings>;
    /**
     * Shared state map for inter-plugin communication
     *
     * Provides a secure mechanism for plugins to share data within a single
     * execution context. The shared state is isolated per execution and
     * automatically cleaned up when execution completes.
     *
     * **Use Cases**:
     * - Database connections and resources
     * - Cached computation results
     * - Processing statistics and metrics
     * - Configuration derived from multiple plugins
     * - Cross-plugin coordination data
     *
     * **Best Practices**:
     * - Use descriptive keys with plugin namespacing
     * - Store only serializable data when possible
     * - Clean up large objects in plugin cleanup hooks
     * - Use typed retrieval for better type safety
     *
     * @example
     * ```typescript
     * // Database plugin shares connection
     * async initialize(context: PluginContext): Promise<void> {
     *   const db = await createDatabaseConnection();
     *   context.shared.set('database-connection', db);
     *   context.shared.set('connection-pool-stats', {
     *     activeConnections: 1,
     *     maxConnections: 10,
     *     createdAt: Date.now()
     *   });
     * }
     *
     * // Another plugin uses shared connection
     * async execute(input: UserData, context: PluginContext): Promise<SavedUser> {
     *   const db = context.shared.get('database-connection') as Database;
     *   if (!db) {
     *     throw new Error('Database connection not available');
     *   }
     *
     *   const result = await db.users.save(input);
     *
     *   // Update shared statistics
     *   const stats = context.shared.get('connection-pool-stats') as any;
     *   stats.totalQueries = (stats.totalQueries || 0) + 1;
     *
     *   return result;
     * }
     * ```
     */
    readonly shared: Map<string, unknown>;
    /**
     * Retrieves settings for a specific plugin
     *
     * Convenient method to access plugin settings with proper typing and
     * null safety. Preferred over direct settings map access for better
     * error handling and debugging.
     *
     * @param pluginName - Name of plugin to get settings for
     * @returns Plugin settings or undefined if plugin not found or has no settings
     *
     * @example
     * ```typescript
     * async execute(input: ApiRequest, context: PluginContext): Promise<ApiResponse> {
     *   // Get own settings with error handling
     *   const settings = context.getSettings(this.metadata.name);
     *   if (!settings) {
     *     throw new Error(`No settings found for plugin: ${this.metadata.name}`);
     *   }
     *
     *   // Extract typed configuration
     *   const config = settings.config as {
     *     apiUrl: string;
     *     timeout: number;
     *     retryAttempts: number;
     *   };
     *
     *   // Check dependencies' settings for coordination
     *   const authSettings = context.getSettings('auth-plugin');
     *   const requiresAuth = authSettings?.enabled && authSettings?.config.enforceAuth;
     *
     *   // Adjust behavior based on settings
     *   if (requiresAuth) {
     *     const token = context.retrieve<string>('auth-token');
     *     if (!token) {
     *       throw new Error('Authentication required but no token available');
     *     }
     *   }
     *
     *   return await this.callApi(input, config);
     * }
     * ```
     *
     * @example
     * ```typescript
     * // Settings-driven feature flags
     * async execute(input: UserData, context: PluginContext): Promise<ProcessedUser> {
     *   const settings = context.getSettings(this.metadata.name);
     *   const features = settings?.config.enabledFeatures as string[] || [];
     *
     *   let result = { ...input };
     *
     *   // Conditional processing based on settings
     *   if (features.includes('email-validation')) {
     *     result = await this.validateEmail(result, context);
     *   }
     *
     *   if (features.includes('data-enrichment')) {
     *     const enrichmentSettings = context.getSettings('enrichment-plugin');
     *     if (enrichmentSettings?.enabled) {
     *       result = await this.enrichUserData(result, context);
     *     }
     *   }
     *
     *   if (features.includes('audit-logging')) {
     *     const auditData = {
     *       userId: input.id,
     *       action: 'user-processing',
     *       timestamp: Date.now(),
     *       features: features
     *     };
     *     context.share('audit-log', auditData);
     *   }
     *
     *   return result;
     * }
     * ```
     */
    getSettings(pluginName: string): PluginSettings | undefined;
    /**
     * Stores a value in shared state for other plugins to access
     *
     * Provides type-safe storage of data that needs to be shared between
     * plugins during execution. The shared state is scoped to the current
     * execution and is automatically cleaned up afterward.
     *
     * @template V - Type of value being stored
     * @param key - Unique key for the value (consider using plugin namespaces)
     * @param value - Value to store in shared state
     *
     * @example
     * ```typescript
     * // Authentication plugin shares token
     * async execute(input: LoginRequest, context: PluginContext): Promise<AuthResult> {
     *   const authResult = await authenticate(input);
     *
     *   if (authResult.success) {
     *     // Share authentication data for downstream plugins
     *     context.share('auth-token', authResult.token);
     *     context.share('user-permissions', authResult.permissions);
     *     context.share('session-data', {
     *       userId: authResult.userId,
     *       sessionId: authResult.sessionId,
     *       expiresAt: authResult.expiresAt
     *     });
     *
     *     context.logger.info(`User authenticated: ${authResult.userId}`);
     *   }
     *
     *   return authResult;
     * }
     * ```
     *
     * @example
     * ```typescript
     * // Data processing plugin shares intermediate results
     * async execute(input: RawData[], context: PluginContext): Promise<ProcessedData[]> {
     *   const startTime = Date.now();
     *
     *   // Process data and track statistics
     *   const results: ProcessedData[] = [];
     *   const errors: ProcessingError[] = [];
     *
     *   for (const item of input) {
     *     try {
     *       const processed = await this.processItem(item);
     *       results.push(processed);
     *     } catch (error) {
     *       errors.push({ item: item.id, error: error.message });
     *     }
     *   }
     *
     *   // Share processing statistics
     *   const stats = {
     *     totalItems: input.length,
     *     successfulItems: results.length,
     *     failedItems: errors.length,
     *     processingTime: Date.now() - startTime,
     *     throughputPerSecond: results.length / ((Date.now() - startTime) / 1000)
     *   };
     *
     *   context.share('processing-stats', stats);
     *   context.share('processing-errors', errors);
     *
     *   // Share for audit/monitoring plugins
     *   context.share(`${this.metadata.name}-execution-summary`, {
     *     plugin: this.metadata.name,
     *     version: this.metadata.version,
     *     executedAt: new Date().toISOString(),
     *     stats
     *   });
     *
     *   return results;
     * }
     * ```
     *
     * @example
     * ```typescript
     * // Cache plugin shares cached data
     * async execute(input: CacheableData, context: PluginContext): Promise<CacheableData> {
     *   const cacheKey = this.generateCacheKey(input);
     *
     *   // Try to get from shared cache first
     *   const cache = context.retrieve<Map<string, any>>('global-cache') || new Map();
     *
     *   if (cache.has(cacheKey)) {
     *     context.logger.debug(`Cache hit for key: ${cacheKey}`);
     *     return cache.get(cacheKey);
     *   }
     *
     *   // Process and cache result
     *   const result = await this.processData(input);
     *   cache.set(cacheKey, result);
     *
     *   // Update shared cache
     *   context.share('global-cache', cache);
     *
     *   // Share cache statistics
     *   const cacheStats = context.retrieve<any>('cache-stats') || { hits: 0, misses: 0 };
     *   cacheStats.misses++;
     *   context.share('cache-stats', cacheStats);
     *
     *   context.logger.debug(`Cache miss for key: ${cacheKey}, cached result`);
     *
     *   return result;
     * }
     * ```
     */
    share<V>(key: string, value: V): void;
    /**
     * Retrieves a value from shared state
     *
     * Provides type-safe retrieval of shared data with proper null handling.
     * The generic type parameter helps maintain type safety throughout the
     * plugin system.
     *
     * @template V - Expected type of the retrieved value
     * @param key - Key of value to retrieve from shared state
     * @returns Retrieved value with proper typing, or undefined if not found
     *
     * @example
     * ```typescript
     * // Authorization plugin uses authentication data
     * async execute(input: AuthorizedRequest, context: PluginContext): Promise<AuthorizedRequest> {
     *   // Retrieve authentication data with type safety
     *   const token = context.retrieve<string>('auth-token');
     *   const permissions = context.retrieve<string[]>('user-permissions');
     *   const sessionData = context.retrieve<SessionData>('session-data');
     *
     *   if (!token || !permissions) {
     *     throw new Error('Authentication required for authorization');
     *   }
     *
     *   // Check permissions for the requested resource
     *   const requiredPermission = input.resource;
     *   if (!permissions.includes(requiredPermission)) {
     *     context.addWarning('INSUFFICIENT_PERMISSIONS',
     *       `User lacks permission: ${requiredPermission}`, {
     *       userId: sessionData?.userId,
     *       requiredPermission,
     *       userPermissions: permissions
     *     });
     *     throw new Error('Insufficient permissions');
     *   }
     *
     *   // Add authorization context to request
     *   return {
     *     ...input,
     *     authContext: {
     *       token,
     *       permissions,
     *       sessionId: sessionData?.sessionId
     *     }
     *   };
     * }
     * ```
     *
     * @example
     * ```typescript
     * // Monitoring plugin aggregates data from multiple sources
     * async execute(input: MonitoringData, context: PluginContext): Promise<MonitoringReport> {
     *   // Retrieve data from various plugins
     *   const processingStats = context.retrieve<ProcessingStats>('processing-stats');
     *   const cacheStats = context.retrieve<CacheStats>('cache-stats');
     *   const authStats = context.retrieve<AuthStats>('auth-stats');
     *   const errorData = context.retrieve<ProcessingError[]>('processing-errors') || [];
     *
     *   // Aggregate performance metrics
     *   const performanceMetrics = {
     *     totalExecutionTime: context.startTime ? Date.now() - context.startTime : 0,
     *     throughput: processingStats?.throughputPerSecond || 0,
     *     cacheHitRate: cacheStats ? (cacheStats.hits / (cacheStats.hits + cacheStats.misses)) : 0,
     *     errorRate: processingStats ? (errorData.length / processingStats.totalItems) : 0
     *   };
     *
     *   // Create comprehensive monitoring report
     *   const report: MonitoringReport = {
     *     executionId: context.executionId,
     *     timestamp: new Date().toISOString(),
     *     performance: performanceMetrics,
     *     processing: processingStats,
     *     caching: cacheStats,
     *     authentication: authStats,
     *     errors: errorData,
     *     summary: {
     *       status: errorData.length === 0 ? 'success' : 'partial_failure',
     *       totalWarnings: context._getWarnings().length,
     *       executionTimeMs: performanceMetrics.totalExecutionTime
     *     }
     *   };
     *
     *   // Share final report for potential audit plugins
     *   context.share('monitoring-report', report);
     *
     *   return report;
     * }
     * ```
     *
     * @example
     * ```typescript
     * // Database plugin retrieves connection pool info
     * async execute(input: DatabaseQuery, context: PluginContext): Promise<QueryResult> {
     *   // Try to get existing database connection
     *   let db = context.retrieve<Database>('database-connection');
     *
     *   if (!db) {
     *     // No existing connection, create new one
     *     db = await this.createConnection();
     *     context.share('database-connection', db);
     *     context.logger.info('Created new database connection');
     *   }
     *
     *   // Get connection pool statistics if available
     *   const poolStats = context.retrieve<ConnectionPoolStats>('connection-pool-stats');
     *   if (poolStats && poolStats.activeConnections > poolStats.maxConnections * 0.8) {
     *     context.addWarning('HIGH_CONNECTION_USAGE',
     *       'Connection pool usage is high', {
     *       activeConnections: poolStats.activeConnections,
     *       maxConnections: poolStats.maxConnections,
     *       utilizationPercentage: (poolStats.activeConnections / poolStats.maxConnections) * 100
     *     });
     *   }
     *
     *   // Execute query with connection
     *   const result = await db.query(input.sql, input.parameters);
     *
     *   // Update query statistics
     *   const queryStats = context.retrieve<QueryStats>('query-stats') || {
     *     totalQueries: 0,
     *     totalExecutionTime: 0
     *   };
     *   queryStats.totalQueries++;
     *   queryStats.totalExecutionTime += result.executionTime;
     *   context.share('query-stats', queryStats);
     *
     *   return result;
     * }
     * ```
     */
    retrieve<V>(key: string): V | undefined;
}

/**
 * Result Type Definitions for plugin execution outcomes
 *
 * Provides structured result types for:
 * - Individual plugin execution results
 * - Manager-level execution results
 * - Success/failure state tracking
 * - Performance metrics and warnings
 */
/**
 * Result of a single plugin execution
 * Contains success state, output data, timing, and diagnostics
 */
interface PluginResult<T = unknown> {
    /** Name of the plugin that produced this result */
    readonly pluginName: string;
    /** Whether the plugin executed successfully */
    readonly success: boolean;
    /** Output data from successful execution (undefined if failed) */
    readonly output?: T;
    /** Error information from failed execution (undefined if successful) */
    readonly error?: Error;
    /** Execution duration in milliseconds */
    readonly duration: number;
    /** Non-fatal warnings generated during execution */
    readonly warnings: readonly string[];
}
/**
 * Overall result of plugin manager execution
 * Aggregates individual plugin results with manager-level metrics
 */
interface ManagerResult<T = unknown> {
    /** Whether the overall execution was successful */
    readonly success: boolean;
    /** Results from individual plugin executions */
    readonly results: readonly PluginResult<T>[];
    /** Total execution duration in milliseconds */
    readonly duration: number;
    /** Fatal errors that stopped execution */
    readonly errors: readonly Error[];
    /** Non-fatal warnings from plugins and manager */
    readonly warnings: readonly string[];
}

/**
 * Plugin Interface - Core contract for all plugins
 *
 * Defines the essential plugin contract:
 * - Plugin metadata for identification and dependencies
 * - Main execution method for processing data
 * - Lifecycle hooks for initialization and cleanup
 * - Error handling for robust execution
 */

interface IPlugin<TInput = unknown, TOutput = unknown, TContext extends PluginContext = PluginContext> {
    /**
     * Plugin metadata including name, version, dependencies, and tags
     * Used for identification, dependency resolution, and documentation
     */
    readonly metadata: PluginMetadata;
    /**
     * Main plugin execution method
     * Processes input data and returns transformed output
     *
     * @param input - Input data to process
     * @param context - Execution context with logging, settings, and shared state
     * @returns Processed output data (sync or async)
     */
    execute(input: TInput, context: TContext): Promise<TOutput> | TOutput;
    /**
     * Plugin initialization hook
     * Called once before any execution begins
     * Use for setup, configuration validation, resource allocation
     *
     * @param context - Execution context for logging and configuration access
     */
    initialize(context: TContext): Promise<void> | void;
    /**
     * Plugin cleanup hook
     * Called after execution completes (success or failure)
     * Use for resource cleanup, connection closing, temporary file removal
     *
     * @param context - Execution context for logging
     */
    cleanup(context: TContext): Promise<void> | void;
    /**
     * Error handling hook
     * Called when plugin execution throws an error
     * Use for error logging, cleanup, or recovery attempts
     *
     * @param error - Error that occurred during execution
     * @param context - Execution context for logging and state access
     */
    onError(error: Error, context: TContext): Promise<void> | void;
}

/**
 * Plugin Manager Interface - Contract for plugin orchestration
 *
 * Defines the public API for plugin managers:
 * - Plugin registration and configuration
 * - Manager lifecycle (build/execute)
 * - Plugin query and inspection methods
 * - Type-safe execution with results
 */

interface IPluginManager<TInput = unknown, TOutput = unknown, TMetadata extends Record<string, unknown> = Record<string, unknown>> {
    /**
     * Registers a plugin with optional settings
     * Must be called before build()
     *
     * @param plugin - Plugin instance to register
     * @param settings - Optional plugin configuration
     * @returns Manager instance for method chaining
     */
    register(plugin: IPlugin, settings?: Partial<PluginSettings>): this;
    /**
     * Removes a plugin from the manager
     * Must be called before build()
     *
     * @param pluginName - Name of plugin to remove
     * @returns Manager instance for method chaining
     */
    unregister(pluginName: string): this;
    /**
     * Updates configuration for an existing plugin
     * Must be called before build()
     *
     * @param pluginName - Name of plugin to configure
     * @param settings - Partial settings to merge
     * @returns Manager instance for method chaining
     */
    configure(pluginName: string, settings: Partial<PluginSettings>): this;
    /**
     * Checks if a plugin is registered
     *
     * @param name - Plugin name to check
     * @returns True if plugin is registered
     */
    hasPlugin(name: string): boolean;
    /**
     * Gets all registered plugin names
     *
     * @returns Array of plugin names
     */
    getPluginNames(): readonly string[];
    /**
     * Builds the manager for execution
     * Validates dependencies and constructs execution pipeline
     * Must be called before execute()
     *
     * @returns Manager instance for method chaining
     */
    build(): this;
    /**
     * Executes all registered plugins in dependency order
     * Manager must be built before calling this method
     *
     * @param input - Input data to process
     * @param metadata - Execution metadata for context
     * @param options - Optional execution configuration
     * @returns Promise resolving to execution results
     */
    execute(input: TInput, metadata: TMetadata, options?: ExecutionOptions): Promise<ManagerResult<TOutput>>;
}

/**
 * Plugin Registration wrapper for managing plugin metadata and settings
 *
 * Encapsulates:
 * - Plugin instance with its metadata
 * - Runtime settings (enabled state, priority, configuration)
 * - Registration timestamp for audit purposes
 * - Convenience methods for accessing plugin properties
 */

/**
 * Represents a registered plugin with its associated settings and metadata
 * Provides immutable access to plugin information and settings management
 */
declare class PluginRegistration<TPlugin extends IPlugin = IPlugin> {
    readonly plugin: TPlugin;
    readonly settings: PluginSettings;
    readonly registeredAt: number;
    constructor(plugin: TPlugin, settings: PluginSettings, registeredAt?: number);
    /** Plugin name from metadata */
    get name(): string;
    /** Current enabled state from settings */
    get isEnabled(): boolean;
    /** Execution priority from settings */
    get priority(): number;
    /** Plugin dependencies from metadata */
    get dependencies(): readonly string[] | undefined;
    /** Plugin version from metadata */
    get version(): string;
    /** Plugin description from metadata */
    get description(): string | undefined;
    /** Plugin tags from metadata */
    get tags(): readonly string[];
    /**
     * Creates a new registration with updated settings
     * Maintains immutability by returning a new instance
     *
     * @param settings - Partial settings to merge with current settings
     * @returns New registration instance with updated settings
     */
    withSettings(settings: Partial<PluginSettings>): PluginRegistration<TPlugin>;
    /**
     * Checks if plugin version is compatible with required version
     * Currently performs exact version matching - can be enhanced for semver ranges
     *
     * @param requiredVersion - Version requirement to check against
     * @returns True if versions are compatible
     */
    isCompatibleWith(requiredVersion: string): boolean;
}

/**
 * Plugin Manager - Core orchestration and execution engine
 *
 * The PluginManager is the central component that orchestrates plugin execution.
 * It handles the complete plugin lifecycle from registration through execution,
 * including dependency resolution, error handling, and result aggregation.
 *
 * ## Key Features
 *
 * - **Type-safe plugin registration** with compile-time validation
 * - **Automatic dependency resolution** with cycle detection
 * - **Isolated execution contexts** with shared state management
 * - **Comprehensive error handling** with graceful degradation
 * - **Performance monitoring** with detailed execution metrics
 * - **Flexible configuration** with priority-based ordering
 *
 * ## Usage Patterns
 *
 * ### Basic Usage
 * ```typescript
 * const manager = new PluginManager<string, string>()
 *   .register(validationPlugin)
 *   .register(transformPlugin)
 *   .build();
 *
 * const result = await manager.execute('input', { requestId: '123' });
 * ```
 *
 * ### Advanced Configuration
 * ```typescript
 * const manager = new PluginManager<ApiRequest, ApiResponse>()
 *   .register(authPlugin, { priority: 100, enabled: true })
 *   .register(rateLimitPlugin, { priority: 90 })
 *   .register(validationPlugin, { priority: 80 })
 *   .register(businessLogicPlugin, { priority: 50 })
 *   .register(responseFormatterPlugin, { priority: 10 })
 *   .build();
 * ```
 */

declare class PluginManager<TInput = unknown, TOutput = unknown, TMetadata extends Record<string, unknown> = Record<string, unknown>> implements IPluginManager<TInput, TOutput, TMetadata> {
    private readonly registrations;
    private pipeline?;
    private built;
    /**
     * Registers a plugin with the manager
     *
     * Plugin registration is the process of adding a plugin to the manager's
     * execution pipeline. Each plugin must have a unique name and will be
     * executed according to its dependencies and priority settings.
     *
     * **Important**: Plugin registration can only be done before calling build().
     * Once the manager is built, the plugin configuration is frozen.
     *
     * @param plugin - The plugin instance to register
     * @param settings - Optional configuration for the plugin's execution behavior
     *
     * @returns The manager instance for method chaining
     *
     * @throws {Error} When plugin name conflicts with existing plugin
     * @throws {Error} When manager is already built
     *
     * @example
     * ```typescript
     * // Basic plugin registration
     * const manager = new PluginManager<string, string>()
     *   .register(uppercasePlugin)
     *   .register(trimPlugin);
     * ```
     *
     * @example
     * ```typescript
     * // Registration with custom settings
     * const manager = new PluginManager<UserData, ProcessedUser>()
     *   .register(validationPlugin, {
     *     enabled: true,
     *     priority: 100,           // Execute first (highest priority)
     *     config: {
     *       strictMode: true,
     *       requiredFields: ['id', 'email', 'name']
     *     }
     *   })
     *   .register(enrichmentPlugin, {
     *     priority: 50,            // Execute after validation
     *     config: {
     *       includePreferences: true,
     *       loadAvatars: false
     *     }
     *   })
     *   .register(debugPlugin, {
     *     enabled: process.env.NODE_ENV === 'development'
     *   });
     * ```
     *
     * @example
     * ```typescript
     * // Registration with dependency handling
     * const manager = new PluginManager<ApiRequest, ApiResponse>()
     *   // Core plugins that others depend on
     *   .register(authenticationPlugin, { priority: 100 })
     *   .register(authorizationPlugin, { priority: 90 })
     *
     *   // Business logic plugins (depend on auth)
     *   .register(userServicePlugin, { priority: 50 })
     *   .register(notificationPlugin, { priority: 40 })
     *
     *   // Response plugins (depend on business logic)
     *   .register(responseFormatterPlugin, { priority: 10 })
     *   .register(compressionPlugin, { priority: 5 });
     * ```
     */
    register(plugin: IPlugin<TInput, TOutput, PluginContext<TMetadata>>, settings?: Partial<PluginSettings>): this;
    /**
     * Removes a plugin from the manager
     *
     * Unregistration removes a previously registered plugin from the manager.
     * This is useful for dynamic plugin management or removing plugins based
     * on runtime conditions.
     *
     * **Important**: Can only be called before build().
     *
     * @param pluginName - Name of the plugin to remove
     *
     * @returns The manager instance for method chaining
     *
     * @throws {Error} When manager is already built
     *
     * @example
     * ```typescript
     * const manager = new PluginManager<string, string>()
     *   .register(pluginA)
     *   .register(pluginB)
     *   .register(debugPlugin);
     *
     * // Remove debug plugin in production
     * if (process.env.NODE_ENV === 'production') {
     *   manager.unregister('debug-plugin');
     * }
     *
     * manager.build();
     * ```
     *
     * @example
     * ```typescript
     * // Conditional plugin removal based on configuration
     * const manager = new PluginManager<UserData, ProcessedUser>()
     *   .register(corePlugin)
     *   .register(analyticsPlugin)
     *   .register(trackingPlugin);
     *
     * // Remove tracking plugins if privacy mode is enabled
     * const config = await loadConfiguration();
     * if (config.privacyMode) {
     *   manager
     *     .unregister('analytics-plugin')
     *     .unregister('tracking-plugin');
     * }
     * ```
     */
    unregister(pluginName: string): this;
    /**
     * Updates configuration for an existing plugin
     *
     * Configuration allows you to modify plugin settings after registration
     * but before building. This is useful for dynamic configuration based on
     * environment variables, user preferences, or runtime conditions.
     *
     * **Important**: Can only be called before build().
     *
     * @param pluginName - Name of the plugin to configure
     * @param settings - Partial settings to merge with existing configuration
     *
     * @returns The manager instance for method chaining
     *
     * @throws {Error} When plugin is not found
     * @throws {Error} When manager is already built
     *
     * @example
     * ```typescript
     * const manager = new PluginManager<UserData, ProcessedUser>()
     *   .register(databasePlugin)
     *   .register(cachePlugin);
     *
     * // Configure database plugin based on environment
     * const dbConfig = process.env.NODE_ENV === 'production'
     *   ? { connectionPool: 20, timeout: 5000 }
     *   : { connectionPool: 5, timeout: 10000 };
     *
     * manager.configure('database-plugin', {
     *   config: dbConfig
     * });
     *
     * // Disable caching in development
     * if (process.env.NODE_ENV === 'development') {
     *   manager.configure('cache-plugin', { enabled: false });
     * }
     * ```
     *
     * @example
     * ```typescript
     * // Runtime configuration based on user settings
     * const userPreferences = await loadUserPreferences(userId);
     *
     * const manager = new PluginManager<UserContent, ProcessedContent>()
     *   .register(contentFilterPlugin)
     *   .register(personalizationPlugin)
     *   .register(recommendationPlugin);
     *
     * // Configure plugins based on user preferences
     * manager
     *   .configure('content-filter', {
     *     config: {
     *       contentRating: userPreferences.maxContentRating,
     *       hideExplicit: userPreferences.hideExplicitContent
     *     }
     *   })
     *   .configure('personalization', {
     *     enabled: userPreferences.enablePersonalization,
     *     config: {
     *       interests: userPreferences.interests,
     *       learningEnabled: userPreferences.adaptiveLearning
     *     }
     *   });
     * ```
     */
    configure(pluginName: string, settings: Partial<PluginSettings>): this;
    /**
     * Retrieves plugin registration information by name
     *
     * @param name - Name of the plugin to retrieve
     * @returns Plugin registration or undefined if not found
     *
     * @example
     * ```typescript
     * const registration = manager.getPlugin('validation-plugin');
     * if (registration) {
     *   console.log(`Plugin version: ${registration.version}`);
     *   console.log(`Is enabled: ${registration.isEnabled}`);
     *   console.log(`Dependencies: ${registration.dependencies}`);
     * }
     * ```
     */
    getPlugin(name: string): PluginRegistration | undefined;
    /**
     * Gets all registered plugin names
     *
     * @returns Array of all registered plugin names
     *
     * @example
     * ```typescript
     * const pluginNames = manager.getPluginNames();
     * console.log(`Registered plugins: ${pluginNames.join(', ')}`);
     * ```
     */
    getPluginNames(): readonly string[];
    /**
     * Checks if a plugin is registered
     *
     * @param name - Plugin name to check
     * @returns True if plugin is registered
     *
     * @example
     * ```typescript
     * if (manager.hasPlugin('optional-feature')) {
     *   console.log('Optional feature is available');
     * }
     * ```
     */
    hasPlugin(name: string): boolean;
    /**
     * Gets all enabled plugin registrations
     *
     * @returns Array of enabled plugin registrations
     *
     * @example
     * ```typescript
     * const enabledPlugins = manager.getEnabledPlugins();
     * console.log(`${enabledPlugins.length} plugins will execute`);
     * ```
     */
    getEnabledPlugins(): readonly PluginRegistration[];
    /**
     * Gets plugins filtered by tag
     *
     * @param tag - Tag to filter by
     * @returns Array of plugin registrations with the specified tag
     *
     * @example
     * ```typescript
     * const validationPlugins = manager.getPluginsByTag('validation');
     * const performancePlugins = manager.getPluginsByTag('performance');
     * ```
     */
    getPluginsByTag(tag: string): readonly PluginRegistration[];
    /**
     * Builds the plugin manager for execution
     *
     * Building is the process of finalizing the plugin configuration and constructing
     * the execution pipeline. During this phase, the manager:
     *
     * 1. **Validates all plugin dependencies** - ensures all required plugins are registered
     * 2. **Resolves execution order** - performs topological sort based on dependencies
     * 3. **Detects circular dependencies** - prevents infinite dependency loops
     * 4. **Constructs execution pipeline** - creates optimized execution chain
     * 5. **Freezes configuration** - prevents further plugin modifications
     *
     * **Important**: After calling build(), no further plugin registration or
     * configuration changes are allowed. The manager is ready for execution.
     *
     * @returns The manager instance for method chaining
     *
     * @throws {Error} When dependencies are invalid or circular
     * @throws {Error} When pipeline construction fails
     * @throws {Error} When manager is already built
     *
     * @example
     * ```typescript
     * // Basic build process
     * const manager = new PluginManager<string, string>()
     *   .register(validationPlugin)
     *   .register(transformPlugin)
     *   .register(outputPlugin)
     *   .build(); // Manager is now ready for execution
     *
     * // Can now execute, but cannot register more plugins
     * const result = await manager.execute('input', {});
     * ```
     *
     * @example
     * ```typescript
     * // Build with error handling
     * try {
     *   const manager = new PluginManager<ApiRequest, ApiResponse>()
     *     .register(authPlugin)
     *     .register(businessLogicPlugin, {
     *       dependencies: ['auth-plugin']
     *     })
     *     .register(responsePlugin, {
     *       dependencies: ['business-logic-plugin']
     *     })
     *     .build();
     *
     *   console.log('Manager built successfully');
     *   console.log(`Execution order: ${manager.getEnabledPlugins().map(p => p.name)}`);
     *
     * } catch (error) {
     *   if (error.message.includes('dependency')) {
     *     console.error('Dependency resolution failed:', error.message);
     *   } else if (error.message.includes('circular')) {
     *     console.error('Circular dependency detected:', error.message);
     *   } else {
     *     console.error('Build failed:', error.message);
     *   }
     * }
     * ```
     *
     * @example
     * ```typescript
     * // Conditional building with validation
     * const manager = new PluginManager<UserData, ProcessedUser>();
     *
     * // Register core plugins
     * manager.register(coreValidationPlugin);
     * manager.register(userTransformPlugin);
     *
     * // Add optional plugins based on configuration
     * const config = await loadConfiguration();
     *
     * if (config.features.analytics) {
     *   manager.register(analyticsPlugin);
     * }
     *
     * if (config.features.notifications) {
     *   manager.register(notificationPlugin, {
     *     dependencies: ['user-transform-plugin']
     *   });
     * }
     *
     * // Validate plugin count before building
     * const enabledCount = manager.getEnabledPlugins().length;
     * if (enabledCount === 0) {
     *   throw new Error('No plugins enabled for execution');
     * }
     *
     * console.log(`Building manager with ${enabledCount} plugins`);
     * manager.build();
     * ```
     */
    build(): this;
    /**
     * Executes all registered plugins in dependency order
     *
     * Execution is the core operation where the manager processes input data
     * through all registered and enabled plugins. The execution process:
     *
     * 1. **Creates isolated execution context** - provides plugins with logging, settings, and shared state
     * 2. **Initializes all plugins** - calls initialize() lifecycle method
     * 3. **Executes plugins in dependency order** - respects dependencies and priorities
     * 4. **Handles errors gracefully** - continues execution when possible, tracks failures
     * 5. **Cleans up resources** - calls cleanup() lifecycle methods
     * 6. **Aggregates results** - combines individual plugin results into manager result
     *
     * **Context Isolation**: Each execution creates a fresh context, preventing
     * data leakage between different execution calls.
     *
     * @param input - Input data to process through the plugin pipeline
     * @param metadata - Execution metadata made available to all plugins via context
     * @param options - Optional execution configuration (timeouts, error handling, etc.)
     *
     * @returns Promise resolving to comprehensive execution results
     *
     * @throws {Error} When manager is not built
     * @throws {Error} When execution fails catastrophically
     *
     * @example
     * ```typescript
     * // Basic execution
     * const manager = new PluginManager<string, string>()
     *   .register(uppercasePlugin)
     *   .register(trimPlugin)
     *   .build();
     *
     * const result = await manager.execute('  hello world  ', {
     *   requestId: 'req-123',
     *   timestamp: Date.now()
     * });
     *
     * if (result.success) {
     *   console.log('Final output:', result.results[result.results.length - 1].output);
     *   console.log(`Execution took ${result.duration}ms`);
     * } else {
     *   console.error('Execution failed:', result.errors);
     * }
     * ```
     *
     * @example
     * ```typescript
     * // Complex execution with comprehensive result handling
     * interface UserRequest {
     *   userId: string;
     *   action: string;
     *   data: Record<string, any>;
     * }
     *
     * interface UserResponse {
     *   success: boolean;
     *   data: any;
     *   metadata: Record<string, any>;
     * }
     *
     * const manager = new PluginManager<UserRequest, UserResponse>()
     *   .register(authenticationPlugin)
     *   .register(authorizationPlugin)
     *   .register(validationPlugin)
     *   .register(businessLogicPlugin)
     *   .register(auditPlugin)
     *   .build();
     *
     * const request: UserRequest = {
     *   userId: 'user-456',
     *   action: 'update-profile',
     *   data: { name: 'John Doe', email: 'john@example.com' }
     * };
     *
     * const executionMetadata = {
     *   requestId: 'req-789',
     *   clientIp: '192.168.1.1',
     *   userAgent: 'Mozilla/5.0...',
     *   timestamp: Date.now()
     * };
     *
     * try {
     *   const result = await manager.execute(request, executionMetadata, {
     *     timeout: 30000,  // 30 second timeout
     *     stopOnError: false  // Continue execution even if some plugins fail
     *   });
     *
     *   // Analyze results
     *   console.log(`Execution ${result.success ? 'succeeded' : 'failed'}`);
     *   console.log(`Total duration: ${result.duration}ms`);
     *   console.log(`Plugins executed: ${result.results.length}`);
     *
     *   // Check individual plugin results
     *   result.results.forEach(pluginResult => {
     *     if (pluginResult.success) {
     *       console.log(`✓ ${pluginResult.pluginName} (${pluginResult.duration}ms)`);
     *     } else {
     *       console.error(`✗ ${pluginResult.pluginName} failed:`, pluginResult.error?.message);
     *     }
     *
     *     // Handle warnings
     *     if (pluginResult.warnings.length > 0) {
     *       console.warn(`⚠ ${pluginResult.pluginName} warnings:`, pluginResult.warnings);
     *     }
     *   });
     *
     *   // Handle overall warnings and errors
     *   if (result.warnings.length > 0) {
     *     console.warn('Execution warnings:', result.warnings);
     *   }
     *
     *   if (result.errors.length > 0) {
     *     console.error('Execution errors:', result.errors);
     *   }
     *
     * } catch (error) {
     *   console.error('Execution failed catastrophically:', error);
     * }
     * ```
     *
     * @example
     * ```typescript
     * // Batch execution with shared context
     * const batchManager = new PluginManager<UserData[], ProcessedUser[]>()
     *   .register(batchValidationPlugin)
     *   .register(batchEnrichmentPlugin)
     *   .register(batchPersistencePlugin)
     *   .build();
     *
     * const userBatch = await loadUserBatch();
     *
     * const result = await batchManager.execute(userBatch, {
     *   batchId: 'batch-001',
     *   batchSize: userBatch.length,
     *   processingMode: 'parallel'
     * });
     *
     * // Track batch processing metrics
     * const totalProcessed = result.success ?
     *   result.results[result.results.length - 1].output?.length || 0 : 0;
     *
     * console.log(`Batch processing complete:`);
     * console.log(`- Input: ${userBatch.length} users`);
     * console.log(`- Processed: ${totalProcessed} users`);
     * console.log(`- Duration: ${result.duration}ms`);
     * console.log(`- Average per user: ${(result.duration / userBatch.length).toFixed(2)}ms`);
     * ```
     */
    execute(input: TInput, metadata: TMetadata, options?: ExecutionOptions): Promise<ManagerResult<TOutput>>;
    /**
     * Validates that plugin name is unique within manager
     */
    private validatePluginUniqueness;
    /**
     * Creates plugin settings with sensible defaults
     */
    private createPluginSettings;
    /**
     * Retrieves registration or throws if not found
     */
    private getRegistration;
    /**
     * Creates execution pipeline from sorted registrations
     * Wraps each plugin in a processor for pipeline compatibility
     */
    private createPipeline;
    /**
     * Creates plugin execution context with settings map
     */
    private createExecutionContext;
    /**
     * Transforms pipeline result into manager result format
     * Aggregates plugin results, errors, and warnings
     */
    private createManagerResult;
    private ensureNotBuilt;
    private ensureNotAlreadyBuilt;
    private ensureBuilt;
}

/**
 * Dependency Resolver for plugin execution order
 *
 * Handles:
 * - Dependency validation (missing, disabled dependencies)
 * - Topological sorting for execution order
 * - Circular dependency detection
 * - Priority-based ordering within dependency levels
 */

declare class DependencyResolver {
    /**
     * Main entry point for resolving plugin dependencies
     * Validates dependencies and returns plugins in execution order
     *
     * @param registrations - Array of plugin registrations to resolve
     * @returns Sorted array of registrations in dependency order
     * @throws {Error} When dependencies are invalid or circular
     */
    static resolve(registrations: PluginRegistration[]): PluginRegistration[];
    /**
     * Validates all plugin dependencies are satisfied
     * Checks for missing dependencies and disabled dependency targets
     */
    private static validateDependencies;
    /**
     * Validates dependencies for a single plugin registration
     * Ensures all dependencies exist and are enabled
     */
    private static validatePluginDependencies;
    /**
     * Performs topological sort to determine execution order
     * Uses depth-first search with cycle detection
     */
    private static topologicalSort;
    /**
     * Sorts registrations by priority (highest first)
     * Used as initial ordering before dependency resolution
     */
    private static sortByPriority;
    /**
     * Alternative circular dependency detection using graph traversal
     * Can be used for pre-validation before sorting
     */
    static validateCircularDependencies(registrations: PluginRegistration[]): void;
}

/**
 * Plugin Manager Builder - Fluent configuration and composition API
 *
 * The PluginManagerBuilder provides a fluent, expressive API for configuring
 * complex plugin arrangements. It's designed to make plugin management more
 * readable and maintainable, especially for large applications with many plugins.
 *
 * ## Key Benefits
 *
 * - **Fluent Interface**: Method chaining for readable configuration
 * - **Conditional Logic**: Runtime decisions about plugin inclusion
 * - **Grouping**: Organize related plugins with shared tags
 * - **Priority Management**: Easy priority assignment and ordering
 * - **Validation**: Pre-build validation of plugin configuration
 * - **Cloning**: Create variations of plugin configurations
 *
 * ## Usage Patterns
 *
 * ### Basic Building
 * ```typescript
 * const manager = createPluginBuilder<string, string>()
 *   .plugin(validationPlugin)
 *   .plugin(transformPlugin)
 *   .plugin(outputPlugin)
 *   .build();
 * ```
 *
 * ### Environment-Specific Configuration
 * ```typescript
 * const builder = createPluginBuilder<ApiRequest, ApiResponse>()
 *   .plugin(corePlugin)
 *   .when(isDevelopment, debugPlugin)
 *   .when(isProduction, monitoringPlugin)
 *   .group({
 *     tag: 'validation',
 *     items: [
 *       { plugin: authPlugin, settings: { priority: 100 } },
 *       { plugin: inputValidationPlugin, settings: { priority: 90 } }
 *     ]
 *   });
 * ```
 */

declare class PluginManagerBuilder<TInput = unknown, TOutput = unknown, TMetadata extends Record<string, unknown> = Record<string, unknown>> {
    private readonly manager;
    /**
     * Registers a single plugin with optional settings
     *
     * This is the fundamental building block for plugin registration.
     * Each call adds one plugin to the manager's execution pipeline.
     *
     * @param plugin - Plugin instance to register
     * @param settings - Optional plugin configuration settings
     *
     * @returns Builder instance for method chaining
     *
     * @example
     * ```typescript
     * // Simple plugin registration
     * const builder = createPluginBuilder<string, string>()
     *   .plugin(uppercasePlugin)
     *   .plugin(trimPlugin);
     * ```
     *
     * @example
     * ```typescript
     * // Plugin registration with detailed settings
     * const builder = createPluginBuilder<UserData, ProcessedUser>()
     *   .plugin(validationPlugin, {
     *     enabled: true,
     *     priority: 100,
     *     config: {
     *       strictMode: true,
     *       requiredFields: ['id', 'email'],
     *       customValidators: ['email-format', 'phone-format']
     *     }
     *   })
     *   .plugin(enrichmentPlugin, {
     *     priority: 50,
     *     config: {
     *       dataSources: ['user-preferences', 'activity-history'],
     *       cacheEnabled: true,
     *       cacheTtl: 300000  // 5 minutes
     *     }
     *   });
     * ```
     *
     * @example
     * ```typescript
     * // Chained registration with different plugin types
     * const apiBuilder = createPluginBuilder<ApiRequest, ApiResponse>()
     *   .plugin(rateLimitingPlugin, {
     *     priority: 100,
     *     config: { maxRequests: 1000, windowMs: 60000 }
     *   })
     *   .plugin(authenticationPlugin, {
     *     priority: 90,
     *     config: { tokenExpiry: 3600, refreshEnabled: true }
     *   })
     *   .plugin(businessLogicPlugin, {
     *     priority: 50,
     *     config: { enableCaching: true, enableAudit: true }
     *   })
     *   .plugin(responseFormatterPlugin, {
     *     priority: 10,
     *     config: { includeMetadata: true, compression: 'gzip' }
     *   });
     * ```
     */
    plugin(plugin: IPlugin<TInput, TOutput, PluginContext<TMetadata>>, settings?: Partial<PluginSettings>): this;
    /**
     * Registers multiple plugins with their respective settings
     *
     * Convenient method for bulk plugin registration when you have
     * multiple plugins to register at once. Particularly useful for
     * plugin suites or when loading plugins from configuration.
     *
     * @param plugins - Array of plugin configurations
     *
     * @returns Builder instance for method chaining
     *
     * @example
     * ```typescript
     * // Bulk registration of related plugins
     * const validationSuite = [
     *   { plugin: schemaValidationPlugin, settings: { priority: 100 } },
     *   { plugin: businessRuleValidationPlugin, settings: { priority: 90 } },
     *   { plugin: securityValidationPlugin, settings: { priority: 80 } }
     * ];
     *
     * const builder = createPluginBuilder<ApiRequest, ApiResponse>()
     *   .plugins(validationSuite)
     *   .plugin(mainBusinessLogicPlugin);
     * ```
     *
     * @example
     * ```typescript
     * // Configuration-driven plugin loading
     * const pluginConfigs = await loadPluginConfiguration();
     *
     * const pluginRegistrations = pluginConfigs.map(config => ({
     *   plugin: pluginRegistry.get(config.name),
     *   settings: {
     *     enabled: config.enabled,
     *     priority: config.priority,
     *     config: config.parameters
     *   }
     * }));
     *
     * const builder = createPluginBuilder<DataRecord, ProcessedRecord>()
     *   .plugins(pluginRegistrations)
     *   .plugin(outputPlugin); // Always include output plugin
     * ```
     *
     * @example
     * ```typescript
     * // Environment-specific plugin suites
     * const developmentPlugins = [
     *   { plugin: debugPlugin, settings: { priority: 200 } },
     *   { plugin: performanceMonitorPlugin, settings: { priority: 190 } },
     *   { plugin: requestLoggerPlugin, settings: { priority: 180 } }
     * ];
     *
     * const productionPlugins = [
     *   { plugin: metricsPlugin, settings: { priority: 200 } },
     *   { plugin: alertingPlugin, settings: { priority: 190 } },
     *   { plugin: auditPlugin, settings: { priority: 180 } }
     * ];
     *
     * const builder = createPluginBuilder<UserRequest, UserResponse>()
     *   .plugin(corePlugin) // Always include core functionality
     *   .plugins(isDevelopment ? developmentPlugins : productionPlugins);
     * ```
     */
    plugins(plugins: Array<{
        plugin: IPlugin<TInput, TOutput, PluginContext<TMetadata>>;
        settings?: Partial<PluginSettings>;
    }>): this;
    /**
     * Conditionally registers a plugin based on a boolean condition
     *
     * Conditional registration allows you to include or exclude plugins
     * based on runtime conditions such as environment variables,
     * feature flags, configuration settings, or user preferences.
     *
     * @param condition - Whether to register the plugin (true = register)
     * @param plugin - Plugin to register if condition is true
     * @param settings - Optional plugin settings
     *
     * @returns Builder instance for method chaining
     *
     * @example
     * ```typescript
     * // Environment-based conditional registration
     * const isDevelopment = process.env.NODE_ENV === 'development';
     * const isProduction = process.env.NODE_ENV === 'production';
     * const enableDebug = process.env.DEBUG === 'true';
     *
     * const builder = createPluginBuilder<ApiRequest, ApiResponse>()
     *   .plugin(corePlugin) // Always include
     *
     *   // Development-only plugins
     *   .when(isDevelopment, debugPlugin)
     *   .when(isDevelopment, mockDataPlugin)
     *   .when(isDevelopment && enableDebug, verboseLoggingPlugin)
     *
     *   // Production-only plugins
     *   .when(isProduction, performanceMonitoringPlugin)
     *   .when(isProduction, alertingPlugin)
     *   .when(isProduction, compressionPlugin);
     * ```
     *
     * @example
     * ```typescript
     * // Feature flag-driven registration
     * const featureFlags = await loadFeatureFlags();
     *
     * const builder = createPluginBuilder<UserData, ProcessedUser>()
     *   .plugin(basicProcessingPlugin)
     *
     *   // Feature-specific plugins
     *   .when(featureFlags.enableRecommendations, recommendationPlugin)
     *   .when(featureFlags.enableAnalytics, analyticsPlugin)
     *   .when(featureFlags.enablePersonalization, personalizationPlugin, {
     *     config: {
     *       algorithm: featureFlags.personalizationAlgorithm,
     *       maxRecommendations: featureFlags.maxRecommendations
     *     }
     *   })
     *
     *   // Beta features
     *   .when(featureFlags.betaFeatures && featureFlags.enableAI, aiProcessingPlugin);
     * ```
     *
     * @example
     * ```typescript
     * // User preference-based registration
     * const userPreferences = await loadUserPreferences(userId);
     * const subscription = await getUserSubscription(userId);
     *
     * const builder = createPluginBuilder<UserContent, ProcessedContent>()
     *   .plugin(basicContentPlugin)
     *
     *   // Preference-based plugins
     *   .when(userPreferences.enablePersonalization, personalizationPlugin)
     *   .when(userPreferences.enableNotifications, notificationPlugin)
     *   .when(userPreferences.privacyMode === false, analyticsPlugin)
     *
     *   // Subscription-based features
     *   .when(subscription.tier === 'premium', premiumFeaturesPlugin)
     *   .when(subscription.tier === 'enterprise', enterpriseFeaturesPlugin)
     *   .when(subscription.addOns.includes('advanced-analytics'), advancedAnalyticsPlugin);
     * ```
     */
    when(condition: boolean, plugin: IPlugin<TInput, TOutput, PluginContext<TMetadata>>, settings?: Partial<PluginSettings>): this;
    /**
     * Registers a group of plugins with a common tag
     *
     * Plugin grouping helps organize related plugins and makes it easier
     * to manage plugin suites that work together. All plugins in a group
     * will be tagged with the group's tag, making them easy to query and
     * manage as a unit.
     *
     * @param plugins - Group configuration with tag and plugin items
     *
     * @returns Builder instance for method chaining
     *
     * @example
     * ```typescript
     * // Validation plugin group
     * const builder = createPluginBuilder<UserData, ProcessedUser>()
     *   .group({
     *     tag: 'validation',
     *     items: [
     *       {
     *         plugin: schemaValidationPlugin,
     *         settings: {
     *           priority: 100,
     *           config: { strictMode: true }
     *         }
     *       },
     *       {
     *         plugin: businessRuleValidationPlugin,
     *         settings: {
     *           priority: 90,
     *           config: { enableCustomRules: true }
     *         }
     *       },
     *       {
     *         plugin: securityValidationPlugin,
     *         settings: {
     *           priority: 80,
     *           config: { enableThreatDetection: true }
     *         }
     *       }
     *     ]
     *   });
     *
     * // Later, you can query validation plugins:
     * // const validationPlugins = manager.getPluginsByTag('validation');
     * ```
     *
     * @example
     * ```typescript
     * // Multiple functional groups
     * const apiBuilder = createPluginBuilder<ApiRequest, ApiResponse>()
     *
     *   // Security group
     *   .group({
     *     tag: 'security',
     *     items: [
     *       { plugin: authenticationPlugin, settings: { priority: 100 } },
     *       { plugin: authorizationPlugin, settings: { priority: 90 } },
     *       { plugin: rateLimitingPlugin, settings: { priority: 80 } }
     *     ]
     *   })
     *
     *   // Processing group
     *   .group({
     *     tag: 'processing',
     *     items: [
     *       { plugin: validationPlugin, settings: { priority: 70 } },
     *       { plugin: transformationPlugin, settings: { priority: 60 } },
     *       { plugin: businessLogicPlugin, settings: { priority: 50 } }
     *     ]
     *   })
     *
     *   // Output group
     *   .group({
     *     tag: 'output',
     *     items: [
     *       { plugin: formattingPlugin, settings: { priority: 20 } },
     *       { plugin: compressionPlugin, settings: { priority: 10 } },
     *       { plugin: cachePlugin, settings: { priority: 5 } }
     *     ]
     *   });
     * ```
     *
     * @example
     * ```typescript
     * // Environment-specific groups
     * const monitoringPlugins = isDevelopment
     *   ? [
     *       { plugin: debugPlugin, settings: { priority: 200 } },
     *       { plugin: performancePlugin, settings: { priority: 190 } }
     *     ]
     *   : [
     *       { plugin: metricsPlugin, settings: { priority: 200 } },
     *       { plugin: alertingPlugin, settings: { priority: 190 } },
     *       { plugin: auditPlugin, settings: { priority: 180 } }
     *     ];
     *
     * const builder = createPluginBuilder<DataRecord, ProcessedRecord>()
     *   .plugin(corePlugin)
     *   .group({
     *     tag: 'monitoring',
     *     items: monitoringPlugins
     *   });
     * ```
     */
    group(plugins: {
        tag: string;
        items: Array<{
            plugin: IPlugin<TInput, TOutput, PluginContext<TMetadata>>;
            settings?: Partial<PluginSettings>;
        }>;
    }): this;
    /**
     * Registers a plugin with a specific priority
     *
     * Priority assignment determines the order of plugin execution within
     * dependency levels. Higher priority plugins execute before lower priority
     * ones. This method provides a convenient way to set priority without
     * manually constructing settings objects.
     *
     * @param priority - Execution priority (higher = earlier execution)
     * @param plugin - Plugin to register
     * @param settings - Optional additional settings
     *
     * @returns Builder instance for method chaining
     *
     * @example
     * ```typescript
     * // Clear priority-based ordering
     * const builder = createPluginBuilder<ApiRequest, ApiResponse>()
     *   // Critical early processing (100-90)
     *   .withPriority(100, authenticationPlugin)
     *   .withPriority(95, rateLimitingPlugin)
     *   .withPriority(90, authorizationPlugin)
     *
     *   // Validation and preprocessing (80-60)
     *   .withPriority(80, inputValidationPlugin)
     *   .withPriority(70, sanitizationPlugin)
     *   .withPriority(60, normalizationPlugin)
     *
     *   // Core business logic (50-30)
     *   .withPriority(50, businessLogicPlugin)
     *   .withPriority(40, dataEnrichmentPlugin)
     *   .withPriority(30, calculationPlugin)
     *
     *   // Output processing (20-10)
     *   .withPriority(20, responseFormattingPlugin)
     *   .withPriority(15, compressionPlugin)
     *   .withPriority(10, cachePlugin);
     * ```
     *
     * @example
     * ```typescript
     * // Priority with additional configuration
     * const builder = createPluginBuilder<UserData, ProcessedUser>()
     *   .withPriority(100, validationPlugin, {
     *     config: {
     *       strictMode: true,
     *       failFast: true,
     *       requiredFields: ['id', 'email']
     *     }
     *   })
     *   .withPriority(50, enrichmentPlugin, {
     *     config: {
     *       sources: ['database', 'cache', 'external-api'],
     *       timeout: 5000,
     *       fallbackEnabled: true
     *     }
     *   })
     *   .withPriority(10, outputPlugin, {
     *     config: {
     *       format: 'json',
     *       includeMetadata: true,
     *       compression: 'gzip'
     *     }
     *   });
     * ```
     *
     * @example
     * ```typescript
     * // Dynamic priority assignment
     * const config = await loadConfiguration();
     *
     * const builder = createPluginBuilder<DataRecord, ProcessedRecord>()
     *   .plugin(corePlugin); // Default priority (0)
     *
     * // Add plugins with computed priorities
     * config.plugins.forEach((pluginConfig, index) => {
     *   const plugin = pluginRegistry.get(pluginConfig.name);
     *   const priority = config.basePriority + (config.plugins.length - index) * 10;
     *
     *   builder.withPriority(priority, plugin, {
     *     enabled: pluginConfig.enabled,
     *     config: pluginConfig.settings
     *   });
     * });
     * ```
     */
    withPriority(priority: number, plugin: IPlugin<TInput, TOutput, PluginContext<TMetadata>>, settings?: Partial<PluginSettings>): this;
    /**
     * Registers a plugin in disabled state
     *
     * Disabled plugins are registered but won't execute until explicitly enabled.
     * This is useful for plugins that you want to configure but activate later,
     * or for plugins that should only run under specific conditions.
     *
     * @param plugin - Plugin to register as disabled
     * @param settings - Optional additional settings
     *
     * @returns Builder instance for method chaining
     *
     * @example
     * ```typescript
     * // Register plugins that will be enabled conditionally later
     * const builder = createPluginBuilder<UserRequest, UserResponse>()
     *   .plugin(corePlugin) // Always enabled
     *
     *   // Disabled by default, enabled based on user tier
     *   .disabled(premiumFeaturesPlugin, {
     *     priority: 50,
     *     config: { featureSet: 'premium' }
     *   })
     *   .disabled(enterpriseFeaturesPlugin, {
     *     priority: 40,
     *     config: { featureSet: 'enterprise' }
     *   });
     *
     * // Later, before building, conditionally enable
     * const userTier = await getUserTier(userId);
     * if (userTier === 'premium') {
     *   manager.configure('premium-features-plugin', { enabled: true });
     * } else if (userTier === 'enterprise') {
     *   manager.configure('enterprise-features-plugin', { enabled: true });
     * }
     * ```
     *
     * @example
     * ```typescript
     * // Feature flags with disabled plugins
     * const builder = createPluginBuilder<DataRecord, ProcessedRecord>()
     *   .plugin(basicProcessingPlugin)
     *
     *   // Register experimental features as disabled
     *   .disabled(experimentalAlgorithmPlugin, {
     *     priority: 60,
     *     config: { algorithm: 'ml-enhanced', version: 'beta' }
     *   })
     *   .disabled(advancedAnalyticsPlugin, {
     *     priority: 30,
     *     config: { realTimeProcessing: true }
     *   });
     *
     * // Enable based on feature flags
     * const featureFlags = await loadFeatureFlags();
     * const manager = builder.build();
     *
     * if (featureFlags.enableExperimental) {
     *   manager.configure('experimental-algorithm-plugin', { enabled: true });
     * }
     * if (featureFlags.enableAdvancedAnalytics) {
     *   manager.configure('advanced-analytics-plugin', { enabled: true });
     * }
     * ```
     */
    disabled(plugin: IPlugin<TInput, TOutput, PluginContext<TMetadata>>, settings?: Partial<PluginSettings>): this;
    /**
     * Builds and returns the configured plugin manager
     *
     * Building finalizes the plugin configuration and creates a ready-to-use
     * plugin manager. This process includes dependency resolution, execution
     * order determination, and pipeline construction. After building, the
     * manager cannot be reconfigured.
     *
     * @returns Built plugin manager ready for execution
     *
     * @throws {Error} When dependency resolution fails
     * @throws {Error} When circular dependencies are detected
     *
     * @example
     * ```typescript
     * // Basic build
     * const manager = createPluginBuilder<string, string>()
     *   .plugin(validationPlugin)
     *   .plugin(transformPlugin)
     *   .plugin(outputPlugin)
     *   .build(); // Now ready for execution
     *
     * const result = await manager.execute('input data', {});
     * ```
     *
     * @example
     * ```typescript
     * // Build with error handling
     * try {
     *   const manager = createPluginBuilder<ApiRequest, ApiResponse>()
     *     .plugin(authPlugin)
     *     .plugin(businessLogicPlugin, { dependencies: ['auth-plugin'] })
     *     .plugin(responsePlugin, { dependencies: ['business-logic-plugin'] })
     *     .validate() // Optional: validate before building
     *     .build();
     *
     *   console.log('Manager built successfully');
     *
     * } catch (error) {
     *   console.error('Build failed:', error.message);
     *   // Handle build failure
     * }
     * ```
     */
    build(): PluginManager<TInput, TOutput, TMetadata>;
    /**
     * Validates the current builder configuration
     *
     * Validation checks the current plugin configuration for common issues
     * before building. This can help catch configuration problems early
     * and provide better error messages.
     *
     * @returns Builder instance for method chaining
     *
     * @throws {Error} When validation fails
     *
     * @example
     * ```typescript
     * // Validate before building
     * const manager = createPluginBuilder<UserData, ProcessedUser>()
     *   .plugin(validationPlugin)
     *   .plugin(transformPlugin)
     *   .validate() // Throws if no plugins or other issues
     *   .build();
     * ```
     */
    validate(): this;
    /**
     * Creates a deep copy of the current builder configuration
     *
     * Cloning allows you to create variations of plugin configurations
     * without modifying the original builder. This is useful for creating
     * different configurations for different environments or use cases.
     *
     * @returns New builder instance with identical configuration
     *
     * @example
     * ```typescript
     * // Base configuration
     * const baseBuilder = createPluginBuilder<ApiRequest, ApiResponse>()
     *   .plugin(authPlugin)
     *   .plugin(validationPlugin)
     *   .plugin(businessLogicPlugin);
     *
     * // Development variant
     * const devBuilder = baseBuilder.clone()
     *   .plugin(debugPlugin)
     *   .plugin(mockDataPlugin);
     *
     * // Production variant
     * const prodBuilder = baseBuilder.clone()
     *   .plugin(monitoringPlugin)
     *   .plugin(alertingPlugin)
     *   .plugin(compressionPlugin);
     *
     * const devManager = devBuilder.build();
     * const prodManager = prodBuilder.build();
     * ```
     */
    clone(): PluginManagerBuilder<TInput, TOutput, TMetadata>;
}

/**
 * Base Plugin Class - Foundation for all plugin implementations
 *
 * The BasePlugin class provides a robust foundation for creating custom plugins.
 * It implements the IPlugin interface with sensible defaults and utility methods
 * that make plugin development faster and more consistent.
 *
 * ## Key Features
 *
 * - **Abstract plugin interface** with required method definitions
 * - **Default lifecycle implementations** that can be overridden as needed
 * - **Logging utilities** with plugin context and consistent formatting
 * - **Error handling patterns** for graceful failure management
 * - **Extensible design** for custom plugin types and behaviors
 *
 * ## Usage Patterns
 *
 * ### Simple Plugin
 * ```typescript
 * class UppercasePlugin extends BasePlugin<string, string> {
 *   readonly metadata = {
 *     name: 'uppercase',
 *     version: '1.0.0',
 *     description: 'Converts text to uppercase'
 *   };
 *
 *   execute(input: string): string {
 *     return input.toUpperCase();
 *   }
 * }
 * ```
 *
 * ### Advanced Plugin with Lifecycle
 * ```typescript
 * class DatabasePlugin extends BasePlugin<UserData, SavedUser> {
 *   readonly metadata = {
 *     name: 'database-saver',
 *     version: '2.1.0',
 *     dependencies: ['validation-plugin']
 *   };
 *
 *   async initialize(context: PluginContext): Promise<void> {
 *     await super.initialize(context);
 *     const db = await createConnection();
 *     context.share('db-connection', db);
 *   }
 *
 *   async execute(input: UserData, context: PluginContext): Promise<SavedUser> {
 *     const db = context.retrieve<Database>('db-connection');
 *     return await db.users.save(input);
 *   }
 *
 *   async cleanup(context: PluginContext): Promise<void> {
 *     const db = context.retrieve<Database>('db-connection');
 *     await db?.close();
 *     await super.cleanup(context);
 *   }
 * }
 * ```
 */

declare abstract class BasePlugin<TInput = unknown, TOutput = unknown, TContext extends PluginContext = PluginContext> implements IPlugin<TInput, TOutput, TContext> {
    /**
     * Plugin metadata containing identification and dependency information
     *
     * This must be implemented by all concrete plugin classes. The metadata
     * is used for dependency resolution, plugin identification, and documentation.
     *
     * @example
     * ```typescript
     * readonly metadata = {
     *   name: 'user-validator',
     *   version: '1.2.3',
     *   description: 'Validates user data according to business rules',
     *   dependencies: ['schema-validator'],
     *   tags: ['validation', 'user-management']
     * };
     * ```
     */
    abstract readonly metadata: PluginMetadata;
    /**
     * Main execution logic that processes input data
     *
     * This is the core method that defines what your plugin does. It receives
     * input data and a context object, and should return the processed output.
     * Can be synchronous or asynchronous based on your plugin's needs.
     *
     * @param input - Input data to process
     * @param context - Execution context with logging, settings, and shared state
     *
     * @returns Processed output data (sync or async)
     *
     * @example
     * ```typescript
     * // Synchronous processing
     * execute(input: string): string {
     *   return input.trim().toLowerCase();
     * }
     * ```
     *
     * @example
     * ```typescript
     * // Asynchronous processing with context usage
     * async execute(input: UserData, context: PluginContext): Promise<EnrichedUser> {
     *   this.logInfo(context, `Processing user: ${input.id}`);
     *
     *   const settings = context.getSettings(this.metadata.name);
     *   const apiUrl = settings?.config.apiUrl as string;
     *
     *   const response = await fetch(`${apiUrl}/users/${input.id}/details`);
     *   const enrichmentData = await response.json();
     *
     *   const result = { ...input, ...enrichmentData };
     *   this.logInfo(context, `User enriched successfully`);
     *
     *   return result;
     * }
     * ```
     */
    abstract execute(input: TInput, context: TContext): Promise<TOutput> | TOutput;
    /**
     * Plugin initialization phase
     *
     * Called once before any execution begins. Use this method to set up
     * resources, validate configuration, establish connections, or perform
     * any one-time setup your plugin needs.
     *
     * The default implementation logs the initialization. Override to add
     * custom initialization logic, but remember to call super.initialize()
     * to maintain logging consistency.
     *
     * @param context - Execution context for logging and configuration access
     *
     * @example
     * ```typescript
     * async initialize(context: PluginContext): Promise<void> {
     *   await super.initialize(context); // Keep default logging
     *
     *   // Custom initialization
     *   const settings = context.getSettings(this.metadata.name);
     *   const connectionString = settings?.config.connectionString as string;
     *
     *   if (!connectionString) {
     *     throw new Error('Database connection string is required');
     *   }
     *
     *   const db = await createDatabaseConnection(connectionString);
     *   context.share('database', db);
     *
     *   this.logInfo(context, 'Database connection established');
     * }
     * ```
     *
     * @example
     * ```typescript
     * async initialize(context: PluginContext): Promise<void> {
     *   await super.initialize(context);
     *
     *   // Initialize cache
     *   const cache = new Map<string, any>();
     *   context.share(`${this.metadata.name}-cache`, cache);
     *
     *   // Validate required settings
     *   const settings = context.getSettings(this.metadata.name);
     *   const requiredConfig = ['apiKey', 'baseUrl', 'timeout'];
     *
     *   for (const key of requiredConfig) {
     *     if (!settings?.config[key]) {
     *       throw new Error(`Missing required configuration: ${key}`);
     *     }
     *   }
     *
     *   this.logInfo(context, 'Plugin initialized successfully');
     * }
     * ```
     */
    initialize(context: TContext): Promise<void>;
    /**
     * Plugin cleanup phase
     *
     * Called after execution completes, regardless of success or failure.
     * Use this method to clean up resources, close connections, delete
     * temporary files, or perform any necessary cleanup.
     *
     * The default implementation logs the cleanup. Override to add custom
     * cleanup logic, and remember to call super.cleanup() to maintain
     * logging consistency.
     *
     * @param context - Execution context for logging
     *
     * @example
     * ```typescript
     * async cleanup(context: PluginContext): Promise<void> {
     *   // Custom cleanup first
     *   const db = context.retrieve<Database>('database');
     *   if (db) {
     *     await db.close();
     *     this.logInfo(context, 'Database connection closed');
     *   }
     *
     *   const cache = context.retrieve<Map<string, any>>(`${this.metadata.name}-cache`);
     *   if (cache) {
     *     cache.clear();
     *     this.logInfo(context, 'Cache cleared');
     *   }
     *
     *   await super.cleanup(context); // Keep default logging
     * }
     * ```
     *
     * @example
     * ```typescript
     * async cleanup(context: PluginContext): Promise<void> {
     *   try {
     *     // Cleanup external resources
     *     const httpClient = context.retrieve<HttpClient>('http-client');
     *     await httpClient?.destroy();
     *
     *     // Remove temporary files
     *     const tempFiles = context.retrieve<string[]>('temp-files') || [];
     *     for (const file of tempFiles) {
     *       await fs.unlink(file).catch(() => {}); // Ignore errors
     *     }
     *
     *     this.logInfo(context, 'Cleanup completed successfully');
     *
     *   } catch (error) {
     *     this.logWarning(context, 'Cleanup encountered errors', { error });
     *   } finally {
     *     await super.cleanup(context);
     *   }
     * }
     * ```
     */
    cleanup(context: TContext): Promise<void>;
    /**
     * Error handling for plugin failures
     *
     * Called when plugin execution throws an error. Use this method to
     * implement custom error handling, logging, recovery attempts, or
     * cleanup operations specific to error conditions.
     *
     * The default implementation logs the error with context. Override
     * to add custom error handling, but consider calling super.onError()
     * to maintain consistent error logging.
     *
     * @param error - Error that occurred during execution
     * @param context - Execution context for logging and state access
     *
     * @example
     * ```typescript
     * async onError(error: Error, context: PluginContext): Promise<void> {
     *   // Log the error with context
     *   await super.onError(error, context);
     *
     *   // Custom error handling
     *   if (error.message.includes('connection')) {
     *     this.logWarning(context, 'Attempting to reconnect...');
     *
     *     try {
     *       const db = await this.reconnectDatabase();
     *       context.share('database', db);
     *       this.logInfo(context, 'Reconnection successful');
     *     } catch (reconnectError) {
     *       this.logError(context, 'Reconnection failed', { reconnectError });
     *     }
     *   }
     *
     *   // Send error to monitoring system
     *   const monitoring = context.retrieve<MonitoringService>('monitoring');
     *   await monitoring?.reportError(this.metadata.name, error);
     * }
     * ```
     *
     * @example
     * ```typescript
     * async onError(error: Error, context: PluginContext): Promise<void> {
     *   await super.onError(error, context);
     *
     *   // Categorize error types
     *   if (error instanceof ValidationError) {
     *     this.logWarning(context, 'Input validation failed', {
     *       validationErrors: error.details
     *     });
     *
     *     // Add warning instead of failing completely
     *     context.addWarning('VALIDATION_FAILED',
     *       `Validation failed: ${error.message}`,
     *       { details: error.details }
     *     );
     *
     *   } else if (error instanceof NetworkError) {
     *     this.logError(context, 'Network operation failed', {
     *       url: error.url,
     *       statusCode: error.statusCode
     *     });
     *
     *     // Implement retry logic or fallback
     *     const retryCount = context.retrieve<number>('retry-count') || 0;
     *     if (retryCount < 3) {
     *       context.share('retry-count', retryCount + 1);
     *       this.logInfo(context, `Scheduling retry attempt ${retryCount + 1}`);
     *     }
     *
     *   } else {
     *     this.logError(context, 'Unexpected error occurred', {
     *       errorType: error.constructor.name,
     *       stack: error.stack
     *     });
     *   }
     * }
     * ```
     */
    onError(error: Error, context: TContext): Promise<void>;
    /**
     * Logs informational message with plugin context
     *
     * Use this for general information about plugin operation, successful
     * completions, or important state changes. Messages are prefixed with
     * the plugin name for easy identification in logs.
     *
     * @param context - Execution context for logging
     * @param message - Message to log
     * @param data - Optional additional data to include
     *
     * @example
     * ```typescript
     * execute(input: UserData, context: PluginContext): Promise<ProcessedUser> {
     *   this.logInfo(context, `Processing user: ${input.id}`);
     *
     *   const result = await this.processUser(input);
     *
     *   this.logInfo(context, 'User processing completed', {
     *     userId: input.id,
     *     processingTime: Date.now() - startTime,
     *     fieldsProcessed: Object.keys(result).length
     *   });
     *
     *   return result;
     * }
     * ```
     */
    protected logInfo(context: TContext, message: string, data?: unknown): void;
    /**
     * Logs warning message and adds to context warnings
     *
     * Use this for non-fatal issues that don't prevent plugin execution
     * but should be noted. Warnings are included in execution results
     * and can be used for monitoring and alerting.
     *
     * @param context - Execution context for logging and warnings
     * @param message - Warning message to log
     * @param data - Optional additional data to include
     *
     * @example
     * ```typescript
     * execute(input: ApiRequest, context: PluginContext): Promise<ApiResponse> {
     *   if (input.timeout && input.timeout > 30000) {
     *     this.logWarning(context, 'Request timeout exceeds recommended limit', {
     *       requestedTimeout: input.timeout,
     *       recommendedMax: 30000
     *     });
     *   }
     *
     *   if (!input.headers['User-Agent']) {
     *     this.logWarning(context, 'User-Agent header missing from request');
     *   }
     *
     *   return this.processRequest(input);
     * }
     * ```
     */
    protected logWarning(context: TContext, message: string, data?: unknown): void;
    /**
     * Logs error message with plugin context
     *
     * Use this for logging errors that occur during plugin execution.
     * This is for logging purposes only and doesn't affect the execution
     * flow. For fatal errors, you should throw an exception.
     *
     * @param context - Execution context for logging
     * @param message - Error message to log
     * @param data - Optional additional data to include
     *
     * @example
     * ```typescript
     * async execute(input: UserData, context: PluginContext): Promise<ProcessedUser> {
     *   try {
     *     const enrichedData = await this.fetchEnrichmentData(input.id);
     *     return { ...input, ...enrichedData };
     *
     *   } catch (error) {
     *     this.logError(context, 'Failed to fetch enrichment data', {
     *       userId: input.id,
     *       error: error.message,
     *       endpoint: this.apiEndpoint
     *     });
     *
     *     // Return input without enrichment instead of failing
     *     this.logWarning(context, 'Proceeding without enrichment data');
     *     return input as ProcessedUser;
     *   }
     * }
     * ```
     */
    protected logError(context: TContext, message: string, data?: unknown): void;
}

/**
 * Plugin Processor - Adapter between plugins and pipeline system
 *
 * Bridges the plugin interface with the pipeline processor interface:
 * - Wraps plugins for pipeline compatibility
 * - Manages plugin lifecycle (setup, execution, cleanup)
 * - Handles dependency-based execution control
 * - Tracks failed plugins to prevent cascading issues
 */

declare class PluginProcessor<TInput, TOutput, TContext extends PluginContext> implements PipelineProcessor<TInput, TOutput, TContext> {
    private readonly plugin;
    private readonly dependencies;
    readonly name: string;
    readonly version: "1.0.0";
    readonly stage: ReturnType<typeof createStage>;
    constructor(plugin: IPlugin<TInput, TOutput, TContext>, dependencies?: readonly string[]);
    /**
     * Determines if plugin can execute based on dependency failures
     * Plugins are skipped if any of their dependencies failed
     */
    private canExecute;
    /**
     * Plugin initialization phase
     * Called once before any processing begins
     */
    setup(context: TContext): Promise<void>;
    /**
     * Main plugin execution
     * Wraps plugin execution with failure tracking
     */
    process(input: TInput, context: TContext): Promise<TOutput>;
    /**
     * Plugin cleanup phase
     * Called after processing completes (success or failure)
     */
    teardown(context: TContext): Promise<void>;
    /**
     * Plugin error handling
     * Delegates to plugin's error handler
     */
    onError(error: Error, context: TContext): Promise<void>;
    /**
     * Marks plugin as failed in shared context
     * Prevents dependent plugins from executing
     */
    private markPluginAsFailed;
}

/**
 * Plugin Factory - Advanced plugin creation with specialized capabilities
 *
 * The PluginFactory provides factory methods for creating sophisticated plugins
 * with built-in patterns like retry logic, caching, throttling, and monitoring.
 * These factories eliminate boilerplate code and provide battle-tested implementations
 * of common plugin patterns.
 *
 * ## Factory Categories
 *
 * - **Core**: Basic plugin creation and composition
 * - **Resilience**: Retry, error handling, and fault tolerance
 * - **Performance**: Caching, throttling, and batch processing
 * - **Control Flow**: Conditional execution and middleware patterns
 * - **Monitoring**: Observability and performance tracking
 *
 * @example
 * ```typescript
 * // Create a resilient API plugin with retry and caching
 * const apiPlugin = PluginFactory.withRetry(
 *   'api-caller',
 *   async (request: ApiRequest) => {
 *     const response = await fetch(request.url, request.options);
 *     return response.json();
 *   },
 *   { maxAttempts: 3, backoffMs: 1000 }
 * );
 *
 * const cachedApiPlugin = PluginFactory.withCache(
 *   'cached-api',
 *   apiPlugin.execute.bind(apiPlugin),
 *   { keyGenerator: (req) => `${req.method}:${req.url}`, ttlMs: 300000 }
 * );
 * ```
 */

/**
 * Lifecycle hooks for plugin execution
 * Provides extension points for custom plugin behavior
 */
interface PluginHooks<TInput, TOutput, TContext extends PluginContext> {
    /** Called once during plugin initialization */
    initialize?: (context: TContext) => Promise<void> | void;
    /** Called after plugin execution completes */
    cleanup?: (context: TContext) => Promise<void> | void;
    /** Called when plugin execution fails */
    onError?: (error: Error, context: TContext) => Promise<void> | void;
}
/**
 * Configuration for conditional plugin execution
 */
interface ConditionalOptions {
    /** Function that determines whether to execute the plugin */
    condition: (input: any, context: PluginContext) => boolean | Promise<boolean>;
    /** Value to return when condition is false (defaults to input) */
    skipValue?: any;
    /** Callback executed when plugin is skipped */
    onSkip?: (input: any, context: PluginContext) => void | Promise<void>;
}
/**
 * Configuration for retry behavior
 */
interface RetryOptions {
    /** Maximum number of execution attempts */
    maxAttempts: number;
    /** Base delay between retries in milliseconds */
    backoffMs?: number;
    /** Function to determine if error should trigger retry */
    retryOn?: (error: Error) => boolean;
    /** Callback executed before each retry attempt */
    onRetry?: (attempt: number, error: Error, context: PluginContext) => void | Promise<void>;
}
/**
 * Configuration for caching behavior
 */
interface CacheOptions {
    /** Function to generate cache keys from input */
    keyGenerator: (input: any, context: PluginContext) => string;
    /** Time-to-live for cached entries in milliseconds */
    ttlMs?: number;
    /** Maximum number of entries in cache */
    maxSize?: number;
}
/**
 * Configuration for throttling behavior
 */
interface ThrottleOptions {
    /** Maximum number of concurrent executions */
    maxConcurrent: number;
    /** Maximum queue size for pending requests */
    queueSize?: number;
    /** Timeout for queued requests in milliseconds */
    timeout?: number;
}
declare class PluginFactory {
    /**
     * Creates a basic plugin with custom execution logic and optional lifecycle hooks
     *
     * This is the foundation method for creating any custom plugin. It provides
     * a clean interface for wrapping your business logic in a plugin container
     * with proper lifecycle management and error handling.
     *
     * @template TInput - Input data type
     * @template TOutput - Output data type
     * @template TContext - Plugin context type
     *
     * @param metadata - Plugin identification and dependency information
     * @param execute - Main execution function that processes input data
     * @param hooks - Optional lifecycle hooks for initialization, cleanup, and error handling
     *
     * @returns A fully configured plugin instance
     *
     * @example
     * ```typescript
     * // Simple synchronous plugin
     * const upperCasePlugin = PluginFactory.create(
     *   {
     *     name: 'uppercase',
     *     version: '1.0.0',
     *     description: 'Converts text to uppercase'
     *   },
     *   (input: string) => input.toUpperCase()
     * );
     * ```
     *
     * @example
     * ```typescript
     * // Complex async plugin with resource management
     * const databasePlugin = PluginFactory.create(
     *   {
     *     name: 'database-saver',
     *     version: '2.1.0',
     *     dependencies: ['validator', 'transformer']
     *   },
     *   async (data: UserData, context) => {
     *     const db = context.retrieve<Database>('db-connection');
     *     const result = await db.users.create(data);
     *     context.logger.info(`Created user: ${result.id}`);
     *     return result;
     *   },
     *   {
     *     initialize: async (context) => {
     *       const db = await createDbConnection();
     *       context.share('db-connection', db);
     *     },
     *     cleanup: async (context) => {
     *       const db = context.retrieve('db-connection');
     *       await db?.close();
     *     }
     *   }
     * );
     * ```
     */
    static create<TInput, TOutput, TContext extends PluginContext = PluginContext>(metadata: PluginMetadata, execute: (input: TInput, context: TContext) => Promise<TOutput> | TOutput, hooks?: PluginHooks<TInput, TOutput, TContext>): IPlugin<TInput, TOutput, TContext>;
    /**
     * Creates a batch processing plugin for handling arrays of data
     *
     * Batch processing is essential for high-throughput scenarios where you need
     * to process large amounts of data efficiently. This factory handles chunking,
     * parallel processing, and result aggregation automatically.
     *
     * @template TInput - Type of individual items in the input array
     * @template TOutput - Type of individual items in the output array
     * @template TContext - Plugin context type
     *
     * @param name - Base name for the batch plugin (will be suffixed with '-batch')
     * @param processor - Function that processes a batch of items
     * @param options - Configuration for batch behavior
     *
     * @returns Plugin that processes arrays of data in configurable batches
     *
     * @example
     * ```typescript
     * // Process user records in batches for database insertion
     * const batchInsertPlugin = PluginFactory.batch(
     *   'user-insert',
     *   async (users: UserData[], context) => {
     *     const db = context.retrieve<Database>('db');
     *     const results = await db.users.insertMany(users);
     *     context.logger.info(`Inserted ${results.length} users`);
     *     return results;
     *   },
     *   {
     *     batchSize: 50,        // Process 50 users at a time
     *     parallel: false,      // Process batches sequentially
     *     description: 'Batch inserts users into database'
     *   }
     * );
     * ```
     *
     * @example
     * ```typescript
     * // Parallel image processing with custom batch size
     * const imageProcessor = PluginFactory.batch(
     *   'image-resize',
     *   async (images: ImageFile[], context) => {
     *     return Promise.all(images.map(async (img) => {
     *       const resized = await resizeImage(img, { width: 800, height: 600 });
     *       context.logger.debug(`Resized image: ${img.name}`);
     *       return resized;
     *     }));
     *   },
     *   {
     *     batchSize: 10,       // 10 images per batch
     *     parallel: true,      // Process batches in parallel
     *     version: '1.2.0'
     *   }
     * );
     * ```
     */
    static batch<TInput, TOutput, TContext extends PluginContext = PluginContext>(name: string, processor: (items: TInput[], context: TContext) => Promise<TOutput[]> | TOutput[], options?: {
        batchSize?: number;
        parallel?: boolean;
        version?: string;
        description?: string;
    }): IPlugin<TInput[], TOutput[], TContext>;
    /**
     * Creates a conditional execution plugin that runs based on runtime conditions
     *
     * Conditional plugins provide dynamic control flow within your pipeline.
     * They're perfect for implementing feature flags, environment-specific logic,
     * or data-driven processing decisions.
     *
     * @template TInput - Input data type
     * @template TOutput - Output data type
     * @template TContext - Plugin context type
     *
     * @param name - Base name for the conditional plugin
     * @param processor - Function to execute when condition is true
     * @param conditionOptions - Configuration for the conditional behavior
     * @param options - Additional plugin options
     *
     * @returns Plugin that conditionally executes based on runtime conditions
     *
     * @example
     * ```typescript
     * // Only process data in production environment
     * const prodOnlyPlugin = PluginFactory.conditional(
     *   'production-processor',
     *   async (data: UserData, context) => {
     *     // Expensive production-only processing
     *     const result = await complexProcessing(data);
     *     context.logger.info(`Processed ${data.id} in production mode`);
     *     return result;
     *   },
     *   {
     *     condition: (data, context) => {
     *       const settings = context.getSettings('production-processor');
     *       return settings?.config.environment === 'production';
     *     },
     *     onSkip: (data, context) => {
     *       context.logger.debug(`Skipping production processing for ${data.id}`);
     *     }
     *   }
     * );
     * ```
     *
     * @example
     * ```typescript
     * // Data-driven conditional processing
     * const premiumFeaturePlugin = PluginFactory.conditional(
     *   'premium-features',
     *   async (user: User, context) => {
     *     const premiumFeatures = await loadPremiumFeatures(user.id);
     *     return { ...user, premiumFeatures };
     *   },
     *   {
     *     condition: (user) => user.subscriptionType === 'premium',
     *     skipValue: (user) => ({ ...user, premiumFeatures: [] }),
     *     onSkip: (user, context) => {
     *       context.addWarning('PREMIUM_SKIPPED', `User ${user.id} is not premium`);
     *     }
     *   }
     * );
     * ```
     */
    static conditional<TInput, TOutput, TContext extends PluginContext = PluginContext>(name: string, processor: (input: TInput, context: TContext) => Promise<TOutput> | TOutput, conditionOptions: ConditionalOptions, options?: {
        version?: string;
        description?: string;
    }): IPlugin<TInput, TInput | TOutput, TContext>;
    /**
     * Creates a retry wrapper plugin for resilient execution
     *
     * Retry plugins add fault tolerance to your pipeline by automatically
     * retrying failed operations with configurable backoff strategies.
     * Essential for handling network issues, temporary service outages,
     * and other transient failures.
     *
     * @template TInput - Input data type
     * @template TOutput - Output data type
     * @template TContext - Plugin context type
     *
     * @param name - Base name for the retry plugin
     * @param processor - Function to execute with retry logic
     * @param retryOptions - Configuration for retry behavior
     * @param options - Additional plugin options
     *
     * @returns Plugin that automatically retries failed executions
     *
     * @example
     * ```typescript
     * // Retry API calls with exponential backoff
     * const resilientApiPlugin = PluginFactory.withRetry(
     *   'api-call',
     *   async (request: ApiRequest, context) => {
     *     const response = await fetch(request.url, {
     *       method: request.method,
     *       headers: request.headers,
     *       body: JSON.stringify(request.data)
     *     });
     *
     *     if (!response.ok) {
     *       throw new Error(`API call failed: ${response.status}`);
     *     }
     *
     *     return response.json();
     *   },
     *   {
     *     maxAttempts: 3,
     *     backoffMs: 1000,      // Start with 1 second, doubles each retry
     *     retryOn: (error) => {
     *       // Only retry on network errors, not on client errors (4xx)
     *       return !error.message.includes('4');
     *     },
     *     onRetry: (attempt, error, context) => {
     *       context.logger.warn(`API call failed, attempt ${attempt}: ${error.message}`);
     *     }
     *   }
     * );
     * ```
     *
     * @example
     * ```typescript
     * // Database operation with custom retry logic
     * const dbRetryPlugin = PluginFactory.withRetry(
     *   'database-write',
     *   async (data: UserData, context) => {
     *     const db = context.retrieve<Database>('database');
     *     return await db.users.create(data);
     *   },
     *   {
     *     maxAttempts: 5,
     *     backoffMs: 500,
     *     retryOn: (error) => {
     *       // Retry on connection errors but not on validation errors
     *       return error.message.includes('connection') ||
     *              error.message.includes('timeout');
     *     }
     *   }
     * );
     * ```
     */
    static withRetry<TInput, TOutput, TContext extends PluginContext = PluginContext>(name: string, processor: (input: TInput, context: TContext) => Promise<TOutput> | TOutput, retryOptions: RetryOptions, options?: {
        version?: string;
        description?: string;
    }): IPlugin<TInput, TOutput, TContext>;
    /**
     * Creates a cached plugin wrapper for performance optimization
     *
     * Caching plugins store execution results to avoid expensive recomputation.
     * They implement LRU eviction and TTL expiration for memory management.
     * Perfect for expensive computations, API calls, or database queries.
     *
     * @template TInput - Input data type
     * @template TOutput - Output data type
     * @template TContext - Plugin context type
     *
     * @param name - Base name for the cached plugin
     * @param processor - Function to execute with caching
     * @param cacheOptions - Configuration for cache behavior
     * @param options - Additional plugin options
     *
     * @returns Plugin that caches execution results for performance
     *
     * @example
     * ```typescript
     * // Cache expensive API responses
     * const cachedUserPlugin = PluginFactory.withCache(
     *   'user-lookup',
     *   async (userId: string, context) => {
     *     context.logger.debug(`Fetching user data for: ${userId}`);
     *     const response = await fetch(`/api/users/${userId}`);
     *     return response.json();
     *   },
     *   {
     *     keyGenerator: (userId) => `user:${userId}`,
     *     ttlMs: 300000,        // Cache for 5 minutes
     *     maxSize: 1000         // Keep up to 1000 users in cache
     *   }
     * );
     * ```
     *
     * @example
     * ```typescript
     * // Cache complex calculations with context-aware keys
     * const calculationPlugin = PluginFactory.withCache(
     *   'complex-calc',
     *   async (input: CalculationInput, context) => {
     *     // Expensive mathematical computation
     *     const result = await performComplexCalculation(input);
     *     context.logger.info(`Calculated result: ${result.value}`);
     *     return result;
     *   },
     *   {
     *     keyGenerator: (input, context) => {
     *       const version = context.getSettings('complex-calc')?.config.version || 'v1';
     *       return `calc:${version}:${JSON.stringify(input)}`;
     *     },
     *     ttlMs: 3600000,       // Cache for 1 hour
     *     maxSize: 500
     *   }
     * );
     * ```
     */
    static withCache<TInput, TOutput, TContext extends PluginContext = PluginContext>(name: string, processor: (input: TInput, context: TContext) => Promise<TOutput> | TOutput, cacheOptions: CacheOptions, options?: {
        version?: string;
        description?: string;
    }): IPlugin<TInput, TOutput, TContext>;
    /**
     * Creates a throttled plugin wrapper for concurrency control
     *
     * Throttling plugins limit concurrent executions to prevent overwhelming
     * external services or consuming too many system resources. They queue
     * requests and process them according to the concurrency limits.
     *
     * @template TInput - Input data type
     * @template TOutput - Output data type
     * @template TContext - Plugin context type
     *
     * @param name - Base name for the throttled plugin
     * @param processor - Function to execute with throttling
     * @param throttleOptions - Configuration for throttling behavior
     * @param options - Additional plugin options
     *
     * @returns Plugin that limits concurrent executions
     *
     * @example
     * ```typescript
     * // Limit concurrent database connections
     * const dbPlugin = PluginFactory.withThrottle(
     *   'database-query',
     *   async (query: DatabaseQuery, context) => {
     *     const db = context.retrieve<Database>('database');
     *     const startTime = Date.now();
     *
     *     const result = await db.execute(query);
     *
     *     const duration = Date.now() - startTime;
     *     context.logger.debug(`Query executed in ${duration}ms`);
     *
     *     return result;
     *   },
     *   {
     *     maxConcurrent: 5,     // Max 5 simultaneous queries
     *     queueSize: 50,        // Queue up to 50 pending queries
     *     timeout: 30000        // 30 second timeout for queued requests
     *   }
     * );
     * ```
     *
     * @example
     * ```typescript
     * // Rate-limit API calls to external service
     * const apiThrottlePlugin = PluginFactory.withThrottle(
     *   'external-api',
     *   async (request: ApiRequest, context) => {
     *     context.logger.debug(`Making API call to: ${request.endpoint}`);
     *
     *     const response = await fetch(request.url, {
     *       method: request.method,
     *       headers: { 'Authorization': `Bearer ${request.token}` },
     *       body: JSON.stringify(request.data)
     *     });
     *
     *     if (!response.ok) {
     *       throw new Error(`API error: ${response.status}`);
     *     }
     *
     *     return response.json();
     *   },
     *   {
     *     maxConcurrent: 10,    // 10 concurrent API calls max
     *     queueSize: 100,       // Queue up to 100 requests
     *     timeout: 60000        // 1 minute timeout
     *   }
     * );
     * ```
     */
    static withThrottle<TInput, TOutput, TContext extends PluginContext = PluginContext>(name: string, processor: (input: TInput, context: TContext) => Promise<TOutput> | TOutput, throttleOptions: ThrottleOptions, options?: {
        version?: string;
        description?: string;
    }): IPlugin<TInput, TOutput, TContext>;
    /**
     * Creates a pipeline composition plugin that chains multiple plugins
     *
     * Composition plugins allow you to create higher-order plugins by chaining
     * multiple existing plugins together. The output of one plugin becomes the
     * input of the next, creating a processing pipeline.
     *
     * @example
     * ```typescript
     * const textProcessor = PluginFactory.compose(
     *   'text-pipeline',
     *   [trimPlugin, uppercasePlugin, validatePlugin],
     *   {
     *     description: 'Complete text processing pipeline',
     *     failFast: true  // Stop on first error
     *   }
     * );
     * ```
     */
    static compose<TInput, TOutput, TContext extends PluginContext = PluginContext>(name: string, plugins: Array<IPlugin<any, any, TContext>>, options?: {
        version?: string;
        description?: string;
        failFast?: boolean;
    }): IPlugin<TInput, TOutput, TContext>;
    /**
     * Creates a parallel execution plugin that runs multiple plugins concurrently
     *
     * Parallel plugins execute multiple plugins simultaneously on the same input
     * and can aggregate their results. Useful for scenarios where you need to
     * perform multiple independent operations on the same data.
     *
     * @example
     * ```typescript
     * const multiValidatorPlugin = PluginFactory.parallel(
     *   'multi-validator',
     *   [schemaValidator, businessRuleValidator, securityValidator],
     *   {
     *     failFast: false,  // Continue even if some validators fail
     *     aggregator: (results) => ({
     *       isValid: results.every(r => r.isValid),
     *       errors: results.flatMap(r => r.errors || [])
     *     })
     *   }
     * );
     * ```
     */
    static parallel<TInput, TOutput, TContext extends PluginContext = PluginContext>(name: string, plugins: Array<IPlugin<TInput, TOutput, TContext>>, options?: {
        version?: string;
        description?: string;
        aggregator?: (results: TOutput[]) => TOutput;
        failFast?: boolean;
    }): IPlugin<TInput, TOutput | TOutput[], TContext>;
    /**
     * Creates a validation plugin for input/output verification
     *
     * Validation plugins provide data integrity checking with configurable
     * error handling. They can either fail fast or continue with warnings
     * based on configuration.
     *
     * @example
     * ```typescript
     * const userValidator = PluginFactory.validation(
     *   'user-data',
     *   async (userData: UserData, context) => {
     *     if (!userData.email || !userData.email.includes('@')) {
     *       throw new Error('Invalid email format');
     *     }
     *     if (userData.age < 0 || userData.age > 120) {
     *       throw new Error('Invalid age range');
     *     }
     *     return userData; // Return validated data
     *   },
     *   {
     *     stopOnError: false  // Continue with warnings instead of failing
     *   }
     * );
     * ```
     */
    static validation<TInput, TOutput, TContext extends PluginContext = PluginContext>(name: string, validator: (input: TInput, context: TContext) => Promise<TOutput> | TOutput, options?: {
        version?: string;
        description?: string;
        stopOnError?: boolean;
    }): IPlugin<TInput, TOutput, TContext>;
    /**
     * Creates a transformation plugin for data manipulation
     *
     * Transformation plugins focus on data conversion and manipulation.
     * They provide a clean interface for data processing operations.
     *
     * @example
     * ```typescript
     * const userTransformer = PluginFactory.transform(
     *   'user-normalizer',
     *   async (userData: RawUserData, context) => {
     *     return {
     *       id: userData.user_id,
     *       name: userData.full_name.trim(),
     *       email: userData.email_address.toLowerCase(),
     *       createdAt: new Date(userData.created_timestamp)
     *     };
     *   },
     *   {
     *     dependencies: ['user-validator'],
     *     description: 'Normalizes user data structure'
     *   }
     * );
     * ```
     */
    static transform<TInput, TOutput, TContext extends PluginContext = PluginContext>(name: string, transformer: (input: TInput, context: TContext) => Promise<TOutput> | TOutput, options?: {
        version?: string;
        description?: string;
        dependencies?: string[];
    }): IPlugin<TInput, TOutput, TContext>;
    /**
     * Creates a middleware plugin for request/response processing
     *
     * Middleware plugins provide intercept-style processing where you can
     * modify data before and after the main processing occurs.
     *
     * @example
     * ```typescript
     * const loggingMiddleware = PluginFactory.middleware(
     *   'request-logger',
     *   async (data: ApiRequest, context, next) => {
     *     const startTime = Date.now();
     *     context.logger.info(`Processing request: ${data.method} ${data.url}`);
     *
     *     const result = await next();
     *
     *     const duration = Date.now() - startTime;
     *     context.logger.info(`Request completed in ${duration}ms`);
     *
     *     return result;
     *   }
     * );
     * ```
     */
    static middleware<TData, TContext extends PluginContext = PluginContext>(name: string, middleware: (data: TData, context: TContext, next: () => Promise<TData>) => Promise<TData>, options?: {
        version?: string;
        description?: string;
    }): IPlugin<TData, TData, TContext>;
    /**
     * Creates a monitoring wrapper plugin for observability
     *
     * Monitoring plugins provide detailed execution metrics, timing information,
     * and custom callbacks for tracking plugin performance and behavior.
     * Essential for production systems where you need visibility into plugin execution.
     *
     * @example
     * ```typescript
     * const monitoredPlugin = PluginFactory.withMonitoring(
     *   'critical-processor',
     *   async (data: CriticalData, context) => {
     *     // Important business logic
     *     return await processCriticalData(data);
     *   },
     *   {
     *     onStart: (input, context) => {
     *       context.logger.info('Starting critical processing', { inputId: input.id });
     *     },
     *     onSuccess: (output, duration, context) => {
     *       if (duration > 5000) {
     *         context.addWarning('SLOW_PROCESSING', `Processing took ${duration}ms`);
     *       }
     *       // Send metrics to monitoring system
     *       metrics.timing('critical_processor.duration', duration);
     *     },
     *     onError: (error, duration, context) => {
     *       // Alert on critical failures
     *       alerting.sendAlert('Critical processor failed', error);
     *     }
     *   }
     * );
     * ```
     */
    static withMonitoring<TInput, TOutput, TContext extends PluginContext = PluginContext>(name: string, processor: (input: TInput, context: TContext) => Promise<TOutput> | TOutput, options?: {
        version?: string;
        description?: string;
        onStart?: (input: TInput, context: TContext) => void | Promise<void>;
        onSuccess?: (output: TOutput, duration: number, context: TContext) => void | Promise<void>;
        onError?: (error: Error, duration: number, context: TContext) => void | Promise<void>;
    }): IPlugin<TInput, TOutput, TContext>;
    /**
     * Creates a circuit breaker plugin for fault tolerance
     *
     * Circuit breaker plugins protect against cascading failures by monitoring
     * error rates and temporarily disabling execution when failures exceed thresholds.
     *
     * @example
     * ```typescript
     * const protectedApiPlugin = PluginFactory.withCircuitBreaker(
     *   'external-api',
     *   async (request: ApiRequest, context) => {
     *     const response = await fetch(request.url);
     *     return response.json();
     *   },
     *   {
     *     failureThreshold: 5,     // Open circuit after 5 failures
     *     resetTimeoutMs: 60000,   // Try again after 1 minute
     *     monitoringWindowMs: 30000 // Monitor failures over 30 seconds
     *   }
     * );
     * ```
     */
    static withCircuitBreaker<TInput, TOutput, TContext extends PluginContext = PluginContext>(name: string, processor: (input: TInput, context: TContext) => Promise<TOutput> | TOutput, options: {
        failureThreshold: number;
        resetTimeoutMs: number;
        monitoringWindowMs?: number;
        version?: string;
        description?: string;
    }): IPlugin<TInput, TOutput, TContext>;
    /**
     * Creates a rate limiting plugin
     *
     * Rate limiting plugins control the frequency of plugin execution to
     * prevent overwhelming downstream systems or exceeding API limits.
     *
     * @example
     * ```typescript
     * const rateLimitedPlugin = PluginFactory.withRateLimit(
     *   'api-caller',
     *   async (request: ApiRequest, context) => {
     *     return await callExternalAPI(request);
     *   },
     *   {
     *     requestsPerSecond: 10,
     *     burstSize: 20,
     *     queueSize: 100
     *   }
     * );
     * ```
     */
    static withRateLimit<TInput, TOutput, TContext extends PluginContext = PluginContext>(name: string, processor: (input: TInput, context: TContext) => Promise<TOutput> | TOutput, options: {
        requestsPerSecond: number;
        burstSize?: number;
        queueSize?: number;
        version?: string;
        description?: string;
    }): IPlugin<TInput, TOutput, TContext>;
}

/**
 * Factory for creating plugin managers and builders
 *
 * Provides convenient factory methods for creating:
 * - Plugin managers with type safety
 * - Plugin manager builders for fluent configuration
 * - Type-safe managers with explicit input/output types
 */

declare class ManagerFactory {
    /**
     * Creates a new plugin manager instance
     *
     * @template TInput - Type of input data for plugins
     * @template TOutput - Type of output data from plugins
     * @template TMetadata - Type of execution metadata
     * @returns New plugin manager instance
     */
    static create<TInput = unknown, TOutput = unknown, TMetadata extends Record<string, unknown> = Record<string, unknown>>(): PluginManager<TInput, TOutput, TMetadata>;
    /**
     * Creates a new plugin manager builder for fluent configuration
     *
     * @template TInput - Type of input data for plugins
     * @template TOutput - Type of output data from plugins
     * @template TMetadata - Type of execution metadata
     * @returns New plugin manager builder instance
     */
    static builder<TInput = unknown, TOutput = unknown, TMetadata extends Record<string, unknown> = Record<string, unknown>>(): PluginManagerBuilder<TInput, TOutput, TMetadata>;
    /**
     * Creates type-safe factory methods for specific input/output types
     * Useful when working with known data structures
     *
     * @param inputType - Constructor for input type (for type inference)
     * @param outputType - Constructor for output type (for type inference)
     * @returns Object with typed create and builder methods
     */
    static typed<TInput, TOutput>(inputType: new () => TInput, outputType: new () => TOutput): {
        /**
         * Creates typed plugin manager
         */
        create: <TMetadata extends Record<string, unknown> = Record<string, unknown>>() => PluginManager<TInput, TOutput, TMetadata>;
        /**
         * Creates typed plugin manager builder
         */
        builder: <TMetadata extends Record<string, unknown> = Record<string, unknown>>() => PluginManagerBuilder<TInput, TOutput, TMetadata>;
    };
}

declare class PluginContextImpl<T extends Record<string, unknown> = Record<string, unknown>> implements PluginContext<T> {
    private readonly baseContext;
    private readonly pluginSettings;
    private readonly _shared;
    constructor(baseContext: PipelineContext<T>, pluginSettings: ReadonlyMap<string, PluginSettings>);
    /** Unique identifier for this execution */
    get executionId(): string;
    /** Execution start timestamp */
    get startTime(): number;
    /** Execution metadata provided by caller */
    get metadata(): Readonly<T>;
    /** Logger instance for plugin output */
    get logger(): Logger;
    /**
     * Adds a warning to the execution context
     * Warnings don't stop execution but are reported in results
     */
    addWarning(code: string, message: string, details?: unknown): void;
    /**
     * Internal method to access warnings (used by pipeline)
     */
    _getWarnings(): readonly PipelineWarning[];
    /** Read-only access to all plugin settings */
    get settings(): ReadonlyMap<string, PluginSettings>;
    /** Shared state map for inter-plugin communication */
    get shared(): Map<string, unknown>;
    /**
     * Retrieves settings for a specific plugin
     *
     * @param pluginName - Name of plugin to get settings for
     * @returns Plugin settings or undefined if not found
     */
    getSettings(pluginName: string): PluginSettings | undefined;
    /**
     * Stores a value in shared state for other plugins to access
     *
     * @template V - Type of value being stored
     * @param key - Unique key for the value
     * @param value - Value to store
     */
    share<V>(key: string, value: V): void;
    /**
     * Retrieves a value from shared state
     *
     * @template V - Expected type of the retrieved value
     * @param key - Key of value to retrieve
     * @returns Retrieved value or undefined if not found
     */
    retrieve<V>(key: string): V | undefined;
    /**
     * Checks if a key exists in shared state
     *
     * @param key - Key to check for existence
     * @returns True if key exists
     */
    hasShared(key: string): boolean;
    /**
     * Removes a value from shared state
     *
     * @param key - Key of value to remove
     * @returns True if value was removed, false if key didn't exist
     */
    deleteShared(key: string): boolean;
    /**
     * Clears all shared state
     * Useful for cleanup or isolation between executions
     */
    clearShared(): void;
    /**
     * Gets all shared state keys
     * Useful for debugging or state inspection
     *
     * @returns Array of all shared state keys
     */
    getSharedKeys(): readonly string[];
}

/**
 * Context Factory for creating plugin execution contexts
 *
 * Provides factory methods for creating properly configured plugin contexts:
 * - Creates base pipeline context with metadata
 * - Wraps with plugin-specific functionality
 * - Manages settings distribution to plugins
 */

declare class ContextFactory {
    /**
     * Creates a plugin context with metadata and settings map
     *
     * @template T - Type of execution metadata
     * @param metadata - Execution metadata to include in context
     * @param settingsMap - Map of plugin names to their settings
     * @returns Configured plugin context ready for execution
     */
    static create<T extends Record<string, unknown>>(metadata: T, settingsMap: ReadonlyMap<string, PluginSettings>): PluginContext<T>;
    /**
     * Creates a plugin context from an array of plugin settings
     * Convenience method for when settings are provided as array
     *
     * @template T - Type of execution metadata
     * @param metadata - Execution metadata to include in context
     * @param settings - Array of plugin name/settings pairs
     * @returns Configured plugin context ready for execution
     */
    static createWithSettings<T extends Record<string, unknown>>(metadata: T, settings: Array<{
        name: string;
        settings: PluginSettings;
    }>): PluginContext<T>;
}

/**
 * Validation utilities for plugin metadata, settings, and configurations
 *
 * Provides comprehensive validation for:
 * - Plugin metadata (name, version, dependencies, tags)
 * - Plugin settings (enabled state, priority, configuration)
 * - Semantic versioning compliance
 * - Naming conventions
 */

declare class ValidationUtils {
    /**
     * Validates plugin metadata for completeness and correctness
     * Checks name, version, dependencies, and tags
     *
     * @param metadata - Plugin metadata to validate
     * @throws {Error} When validation fails
     */
    static validatePluginMetadata(metadata: PluginMetadata): void;
    /**
     * Validates plugin settings for type correctness
     * Ensures enabled is boolean, priority is number, and config is object
     *
     * @param settings - Plugin settings to validate
     * @throws {Error} When validation fails
     */
    static validatePluginSettings(settings: PluginSettings): void;
    /**
     * Validates plugin name format and uniqueness requirements
     * Enforces alphanumeric characters, hyphens, and underscores only
     *
     * @param name - Plugin name to validate
     * @throws {Error} When validation fails
     */
    static validatePluginName(name: string): void;
    /**
     * Validates that a field is a non-empty string
     */
    private static validateRequiredStringField;
    /**
     * Validates semantic version format using regex
     * Supports major.minor.patch with optional pre-release and build metadata
     */
    private static isValidSemVer;
    /**
     * Validates array of plugin dependencies
     * Ensures each dependency follows naming conventions
     */
    private static validateDependencies;
    /**
     * Validates array of plugin tags
     * Ensures each tag is a non-empty string
     */
    private static validateTags;
}

/**
 * Error handling utilities and custom error classes for plugin system
 *
 * Provides structured error types for different failure scenarios:
 * - PluginError: General plugin execution failures
 * - PluginRegistrationError: Registration-specific failures
 * - PluginDependencyError: Dependency resolution failures
 * - PluginValidationError: Input/configuration validation failures
 */
/**
 * Base error class for plugin-related failures
 * Captures the plugin name and original error for debugging
 */
declare class PluginError extends Error {
    readonly pluginName: string;
    readonly originalError?: Error | undefined;
    constructor(message: string, pluginName: string, originalError?: Error | undefined);
}
/**
 * Error thrown when plugin registration fails
 * Typically due to naming conflicts or invalid metadata
 */
declare class PluginRegistrationError extends Error {
    readonly pluginName: string;
    constructor(message: string, pluginName: string);
}
/**
 * Error thrown when plugin dependencies cannot be resolved
 * Indicates missing or disabled required dependencies
 */
declare class PluginDependencyError extends Error {
    readonly pluginName: string;
    readonly missingDependency: string;
    constructor(message: string, pluginName: string, missingDependency: string);
}
/**
 * Error thrown when plugin validation fails
 * Indicates specific field or configuration issues
 */
declare class PluginValidationError extends Error {
    readonly pluginName: string;
    readonly field: string;
    constructor(message: string, pluginName: string, field: string);
}
/**
 * Utility class for error handling and creation
 * Provides consistent error wrapping and type checking
 */
declare class ErrorUtils {
    /**
     * Wraps any error as a PluginError if not already one
     * Preserves the original error chain for debugging
     */
    static wrapPluginError(error: Error, pluginName: string): PluginError;
    /**
     * Type guard to check if error is a PluginError
     */
    static isPluginError(error: Error): error is PluginError;
    /**
     * Extracts plugin name from plugin-related errors
     * Returns undefined for non-plugin errors
     */
    static extractPluginName(error: Error): string | undefined;
    /**
     * Factory method for creating registration errors
     */
    static createRegistrationError(pluginName: string, reason: string): PluginRegistrationError;
    /**
     * Factory method for creating dependency errors
     */
    static createDependencyError(pluginName: string, missingDependency: string): PluginDependencyError;
    /**
     * Factory method for creating validation errors
     */
    static createValidationError(pluginName: string, field: string, reason: string): PluginValidationError;
}

/**
 * Harmony Plugin Manager - A comprehensive TypeScript plugin system
 *
 * A type-safe plugin system with lifecycle management, dependency resolution,
 * and comprehensive error handling using modular architecture.
 *
 * ## Quick Start
 *
 * ```typescript
 * import { createPluginManager, simplePlugin } from 'harmony-plugin-manager';
 *
 * // Create a simple text processing plugin
 * const uppercasePlugin = simplePlugin(
 *   { name: 'uppercase', version: '1.0.0', description: 'Converts text to uppercase' },
 *   (input: string) => input.toUpperCase()
 * );
 *
 * // Create and configure the manager
 * const manager = createPluginManager<string, string>()
 *   .register(uppercasePlugin)
 *   .build();
 *
 * // Execute the pipeline
 * const result = await manager.execute('hello world', {});
 * console.log(result.results[0].output); // "HELLO WORLD"
 * ```
 *
 * ## Advanced Usage
 *
 * ```typescript
 * // Using the builder pattern for complex configurations
 * const manager = createPluginBuilder<string, string>()
 *   .plugin(validationPlugin, { priority: 100 })
 *   .plugin(transformPlugin, { priority: 50 })
 *   .when(process.env.NODE_ENV === 'development', debugPlugin)
 *   .group({
 *     tag: 'formatting',
 *     items: [
 *       { plugin: trimPlugin },
 *       { plugin: normalizePlugin }
 *     ]
 *   })
 *   .build();
 * ```
 *
 * ## Key Concepts
 *
 * - **Plugins**: Self-contained processing units with metadata and lifecycle hooks
 * - **Manager**: Orchestrates plugin execution with dependency resolution
 * - **Context**: Provides shared state, logging, and configuration access
 * - **Pipeline**: Executes plugins in dependency order with error handling
 *
 * @packageDocumentation
 */

/**
 * Creates a new plugin manager instance with type safety
 *
 * The plugin manager is the core orchestrator that handles plugin registration,
 * dependency resolution, and execution. It provides a clean API for managing
 * complex plugin workflows with error handling and performance monitoring.
 *
 * @template TInput - Type of data that plugins will receive as input
 * @template TOutput - Type of data that plugins will produce as output
 * @template TMetadata - Type of execution metadata passed to plugins
 *
 * @returns A new PluginManager instance ready for plugin registration
 *
 * @example
 * ```typescript
 * // Basic string processing manager
 * const textManager = createPluginManager<string, string>();
 *
 * // Complex data transformation manager
 * interface UserData { id: string; name: string; email: string; }
 * interface ProcessedUser { id: string; displayName: string; domain: string; }
 *
 * const userManager = createPluginManager<UserData, ProcessedUser, {
 *   requestId: string;
 *   userId: string;
 * }>();
 * ```
 *
 * @example
 * ```typescript
 * // Complete workflow example
 * const manager = createPluginManager<string, string>()
 *   .register(validationPlugin, { priority: 100 })
 *   .register(transformPlugin, { priority: 50 })
 *   .register(outputPlugin, { priority: 10 })
 *   .build();
 *
 * const result = await manager.execute('input data', {
 *   requestId: 'req-123',
 *   timestamp: Date.now()
 * });
 *
 * if (result.success) {
 *   console.log('Processing completed:', result.results);
 * } else {
 *   console.error('Processing failed:', result.errors);
 * }
 * ```
 */
declare function createPluginManager<TInput = unknown, TOutput = unknown, TMetadata extends Record<string, unknown> = Record<string, unknown>>(): PluginManager<TInput, TOutput, TMetadata>;
/**
 * Creates a new plugin manager builder for fluent configuration
 *
 * The builder pattern provides a more expressive way to configure complex
 * plugin arrangements. It offers methods for conditional registration,
 * grouping, priority setting, and validation before building the final manager.
 *
 * @template TInput - Type of data that plugins will receive as input
 * @template TOutput - Type of data that plugins will produce as output
 * @template TMetadata - Type of execution metadata passed to plugins
 *
 * @returns A new PluginManagerBuilder instance for fluent configuration
 *
 * @example
 * ```typescript
 * // Basic builder usage
 * const manager = createPluginBuilder<string, string>()
 *   .plugin(trimPlugin)
 *   .plugin(uppercasePlugin)
 *   .build();
 * ```
 *
 * @example
 * ```typescript
 * // Advanced builder with conditional logic and grouping
 * const isDevelopment = process.env.NODE_ENV === 'development';
 * const enableLogging = process.env.ENABLE_LOGGING === 'true';
 *
 * const manager = createPluginBuilder<ApiRequest, ApiResponse>()
 *   // High priority validation
 *   .withPriority(100, authPlugin)
 *   .withPriority(90, validationPlugin)
 *
 *   // Conditional development plugins
 *   .when(isDevelopment, debugPlugin)
 *   .when(enableLogging, loggingPlugin)
 *
 *   // Grouped processing plugins
 *   .group({
 *     tag: 'data-processing',
 *     items: [
 *       { plugin: transformPlugin, settings: { priority: 50 } },
 *       { plugin: enrichPlugin, settings: { priority: 40 } },
 *       { plugin: validateOutputPlugin, settings: { priority: 30 } }
 *     ]
 *   })
 *
 *   // Response formatting
 *   .withPriority(10, formatResponsePlugin)
 *
 *   .validate() // Optional: validate configuration before build
 *   .build();
 * ```
 *
 * @example
 * ```typescript
 * // Builder with environment-specific configuration
 * const createApiManager = (environment: 'dev' | 'staging' | 'prod') => {
 *   const builder = createPluginBuilder<ApiRequest, ApiResponse>()
 *     .plugin(corePlugin)
 *     .plugin(businessLogicPlugin);
 *
 *   if (environment !== 'prod') {
 *     builder.plugin(testingPlugin);
 *   }
 *
 *   if (environment === 'dev') {
 *     builder
 *       .plugin(debugPlugin)
 *       .plugin(mockDataPlugin);
 *   }
 *
 *   return builder.build();
 * };
 * ```
 */
declare function createPluginBuilder<TInput = unknown, TOutput = unknown, TMetadata extends Record<string, unknown> = Record<string, unknown>>(): PluginManagerBuilder<TInput, TOutput, TMetadata>;
/**
 * Creates a simple plugin with minimal configuration
 *
 * This is the quickest way to create a plugin for basic data transformation.
 * The plugin will have default lifecycle methods and error handling, while
 * allowing you to focus on the core processing logic.
 *
 * @template TInput - Type of input data the plugin processes
 * @template TOutput - Type of output data the plugin produces
 * @template TContext - Type of plugin context (usually PluginContext)
 *
 * @param metadata - Plugin identification and dependency information
 * @param execute - The main processing function that transforms input to output
 * @param hooks - Optional lifecycle hooks for advanced plugin behavior
 *
 * @returns A fully configured plugin ready for registration
 *
 * @example
 * ```typescript
 * // Simple text transformation plugin
 * const uppercasePlugin = simplePlugin(
 *   {
 *     name: 'uppercase-transformer',
 *     version: '1.0.0',
 *     description: 'Converts text to uppercase'
 *   },
 *   (input: string) => input.toUpperCase()
 * );
 * ```
 *
 * @example
 * ```typescript
 * // Plugin with async processing
 * const apiCallPlugin = simplePlugin(
 *   {
 *     name: 'api-enricher',
 *     version: '1.2.0',
 *     description: 'Enriches data with external API calls',
 *     dependencies: ['validation-plugin'] // Runs after validation
 *   },
 *   async (userData: UserData, context) => {
 *     context.logger.info(`Processing user: ${userData.id}`);
 *
 *     const response = await fetch(`/api/users/${userData.id}/details`);
 *     const enrichedData = await response.json();
 *
 *     return {
 *       ...userData,
 *       ...enrichedData
 *     };
 *   }
 * );
 * ```
 *
 * @example
 * ```typescript
 * // Plugin with lifecycle hooks for resource management
 * const databasePlugin = simplePlugin(
 *   {
 *     name: 'database-writer',
 *     version: '2.1.0',
 *     description: 'Persists data to database'
 *   },
 *   async (data: ProcessedData, context) => {
 *     const db = context.retrieve<Database>('database-connection');
 *     if (!db) {
 *       throw new Error('Database connection not available');
 *     }
 *
 *     const result = await db.save(data);
 *     context.logger.info(`Saved record with ID: ${result.id}`);
 *
 *     return result;
 *   },
 *   {
 *     // Initialize database connection
 *     initialize: async (context) => {
 *       const config = context.getSettings('database-writer')?.config;
 *       const db = await createDatabaseConnection(config);
 *       context.share('database-connection', db);
 *       context.logger.info('Database connection established');
 *     },
 *
 *     // Clean up resources
 *     cleanup: async (context) => {
 *       const db = context.retrieve<Database>('database-connection');
 *       if (db) {
 *         await db.close();
 *         context.logger.info('Database connection closed');
 *       }
 *     },
 *
 *     // Handle errors gracefully
 *     onError: async (error, context) => {
 *       context.logger.error('Database operation failed', {
 *         error: error.message,
 *         stack: error.stack
 *       });
 *
 *       // Could implement retry logic, fallback storage, etc.
 *     }
 *   }
 * );
 * ```
 *
 * @example
 * ```typescript
 * // Plugin with context usage for shared state
 * const cachePlugin = simplePlugin(
 *   {
 *     name: 'cache-manager',
 *     version: '1.0.0',
 *     description: 'Caches processed results'
 *   },
 *   async (input: string, context) => {
 *     const cacheKey = `processed_${input}`;
 *
 *     // Try to get from cache first
 *     const cached = context.retrieve<string>(cacheKey);
 *     if (cached) {
 *       context.logger.debug(`Cache hit for key: ${cacheKey}`);
 *       return cached;
 *     }
 *
 *     // Process the input (expensive operation)
 *     const processed = await expensiveProcessing(input);
 *
 *     // Store in cache for future use
 *     context.share(cacheKey, processed);
 *     context.logger.debug(`Cached result for key: ${cacheKey}`);
 *
 *     return processed;
 *   }
 * );
 * ```
 */
declare function simplePlugin<TInput, TOutput, TContext extends PluginContext = PluginContext>(metadata: PluginMetadata, execute: (input: TInput, context: TContext) => Promise<TOutput> | TOutput, hooks?: PluginHooks<TInput, TOutput, TContext>): IPlugin<TInput, TOutput, TContext>;

export { BasePlugin, ContextFactory, DependencyResolver, ErrorUtils, ManagerFactory, BasePlugin as Plugin, PluginContextImpl, PluginDependencyError, PluginError, PluginFactory, PluginManager, PluginManagerBuilder, PluginProcessor, PluginRegistration, PluginRegistrationError, PluginValidationError, ValidationUtils, createPluginBuilder, createPluginManager, simplePlugin };
export type { IPlugin, IPluginManager, ManagerResult, PluginContext, PluginHooks, PluginMetadata, PluginResult, PluginSettings };
