/**
 * This file was automatically generated by xBuild.
 * DO NOT EDIT MANUALLY.
 */

import { BuildOptions, BuildResult, Loader, Message, OnEndResult, OnLoadArgs, OnLoadResult, OnResolveArgs, OnResolveResult, OnStartResult, PartialMessage, Platform, PluginBuild } from 'esbuild';
import ts, { CompilerOptions, DiagnosticCategory, IScriptSnapshot, LanguageService, ParsedCommandLine, ResolvedModuleWithFailedLookupLocations, SourceFile } from 'typescript';
import { IncomingMessage, ServerResponse } from 'http';
import { ResolveMetadataInterface as xMapResolveMetadataInterface, ResolveOptionsInterface } from '@remotex-labs/xmap';
import { Options } from 'yargs';

/**
 * Orchestrates the build process across multiple variants with lifecycle management and configuration.
 *
 * @remarks
 * The `BuildService` is the primary service for managing multi-variant builds in xBuild.
 * It handles configuration changes, variant lifecycle, type checking, and build execution
 * with support for hot reloading and file watching.
 *
 * **Key responsibilities**:
 * - Manages multiple build variants (e.g., production, development, testing)
 * - Provides reactive configuration updates through subscription system
 * - Coordinates lifecycle hooks (onStart, onEnd) across all variants
 * - Handles macro transformation and directive processing
 * - Supports incremental builds and file touch notifications
 * - Aggregates build results and type checking diagnostics
 *
 * **Architecture**:
 * Each variant is managed by a {@link VariantService} instance with its own:
 * - esbuild configuration and context
 * - TypeScript language service
 * - Lifecycle provider for hooks and plugins
 * - Build state and watch mode support
 *
 * The service uses a subscription pattern to react to configuration changes,
 * automatically creating new variants or disposing removed ones.
 *
 * @example Basic usage
 * ```ts
 * const buildService = new BuildService({
 *   variants: {
 *     production: {
 *       esbuild: { minify: true, sourcemap: false }
 *     },
 *     development: {
 *       esbuild: { minify: false, sourcemap: true }
 *     }
 *   }
 * });
 *
 * // Build all variants
 * const results = await buildService.build();
 * console.log(results.production.errors);
 * ```
 *
 * @example With lifecycle hooks
 * ```ts
 * const buildService = new BuildService(config);
 *
 * buildService.onStart = (context) => {
 *   console.log(`Building variant: ${context.variantName}`);
 * };
 *
 * buildService.onEnd = (context) => {
 *   console.log(`Completed ${context.variantName}: ${context.result.errors.length} errors`);
 * };
 *
 * await buildService.build();
 * ```
 *
 * @example Configuration reload
 * ```ts
 * const buildService = new BuildService(initialConfig);
 *
 * // Reload with new configuration
 * buildService.reload({
 *   variants: {
 *     production: { esbuild: { target: 'es2020' } },
 *     staging: { esbuild: { minify: true } }
 *   }
 * });
 * // Old variants disposed, new ones created
 * ```
 *
 * @example Type checking
 * ```ts
 * const buildService = new BuildService(config);
 * const diagnostics = await buildService.typeChack();
 *
 * for (const [variant, errors] of Object.entries(diagnostics)) {
 *   console.log(`${variant}: ${errors.length} type errors`);
 * }
 * ```
 *
 * @see {@link VariantService} for individual variant management
 * @see {@link ConfigurationService} for configuration handling
 * @see {@link LifecycleProvider} for hook management
 *
 * @since 2.0.0
 */
declare class BuildService {
    private argv;
    /**
     * Callback invoked when a build completes for any variant.
     *
     * @remarks
     * Set via the `onEnd` setter. Called after each variant's build finishes,
     * providing access to build results, errors, warnings, and metadata.
     *
     * @since 2.0.0
     */
    private onEndCallback?;
    /**
     * Callback invoked when a build starts for any variant.
     *
     * @remarks
     * Set via the `onStart` setter. Called before each variant's build begins,
     * after macro metadata analysis completes.
     *
     * @since 2.0.0
     */
    private onStartCallback?;
    /**
     * Map of variant names to their service instances.
     *
     * @remarks
     * Contains all active build variants. Variants are created during construction
     * and updated when configuration changes via {@link reload} or {@link setConfiguration}.
     *
     * @since 2.0.0
     */
    private variants;
    /**
     * Configuration service managing build settings and variant definitions.
     *
     * @remarks
     * Injected singleton that provides reactive configuration updates through
     * its subscription system. Changes trigger automatic variant recreation.
     *
     * @since 2.0.0
     */
    private readonly configuration;
    /**
     * Creates a new BuildService instance with optional configuration and command-line arguments.
     *
     * @param argv - Command-line arguments passed to variant services (default: empty object)
     *
     * @remarks
     * The constructor:
     * 1. Accepts optional initial configuration
     * 2. Stores command-line arguments for variant initialization
     * 3. Subscribes to configuration changes via {@link parseVariants}
     * 4. Automatically creates variants defined in the configuration
     *
     * Configuration can be provided later via {@link reload} or {@link setConfiguration}
     * if not supplied during construction.
     *
     * @since 2.0.0
     */
    constructor(argv?: Record<string, unknown>);
    /**
     * Gets the current complete build configuration.
     *
     * @returns The active build configuration including all variants and common settings
     *
     * @remarks
     * Retrieves the immutable snapshot of the current configuration from the
     * configuration service. Changes to the returned object do not affect
     * the actual configuration - use {@link setConfiguration} or {@link reload} instead.
     *
     * @since 2.0.0
     */
    get config(): BuildConfigInterface;
    /**
     * Sets the callback to invoke when any variant build completes.
     *
     * @param callback - Function receiving the result context with build output and metadata
     *
     * @remarks
     * The callback receives a {@link ResultContextInterface} containing:
     * - Variant name
     * - Build result (errors, warnings, outputs)
     * - Metadata files and outputs
     * - Timestamp and duration
     *
     * Called after the build finishes but before promises resolve.
     *
     * @example
     * ```ts
     * buildService.onEnd = (context) => {
     *   const { variantName, result } = context;
     *   console.log(`✓ ${variantName}: ${result.errors.length} errors`);
     * };
     * ```
     *
     * @since 2.0.0
     */
    set onEnd(callback: OnEndType);
    /**
     * Sets the callback to invoke when any variant build starts.
     *
     * @param callback - Function receiving the build context with file and variant information
     *
     * @remarks
     * The callback receives a {@link BuildContextInterface} containing:
     * - Variant name
     * - File path being processed
     * - Build stage and metadata
     * - Loader type
     *
     * Called after macro analysis but before transformation begins.
     *
     * @example
     * ```ts
     * buildService.onStart = (context) => {
     *   console.log(`Building ${context.args.path} for ${context.variantName}`);
     * };
     * ```
     *
     * @since 2.0.0
     */
    set onStart(callback: OnStartType);
    /**
     * Reloads the build configuration and updates variants accordingly.
     *
     * @param config - Optional new configuration to replace the current one
     * @param clearCache - Whether to clear cached files and TypeScript language service state before reloading
     *
     * @remarks
     * The reload process:
     * 1. Optionally clears cached file state and TypeScript language service data
     * 2. Replaces configuration if provided
     * 3. Compares new variant names with existing ones
     * 4. Disposes variants no longer in configuration
     * 5. Creates new variants from the updated configuration
     * 6. Existing variants with matching names continue unchanged
     *
     * This is useful for hot-reloading configuration files without restarting the build process.
     *
     * @example
     * ```ts
     * // Reload with a new staging variant
     * buildService.reload({
     *   config: {
     *     variants: {
     *       ...buildService.config.variants,
     *       staging: { esbuild: { minify: true } }
     *     }
     *   }
     * });
     * ```
     *
     * @example
     * ```ts
     * // Reload and clear cached file/type-checking state first
     * buildService.reload({
     *   clearCache: true
     * });
     * ```
     *
     * @since 2.3.0
     */
    reload({ config, clearCache }?: ReloadOptionsInterface): void;
    /**
     * Notifies all variants that specific files have been modified.
     *
     * @param files - Array of file paths that have changed
     *
     * @remarks
     * Propagates file change notifications to all variant services, triggering
     * incremental rebuilds in watch mode. Each variant's watch service handles
     * the actual rebuild logic.
     *
     * Typically used by file watchers or development servers to trigger hot reloads.
     *
     * @example
     * ```ts
     * // File watcher integration
     * watcher.on('change', (changedFiles) => {
     *   buildService.touchFiles(changedFiles);
     * });
     * ```
     *
     * @see {@link VariantService.touchFiles}
     *
     * @since 2.0.0
     */
    touchFiles(files: Array<string>): void;
    /**
     * Partially updates the build configuration without replacing it entirely.
     *
     * @param config - Partial configuration to merge with the current configuration
     *
     * @remarks
     * Performs a shallow merge of the provided configuration with the current one.
     * Use {@link reload} for deep configuration replacement or variant restructuring.
     *
     * Common use cases:
     * - Toggling minification
     * - Updating define constants
     * - Modifying common build options
     *
     * @example
     * ```ts
     * // Enable minification for all variants
     * buildService.setConfiguration({
     *   common: { esbuild: { minify: true } }
     * });
     * ```
     *
     * @see {@link reload} for full configuration replacement
     *
     * @since 2.0.0
     */
    setConfiguration(config: Partial<BuildConfigInterface>): void;
    /**
     * Performs TypeScript type checking across all variants.
     *
     * @returns Promise resolving to a map of variant names to their diagnostic results
     *
     * @remarks
     * Runs the TypeScript compiler's diagnostic checker for each variant in parallel.
     * Returns all type errors, warnings, and suggestions without failing the build.
     *
     * **Note**: Method name has a typo - should be `typeCheck` but kept for backward compatibility.
     *
     * Useful for:
     * - Pre-build validation
     * - CI/CD type checking pipelines
     * - IDE integration and diagnostics display
     *
     * @example
     * ```ts
     * const diagnostics = await buildService.typeChack();
     *
     * for (const [variant, errors] of Object.entries(diagnostics)) {
     *   if (errors.length > 0) {
     *     console.error(`${variant} has ${errors.length} type errors`);
     *     errors.forEach(err => console.error(err.messageText));
     *   }
     * }
     * ```
     *
     * @see {@link DiagnosticInterface}
     * @see {@link VariantService.check}
     *
     * @since 2.0.0
     */
    typeChack(): Promise<Record<string, DiagnosticInterface[]>>;
    /**
     * Executes the build process for all or specific variants,
     * respecting `dependOn` ordering and running independent variants in parallel.
     *
     * @param names - Optional array of variant names to build (builds all if omitted)
     *
     * @returns Promise resolving to a map of variant names to their enhanced build results
     *
     * @throws xBuildError - When a circular dependency is detected before any build starts
     * @throws AggregateError - When any variant build fails, containing all error details
     *
     * @remarks
     * The build process:
     * 1. Validates the dependency graph — throws immediately on circular deps
     * 2. Launches all requested variants concurrently
     * 3. Each variant awaits its `dependOn` dependencies before running
     * 4. Collects results and errors from each variant without stopping others
     * 5. Enhances build results with additional metadata
     * 6. Throws AggregateError if any builds failed
     *
     * **Dependency resolution**:
     * - `dependOn` variants always finish before the dependent variant starts
     * - A shared dependency (e.g. two variants both depending on `types`) builds
     *   only once — subsequent dependents await the same running promise
     * - Independent variants run fully in parallel
     *
     * **Error handling**:
     * - Build failures don't stop other variants from building
     * - All errors are collected into {@link BuildTreeInterface.errors} and thrown
     *   together after all builds complete
     * - Supports both esbuild-specific errors and generic JavaScript errors
     *
     * **Result enhancement**:
     * Build results are processed by {@link enhancedBuildResult} to provide
     * structured error and warning information.
     *
     * @example Build all variants
     * ```ts
     * try {
     *   const results = await buildService.build();
     *   console.log(`Built ${Object.keys(results).length} variants`);
     * } catch (error) {
     *   if (error instanceof AggregateError) {
     *     error.errors.forEach(err => console.error(err.message));
     *   }
     * }
     * ```
     *
     * @example Build specific variants
     * ```ts
     * const results = await buildService.build(['production', 'staging']);
     * // Only production and staging variants are built
     * ```
     *
     * @example With dependency ordering
     * ```ts
     * // Given: main dependOn shared, shared dependOn types
     * // Build order: types → shared → main (dependencies first)
     * const results = await buildService.build();
     * ```
     *
     * @see {@link buildVariant} for per-variant execution and caching logic
     * @see {@link BuildTreeInterface}
     * @see {@link enhancedBuildResult}
     * @see {@link BuildResultInterface}
     * @see {@link VariantService.build}
     * @see {@link validateDependencies} for circular dependency detection
     *
     * @since 2.4.0
     */
    build(names?: Array<string>): Promise<Record<string, BuildResultInterface>>;
    /**
     * Triggers the onEnd callback when a variant build completes.
     *
     * @param context - The result context containing build output and metadata
     *
     * @remarks
     * Internal handler that safely invokes the user-provided onEnd callback if set.
     * Called by variant lifecycle providers after each build finishes.
     *
     * @since 2.0.0
     */
    private onEndTrigger;
    /**
     * Triggers the onStart callback and performs macro analysis before a variant build starts.
     *
     * @param context - The build context containing file and variant information
     *
     * @returns Promise resolving to the load result after macro metadata analysis
     *
     * @throws Error - Propagates errors from macro analysis that aren't AggregateErrors
     *
     * @remarks
     * Internal handler that:
     * 1. Analyzes macro metadata for the file being built
     * 2. Invokes the user-provided onStart callback if set
     * 3. Returns the analysis result to the build pipeline
     * 4. Converts AggregateErrors to esbuild-compatible error format
     *
     * The macro analysis prepares directive information ($$ifdef, $$inline, etc.)
     * that will be used during the transformation phase.
     *
     * @see {@link analyzeMacroMetadata}
     *
     * @since 2.0.0
     */
    private onStartTrigger;
    /**
     * Disposes and removes variants by name.
     *
     * @param dispose - Array of variant names to dispose
     *
     * @remarks
     * Cleanly shuts down variant services and removes them from the internal map.
     * Called during configuration reload to remove variants no longer in config.
     *
     * Each variant's dispose method:
     * - Stops watch mode if active
     * - Cleans up esbuild contexts
     * - Releases TypeScript language service resources
     *
     * @since 2.0.0
     */
    private disposeVariants;
    /**
     * Compares two objects and returns keys present in the second but not the first.
     *
     * @param obj1 - Reference object (usually new configuration)
     * @param obj2 - Comparison object (usually existing variants)
     *
     * @returns Array of keys present in obj2 but missing in obj1
     *
     * @remarks
     * Used to identify variants that should be disposed during configuration reload.
     * If a variant exists in the service but not in the new configuration, it's removed.
     *
     * @since 2.0.0
     */
    private compareKeys;
    /**
     * Creates variant service instances from the current configuration.
     *
     * @throws xBuildError - When no variants are defined in the configuration
     *
     * @remarks
     * Invoked by the configuration subscription whenever configuration changes.
     * For each variant in the configuration:
     * 1. Skips if the variant already exists (prevents recreation)
     * 2. Creates a new LifecycleProvider with hooks
     * 3. Attaches onStart and onEnd listeners
     * 4. Creates VariantService with configuration
     * 5. Registers macro transformer directive
     *
     * The lifecycle hooks enable:
     * - Build start/end notifications
     * - Macro analysis and transformation
     * - Custom plugin integration
     *
     * @see {@link VariantService}
     * @see {@link LifecycleProvider}
     * @see {@link transformerDirective}
     *
     * @since 2.0.0
     */
    private parseVariants;
    /**
     * Returns the normalized `dependOn` list for a variant.
     *
     * @param variantName - The variant to look up
     *
     * @returns Array of dependency variant names, empty if none defined
     *
     * @remarks
     * Normalizes the `dependOn` field from the variant configuration into
     * a consistent array form, since the field accepts either a single
     * string or an array of strings.
     *
     * @see {@link buildVariant}
     * @see {@link validateDependencies}
     *
     * @since 2.4.0
     */
    private getDependOn;
    /**
     * Validates the dependency graph for all or specific variants before building starts.
     *
     * @param names - Optional subset of variant names to validate (validates all if omitted)
     *
     * @throws xBuildError - When a circular dependency is detected, with the full cycle
     * path included in the message (e.g. `Circular dependency detected: main → shared → main`)
     *
     * @remarks
     * Performs a depth-first traversal of the dependency graph using two sets:
     * - `visited` — variants fully processed, skipped on revisit
     * - `inStack` — variants in the current traversal path, used to detect cycles
     *
     * Dependencies that exist in `dependOn` but have no matching variant instance
     * in {@link variants} are silently skipped.
     *
     * Called by {@link build} before any variant starts, ensuring the entire
     * graph is valid before any work begins.
     *
     * @see {@link build}
     * @see {@link getDependOn}
     *
     * @since 2.4.0
     */
    private validateDependencies;
    /**
     * Executes the build for a single variant after all its dependencies resolve.
     *
     * @param name - Variant name to build
     * @param ctx - Isolated build context for this {@link build} invocation
     *
     * @remarks
     * Called exclusively by {@link buildVariant} after the promise is registered
     * in {@link BuildTreeInterface.cache}, preventing re-entry.
     *
     * Awaits all `dependOn` dependencies concurrently via `Promise.all` before
     * running the variant. Dependencies missing from {@link variants} are silently skipped.
     *
     * Errors are pushed into {@link BuildTreeInterface.errors} rather than thrown,
     * so all variants attempt to build even if a sibling fails. Handles both
     * esbuild-specific errors via {@link isBuildResultError} and generic JavaScript errors.
     *
     * @see {@link buildVariant}
     * @see {@link getDependOn}
     * @see {@link isBuildResultError}
     * @see {@link BuildTreeInterface}
     * @see {@link enhancedBuildResult}
     *
     * @since 2.4.0
     */
    private executeBuild;
    /**
     * Builds a single variant, first awaiting any `dependOn` dependencies.
     *
     * @param name - Variant name to build
     * @param ctx - Isolated build context for this {@link build} invocation,
     * carrying the promise cache, error list, and results map
     *
     * @returns Promise that resolves when the variant and all its dependencies finish
     *
     * @remarks
     * Stores its promise in {@link BuildTreeInterface.cache} on first call so any
     * subsequent caller depending on the same variant awaits the already-running
     * promise rather than triggering a duplicate build.
     *
     * Delegates actual execution to {@link executeBuild} after registering the promise,
     * ensuring the cache is populated before any async work begins.
     *
     * @see {@link build}
     * @see {@link executeBuild}
     * @see {@link BuildTreeInterface}
     *
     * @since 2.4.0
     */
    private buildVariant;
}
/**
 * Options used to reload the build service configuration.
 *
 * @remarks
 * These options control how configuration reload behaves:
 * - `config` replaces the current build configuration
 * - `clearCache` clears cached file and TypeScript language service state before reloading
 *
 * @since 2.3.0
 */
interface ReloadOptionsInterface {
    /**
     * Optional new configuration to replace the current one.
     *
     * @remarks
     * When provided, the build service reloads using this configuration
     * before recalculating variants.
     *
     * @since 2.3.0
     */
    config?: PartialBuildConfigType;
    /**
     * Whether to clear cached files and TypeScript language service state before reloading.
     *
     * @remarks
     * When enabled, cached file tracking and language service state are reset
     * before the configuration is reloaded.
     *
     * @since 2.3.0
     */
    clearCache?: boolean;
}
/**
 * Isolated state container for a single {@link BuildService.build} invocation.
 *
 * @remarks
 * Created fresh on every `build()` call to ensure concurrent watch-mode
 * rebuilds cannot share or overwrite each other's state.
 *
 * Passed through {@link BuildService.buildVariant} to carry the promise
 * cache, accumulated errors, and collected results across the full
 * dependency graph traversal.
 *
 * @see {@link BuildService.build}
 * @see {@link BuildService.buildVariant}
 *
 * @since 2.4.0
 */
interface BuildTreeInterface {
    /**
     * Promise cache keyed by variant name.
     *
     * @remarks
     * Ensures each variant builds exactly once per `build()` call.
     * Subsequent callers depending on the same variant await the
     * already-running promise instead of triggering a duplicate build.
     *
     * @since 2.4.0
     */
    cache: Map<string, Promise<void>>;
    /**
     * Accumulated build errors across all variants.
     *
     * @remarks
     * Errors are pushed here rather than thrown immediately, so all
     * variants attempt to build even if a sibling fails. Thrown together
     * as an `AggregateError` after all builds complete.
     *
     * @since 2.4.0
     */
    errors: Array<Error>;
    /**
     * Collected build results keyed by variant name.
     *
     * @remarks
     * Populated by {@link BuildService.buildVariant} as each variant
     * finishes. Only contains results for variants that built successfully.
     *
     * @since 2.4.0
     */
    results: Record<string, BuildResultInterface>;
}
/**
 * Extended build result interface with normalized error and warning arrays.
 *
 * @remarks
 * This interface extends esbuild's {@link BuildResult} while replacing the `errors` and `warnings`
 * properties with normalized Error instances instead of esbuild's Message objects. This normalization
 * provides consistent error handling throughout the xBuild system with proper stack traces, formatting,
 * and error classification.
 *
 * **Key differences from esbuild's BuildResult**:
 * - `errors`: Changed from `Message[]` to `Error[]` with normalized error types
 * - `warnings`: Changed from `Message[]` to `Error[]` with normalized error types
 * - All other properties (metafile, outputFiles, mangleCache) are preserved unchanged
 *
 * **Benefits of normalization**:
 * - Consistent error handling across different error sources (esbuild, TypeScript, VM runtime)
 * - Proper error inheritance and type checking
 * - Rich stack trace information with source mapping
 * - Formatted error output with syntax highlighting
 * - Integration with xBuild's custom error classes
 *
 * The normalized errors may include:
 * - {@link TypesError} for TypeScript type checking failures
 * - {@link xBuildError} for text errors during build hooks
 * - {@link esBuildError} for esbuild compilation errors with location information
 * - {@link VMRuntimeError} for runtime errors during build hooks
 * - {@link xBuildBaseError} for custom build system errors
 *
 * @example
 * ```ts
 * const result: BuildResultInterface = {
 *   errors: [
 *     new esBuildError(esbuildMessage),
 *     new TypesError('Type checking failed', diagnostics)
 *   ],
 *   warnings: [
 *     new xBuildError('Deprecation warning')
 *   ],
 *   metafile: { ... },
 *   outputFiles: [ ... ],
 *   mangleCache: { ... }
 * };
 * ```
 *
 * @see {@link BuildResult} from esbuild for the base interface
 *
 * @since 2.0.0
 */
interface BuildResultInterface extends Omit<BuildResult, 'errors' | 'warnings'> {
    /**
     * Array of normalized error instances encountered during the build.
     *
     * @remarks
     * Contains Error instances converted from esbuild messages and other error sources.
     * Unlike esbuild's native error array which contains Message objects, this array
     * contains fully normalized Error instances with proper stack traces and formatting.
     *
     * Errors in this array may originate from:
     * - Compilation errors (syntax, resolution failures)
     * - Type checking failures
     * - Build hook execution errors
     * - Plugin errors
     *
     * @example
     * ```ts
     * if (result.errors.length > 0) {
     *   console.error(`Build failed with ${result.errors.length} errors`);
     *   result.errors.forEach(err => console.error(err.stack));
     * }
     * ```
     *
     * @since 2.0.0
     */
    errors: Array<Error>;
    /**
     * Array of normalized warning instances encountered during the build.
     *
     * @remarks
     * Contains Error instances converted from esbuild warning messages and other warning sources.
     * Unlike esbuild's native warning array which contains Message objects, this array
     * contains fully normalized Error instances with proper stack traces and formatting.
     *
     * Warnings indicate non-fatal issues that don't prevent build completion but may
     * require attention, such as:
     * - Deprecated API usage
     * - Type checking warnings
     * - Performance concerns
     * - Potential runtime issues
     *
     * @example
     * ```ts
     * if (result.warnings.length > 0) {
     *   console.warn(`Build completed with ${result.warnings.length} warnings`);
     *   result.warnings.forEach(warn => console.warn(warn.message));
     * }
     * ```
     *
     * @since 2.0.0
     */
    warnings: Array<Error>;
}
/**
 * Recursively makes all properties of a type optional.
 *
 * @remarks
 * This utility type behaves like TypeScript’s built-in {@link Partial} type,
 * but applies recursively to all nested object properties.
 *
 * It is commonly used for:
 * - Partial configuration overrides
 * - Patch / update objects
 * - Programmatic configuration merging
 * - Build variant and preset definitions
 *
 * This type only affects compile-time type checking and has no runtime impact.
 *
 * ⚠️ **Important limitations**:
 * - Arrays and functions are treated as objects and will also be recursively
 *   transformed. If this is undesirable, a more specialized deep-partial
 *   implementation should be used.
 * - Intended for configuration and data-shaping use cases, not strict domain models.
 *
 * @example
 * ```ts
 * interface Config {
 *   server: {
 *     host: string;
 *     port: number;
 *   };
 *   features: {
 *     experimental: boolean;
 *   };
 * }
 *
 * const override: DeepPartialType<Config> = {
 *   server: {
 *     port: 8080
 *   }
 * };
 * ```
 *
 * @template T - The type to recursively make optional.
 *
 * @since 2.0.0
 */
type DeepPartialType<T> = {
    [K in keyof T]?: T[K] extends object ? DeepPartialType<T[K]> : T[K];
};
/**
 * Represents code that can be injected into build output as a banner or footer.
 * Can be a static string or a function that generates code dynamically based on build context.
 *
 * @remarks
 * This type provides flexibility for injecting code at the top (banner) or bottom (footer) of
 * bundled output files. The function form receives the plugin name and command-line arguments,
 * allowing for context-aware code generation.
 *
 * Common use cases:
 * - Static banners: Copyright notices, license headers, version information
 * - Dynamic banners: Build timestamps, environment-specific code, conditional imports
 * - Footer code: Analytics snippets, polyfills, initialization scripts
 *
 * When using the function form, the generated string is cached per build variant to avoid
 * regenerating the same code multiple times.
 *
 * @example
 * ```ts
 * // Static banner
 * const banner: InjectableCodeType = '\/* Copyright 2024 *\/';
 *
 * // Dynamic banner
 * const banner: InjectableCodeType = (name, argv) => {
 *   const version = argv.version || '1.0.0';
 *   return `\/* Built by ${name} v${version} at ${new Date().toISOString()} *\/`;
 * };
 * ```
 *
 * @see {@link BaseBuildDefinitionInterface.banner}
 * @see {@link BaseBuildDefinitionInterface.footer}
 *
 * @since 2.0.0
 */
type InjectableCodeType = string | ((name: string, argv: Record<string, unknown>) => string);
/**
 * Defines lifecycle hook handlers for build process stages.
 * Allows registration of custom logic during resolution, loading, build start, build end, and success.
 *
 * @remarks
 * This interface groups all available lifecycle hooks in a single configuration object.
 * All hooks are optional, allowing selective registration of only necessary handlers.
 *
 * Hook execution order during a build:
 * 1. `onStart` - Before any file processing
 * 2. `onResolve` - During import path resolution
 * 3. `onLoad` - When loading file contents
 * 4. `onEnd` - After build completes (success or failure)
 * 5. `onSuccess` - After a build completes successfully
 *
 * Each hook receives a specialized context object appropriate for its lifecycle stage, providing
 * access to build configuration, variant information, and cross-hook communication through the
 * shared stage object.
 *
 * @example
 * ```ts
 * const hooks: LifecycleHooksInterface = {
 *   onStart: async (context) => {
 *     console.log(`${context.variantName} build starting...`);
 *   },
 *   onLoad: async (context) => {
 *     if (context.args.path.endsWith('.custom')) {
 *       return { contents: transform(context.contents), loader: 'ts' };
 *     }
 *   },
 *   onSuccess: async (context) => {
 *     console.log(`Build succeeded in ${context.duration}ms!`);
 *   }
 * };
 * ```
 *
 * @see {@link OnEndType}
 * @see {@link OnLoadType}
 * @see {@link OnStartType}
 * @see {@link OnResolveType}
 *
 * @since 2.0.0
 */
interface LifecycleHooksInterface {
    /**
     * Hook handler executed when the build completes, regardless of success or failure.
     *
     * @remarks
     * Called after all build operations finish with a result context containing the build result,
     * calculated duration, variant name, arguments, and stage state. Useful for cleanup, logging,
     * reporting, and post-processing.
     *
     * The handler receives `ResultContextInterface` providing access to:
     * - `buildResult`: Final build outcome with errors and warnings
     * - `duration`: Build duration in milliseconds
     * - `variantName`: Build variant identifier
     * - `argv`: Command-line arguments and configuration
     * - `stage`: Shared state object for cross-hook communication
     *
     * @example
     * ```ts
     * onEnd: async (context) => {
     *   const { buildResult, duration, variantName } = context;
     *   console.log(`${variantName} completed in ${duration}ms`);
     *   if (buildResult.errors.length > 0) {
     *     // Handle errors
     *   }
     * }
     * ```
     *
     * @see {@link ResultContextInterface}
     *
     * @since 2.0.0
     */
    onEnd?: OnEndType;
    /**
     * Hook handler executed when loading file contents during module processing.
     *
     * @remarks
     * Called for each file being processed with a load context containing the current file contents
     * (potentially transformed by previous hooks), loader type, load arguments, variant name, and
     * stage state. Can transform contents and change the loader type. Multiple handlers execute in
     * a pipeline pattern where each receives the output of previous hooks.
     *
     * The handler receives `LoadContextInterface` providing access to:
     * - `contents`: Current file contents (string or binary)
     * - `loader`: Current loader type (e.g., 'ts', 'js', 'json')
     * - `args`: Load arguments including file path and namespace
     * - `variantName`: Build variant identifier
     * - `argv`: Command-line arguments and configuration
     * - `stage`: Shared state object for cross-hook communication
     *
     * @example
     * ```ts
     * onLoad: async (context) => {
     *   const { contents, args, variantName } = context;
     *   if (args.path.endsWith('.custom')) {
     *     return {
     *       contents: transform(contents.toString()),
     *       loader: 'ts'
     *     };
     *   }
     * }
     * ```
     *
     * @see {@link LoadContextInterface}
     *
     * @since 2.0.0
     */
    onLoad?: OnLoadType;
    /**
     * Hook handler executed when the build process begins.
     *
     * @remarks
     * Called before any file processing starts with a build context containing the esbuild build object,
     * variant name, arguments, and stage state. Useful for initialization, validation, and setup tasks.
     *
     * The handler receives `BuildContextInterface` providing access to:
     * - `build`: esbuild plugin build object with configuration and utilities
     * - `variantName`: Build variant identifier
     * - `argv`: Command-line arguments and configuration
     * - `stage`: Shared state object for cross-hook communication
     *
     * @example
     * ```ts
     * onStart: async (context) => {
     *   const { build, variantName, stage } = context;
     *   console.log(`Starting ${variantName} build`);
     *   stage.startTime = new Date();
     *
     *   // Validate configuration
     *   if (!build.initialOptions.outdir) {
     *     return { errors: [{ text: 'Output directory required' }] };
     *   }
     * }
     * ```
     *
     * @see {@link BuildContextInterface}
     *
     * @since 2.0.0
     */
    onStart?: OnStartType;
    /**
     * Hook handler executed when the build completes successfully without errors.
     *
     * @remarks
     * Only called when `buildResult.errors.length === 0`, after all regular end hooks have completed.
     * Receives the same result context as end hooks, containing build result, duration, variant name,
     * arguments, and stage state. Useful for deployment, success notifications, and success-only operations.
     *
     * The handler receives `ResultContextInterface` providing access to:
     * - `buildResult`: Final build outcome (guaranteed to have zero errors)
     * - `duration`: Build duration in milliseconds
     * - `variantName`: Build variant identifier
     * - `argv`: Command-line arguments and configuration
     * - `stage`: Shared state object for cross-hook communication
     *
     * @example
     * ```ts
     * onSuccess: async (context) => {
     *   const { buildResult, duration, variantName } = context;
     *   console.log(`${variantName} succeeded in ${duration}ms!`);
     *   await deploy(buildResult.metafile);
     * }
     * ```
     *
     * @see {@link ResultContextInterface}
     *
     * @since 2.0.0
     */
    onSuccess?: OnEndType;
    /**
     * Hook handler executed during module path resolution.
     *
     * @remarks
     * Called when resolving import paths to file system locations with a resolve context containing
     * the resolution arguments, variant name, and stage state. Can redirect imports, mark modules as
     * external, or implement custom resolution logic. Multiple handlers execute, and their results are
     * merged, with later hooks able to override earlier ones.
     *
     * The handler receives `ResolveContextInterface` providing access to:
     * - `args`: Resolution arguments including import path and importer info
     * - `variantName`: Build variant identifier
     * - `argv`: Command-line arguments and configuration
     * - `stage`: Shared state object for cross-hook communication
     *
     * @example
     * ```ts
     * onResolve: async (context) => {
     *   const { args, variantName } = context;
     *
     *   // Redirect '@/' imports to 'src/'
     *   if (args.path.startsWith('@/')) {
     *     return {
     *       path: resolve('src', args.path.slice(2)),
     *       namespace: 'file'
     *     };
     *   }
     *
     *   // Mark as external in production
     *   if (variantName === 'production' && args.path.includes('node_modules')) {
     *     return { path: args.path, external: true };
     *   }
     * }
     * ```
     *
     * @see {@link ResolveContextInterface}
     *
     * @since 2.0.0
     */
    onResolve?: OnResolveType;
}
/**
 * Configuration options for TypeScript declaration file generation.
 *
 * @remarks
 * Controls how and where TypeScript declaration files (`.d.ts`) are generated during the build.
 * These options work in conjunction with the TypeScript compiler to produce type definitions
 * for bundled code.
 *
 * When `bundle` is true, declarations from multiple source files are combined into a single
 * declaration file per entry point. When false, individual declaration files are generated
 * for each source file.
 *
 * @example
 * ```ts
 * // Generate bundled declarations in custom directory
 * const options: DeclarationOptionsInterface = {
 *   outDir: 'types',
 *   bundle: true
 * };
 * ```
 *
 * @see {@link BaseBuildDefinitionInterface.declaration}
 *
 * @since 2.0.0
 */
interface DeclarationOptionsInterface {
    /**
     * Output directory for generated declaration files.
     *
     * @remarks
     * Specifies where `.d.ts` files should be written. If not provided, uses the TypeScript
     * compiler's `declarationDir` or `outDir` from `tsconfig.json`.
     *
     * @example
     * ```ts
     * outDir: 'dist/types'
     * ```
     *
     * @since 2.0.0
     */
    outDir?: string;
    /**
     * Whether to bundle declarations into a single file per entry point.
     *
     * @remarks
     * When true, combines all declarations from imported modules into a single `.d.ts` file.
     * When false, generates individual declaration files mirroring the source structure.
     *
     * Bundling is useful for library distribution as it provides a single type definition file
     * that consumers can reference.
     *
     * @example
     * ```ts
     * bundle: true  // Produces single bundled .d.ts
     * bundle: false // Produces multiple .d.ts files
     * ```
     *
     * @since 2.0.0
     */
    bundle?: boolean;
}
/**
 * Configuration options for TypeScript type checking during builds.
 *
 * @remarks
 * Controls how TypeScript type checking is performed and whether type errors should fail the build.
 * Type checking runs in parallel with the esbuild compilation process for better performance.
 *
 * @example
 * ```ts
 * // Fail build on type errors
 * const options: TypeCheckOptionsInterface = {
 *   failOnError: true
 * };
 * ```
 *
 * @see {@link BaseBuildDefinitionInterface.types}
 *
 * @since 2.0.0
 */
interface TypeCheckOptionsInterface {
    /**
     * Whether to fail the build when TypeScript errors are detected.
     *
     * @remarks
     * When true, any TypeScript errors will cause the build to fail with a non-zero exit code.
     * When false, errors are logged, but the build continues and succeeds.
     *
     * Useful in CI/CD pipelines where type safety must be enforced before deployment.
     *
     * @example
     * ```ts
     * failOnError: true  // Build fails on type errors
     * failOnError: false // Type errors logged, but build continues
     * ```
     *
     * @since 2.0.0
     */
    failOnError?: boolean;
}
/**
 * Base configuration shared across all build definitions, including common and variant builds.
 * Provides common settings for hooks, type checking, code injection, and declaration generation.
 *
 * @remarks
 * This interface defines the foundation for build configuration that applies to both common
 * settings and individual build variants. Properties defined here can be overridden at the
 * variant level for customization.
 *
 * Configuration inheritance:
 * - Common build settings apply to all variants
 * - Variant settings override common settings
 * - Objects like `define` are merged (variant takes precedence)
 * - Arrays and primitives replace common values
 *
 * @example
 * ```ts
 * const base: BaseBuildDefinitionInterface = {
 *   types: { failOnError: true },
 *   declaration: { bundle: true, outDir: 'types' },
 *   define: { 'process.env.NODE_ENV': '"production"' },
 *   banner: 'const x = "test"',
 *   hooks: {
 *     onSuccess: async () => console.log('Build complete!')
 *   }
 * };
 * ```
 *
 * @see {@link CommonBuildInterface}
 * @see {@link VariantBuildInterface}
 * @see {@link BuildConfigInterface}
 *
 * @since 2.0.0
 */
interface BaseBuildDefinitionInterface {
    /**
     * Lifecycle hook handlers for build process stages.
     *
     * @remarks
     * Registers custom handlers for various build lifecycle events including start, resolve,
     * load, end, and success stages. All hooks are optional.
     *
     * @see {@link LifecycleHooksInterface}
     *
     * @since 2.0.0
     */
    lifecycle?: LifecycleHooksInterface;
    /**
     * TypeScript type checking configuration.
     *
     * @remarks
     * Controls whether and how TypeScript type checking is performed during builds.
     * - `true`: Enable type checking with default options
     * - `false` or omitted: Disable type checking
     * - Object: Enable with specific options like `failOnError`
     *
     * @example
     * ```ts
     * types: true                      // Enable with default
     * types: { failOnError: true }     // Enable and fail on errors
     * types: false                     // Disable
     * ```
     *
     * @see {@link TypeCheckOptionsInterface}
     *
     * @since 2.0.0
     */
    types?: boolean | TypeCheckOptionsInterface;
    /**
     * Global constants to replace during bundling.
     *
     * @remarks
     * Defines key-value pairs for constant replacement during the build. Keys are identifiers
     * or property access expressions, values are JSON-stringified replacements.
     *
     * Commonly used for environment variables, feature flags, and build-time constants.
     *
     * @example
     * ```ts
     * define: {
     *   'process.env.NODE_ENV': '"production"',
     *   'DEBUG': 'false',
     *   'VERSION': '"1.2.3"'
     * }
     * ```
     *
     * @since 2.0.0
     */
    define?: Record<string, unknown>;
    /**
     * Code to inject at the beginning of each output file.
     *
     * @remarks
     * Can be a static string or a function that generates code based on build context.
     * Commonly used for copyright notices, license headers, or polyfill imports.
     *
     * @example
     * ```ts
     * banner: 'const x = "test"'
     * banner: (name, argv) => `const x = "Built: ${new Date().toISOString()}"`
     * ```
     *
     * @see {@link InjectableCodeType}
     *
     * @since 2.0.0
     */
    banner?: {
        [key: string]: InjectableCodeType;
    };
    /**
     * Code to inject at the end of each output file.
     *
     * @remarks
     * Can be a static string or a function that generates code based on build context.
     * Commonly used for initialization code, analytics, or polyfills.
     *
     * @example
     * ```ts
     * footer: '// End of bundle'
     * footer: (name, argv) => `console.log('Loaded ${name}');`
     * ```
     *
     * @see {@link InjectableCodeType}
     *
     * @since 2.0.0
     */
    footer?: {
        [key: string]: InjectableCodeType;
    };
    /**
     * TypeScript declaration file generation configuration.
     *
     * @remarks
     * Controls whether and how TypeScript declaration files are generated.
     * - `true`: Generate declarations with default options
     * - `false` or omitted: Do not generate declarations
     * - Object: Generate with specific options like `outDir` and `bundle`
     *
     * @example
     * ```ts
     * declaration: true                              // Generate with default
     * declaration: { outDir: 'types', bundle: true } // Generate bundled in custom dir
     * declaration: false                             // Disable
     * ```
     *
     * @see {@link DeclarationOptionsInterface}
     *
     * @since 2.0.0
     */
    declaration?: boolean | DeclarationOptionsInterface;
}
/**
 * Build configuration for a specific build variant including esbuild settings and entry points.
 * Extends base configuration with variant-specific esbuild options and required entry points.
 *
 * @remarks
 * A variant represents a distinct build target with its own entry points and esbuild configuration.
 * Variants inherit settings from the common configuration but can override any property.
 *
 * The `esbuild` property excludes fields that are managed by the build system:
 * - `plugins`: Managed by the hook provider
 * - `define`, `banner`, `footer`: Managed by base configuration
 * - `entryPoints`: Required at variant level (non-nullable)
 *
 * Multiple variants enable building different outputs from the same codebase, such as
 * - Different module formats (ESM, CJS)
 * - Different targets (Node.js, browser)
 * - Different bundles (main, worker, tests)
 *
 * @example
 * ```ts
 * const variant: VariantBuildInterface = {
 *   esbuild: {
 *     entryPoints: ['src/index.ts'],
 *     outdir: 'dist/esm',
 *     format: 'esm',
 *     target: 'es2020'
 *   },
 *   types: true,
 *   declaration: { bundle: true, outDir: 'dist/types' }
 * };
 * ```
 *
 * @see {@link VariantsType}
 * @see {@link CommonBuildInterface}
 * @see {@link BaseBuildDefinitionInterface}
 *
 * @since 2.0.0
 */
interface VariantBuildInterface extends BaseBuildDefinitionInterface {
    /**
     * Esbuild-specific configuration for this variant including entry points.
     *
     * @remarks
     * Contains all esbuild options except those managed by the build system.
     * The `entryPoints` field is required and must be non-empty to define what to build.
     *
     * Common options include:
     * - `format`: Output format (esm, cjs, iife)
     * - `outdir` or `outfile`: Output location
     * - `target`: ECMAScript target version
     * - `platform`: Target platform (browser, node, neutral)
     * - `minify`: Whether to minify output
     * - `sourcemap`: Whether to generate source maps
     *
     * @example
     * ```ts
     * esbuild: {
     *   entryPoints: ['src/index.ts', 'src/worker.ts'],
     *   outdir: 'dist',
     *   format: 'esm',
     *   target: 'es2020',
     *   minify: true,
     *   sourcemap: true
     * }
     * ```
     *
     * @since 2.0.0
     */
    esbuild: Omit<BuildOptions, 'plugins' | 'define' | 'banner' | 'footer'>;
    /**
     * Variants that must finish building before this variant starts.
     *
     * @remarks
     * Use this field to express build ordering between variants when one output
     * depends on another being completed first.
     *
     * You can provide:
     * - a single variant name
     * - an array of variant names
     *
     * The build system should resolve these dependencies before running the current
     * variant and should also detect circular dependencies to avoid infinite loops.
     *
     * @example
     * ```ts
     * dependOn: 'types'
     * ```
     *
     * @example
     * ```ts
     * dependOn: ['types', 'shared']
     * ```
     *
     * @see {@link VariantsType}
     * @since 2.4.0
     */
    dependOn?: string | Array<string>;
}
/**
 * Shared configuration applied to all build variants.
 * Extends base configuration with esbuild settings but without entry points.
 *
 * @remarks
 * Common configuration provides default settings that apply to all variants unless overridden.
 * This reduces duplication when multiple variants share similar settings.
 *
 * The `esbuild` property excludes managed fields and `entryPoints` (which must be variant-specific).
 * Settings defined here are merged with variant-specific settings, with variants taking precedence.
 *
 * Typical use cases:
 * - Shared compiler options (target, platform)
 * - Common minification and sourcemap settings
 * - Shared external dependencies
 * - Default output configuration
 *
 * @example
 * ```ts
 * const common: CommonBuildInterface = {
 *   esbuild: {
 *     target: 'es2020',
 *     platform: 'node',
 *     sourcemap: true,
 *     external: ['react', 'react-dom']
 *   },
 *   types: { failOnError: true },
 *   declaration: true
 * };
 * ```
 *
 * @see {@link BaseBuildDefinitionInterface}
 * @see {@link VariantBuildInterface}
 * @see {@link BuildConfigInterface}
 *
 * @since 2.0.0
 */
interface CommonBuildInterface extends BaseBuildDefinitionInterface {
    /**
     * Shared esbuild configuration for all variants.
     *
     * @remarks
     * Contains esbuild options that apply to all variants by default. Variants can override
     * any of these settings with their own specific values.
     *
     * Excludes managed fields and `entryPoints` since entry points must be variant-specific.
     *
     * @example
     * ```ts
     * esbuild: {
     *   platform: 'node',
     *   target: 'node18',
     *   external: ['typescript']
     * }
     * ```
     *
     * @since 2.0.0
     */
    esbuild?: Omit<BuildOptions, 'plugins' | 'define' | 'banner' | 'footer'>;
}
/**
 * Maps variant names to their build configurations.
 * Allows defining multiple build targets with different entry points and settings.
 *
 * @remarks
 * This type represents a collection of named build variants. Each key is a user-defined
 * variant name (e.g., 'esm', 'cjs', 'browser'), and each value is the complete build
 * configuration for that variant.
 *
 * Variant names are used for:
 * - CLI targeting specific builds
 * - Build output organization
 * - Logging and error reporting
 * - Parallel build coordination
 *
 * @example
 * ```ts
 * const variants: VariantsType = {
 *   esm: {
 *     esbuild: {
 *       entryPoints: ['src/index.ts'],
 *       format: 'esm',
 *       outdir: 'dist/esm'
 *     }
 *   },
 *   cjs: {
 *     esbuild: {
 *       entryPoints: ['src/index.ts'],
 *       format: 'cjs',
 *       outdir: 'dist/cjs'
 *     }
 *   }
 * };
 * ```
 *
 * @see {@link VariantBuildInterface}
 * @see {@link BuildConfigInterface}
 *
 * @since 2.0.0
 */
type VariantsType = {
    [variantName: string]: VariantBuildInterface;
};
/**
 * Complete build configuration including common settings, variants, and CLI options.
 * Serves as the root configuration object for the entire build system.
 *
 * @remarks
 * This interface defines the complete structure of the build configuration file. It includes:
 * - Optional common settings shared across all variants
 * - Required variants mapping defining all build targets
 * - Optional verbose logging flag
 * - Optional custom command-line argument definitions
 *
 * The configuration is typically exported from a `build.config.ts` or similar file and
 * loaded by the build system at startup.
 *
 * Configuration resolution:
 * 1. Load the configuration file
 * 2. Parse command-line arguments using `userArgv` definitions
 * 3. Merge common settings with each variant
 * 4. Execute builds for all or selected variants
 *
 * @example
 * ```ts
 * const config: BuildConfigInterface = {
 *   verbose: true,
 *   common: {
 *     esbuild: {
 *       platform: 'node',
 *       target: 'node18'
 *     },
 *     types: true
 *   },
 *   variants: {
 *     esm: {
 *       esbuild: {
 *         entryPoints: ['src/index.ts'],
 *         format: 'esm',
 *         outdir: 'dist/esm'
 *       }
 *     },
 *     cjs: {
 *       esbuild: {
 *         entryPoints: ['src/index.ts'],
 *         format: 'cjs',
 *         outdir: 'dist/cjs'
 *       }
 *     }
 *   },
 *   userArgv: {
 *     watch: { type: 'boolean', description: 'Watch for changes' }
 *   }
 * };
 * ```
 *
 * @see {@link VariantsType}
 * @see {@link CommonBuildInterface}
 * @see {@link PartialBuildConfigType}
 *
 * @since 2.0.0
 */
interface BuildConfigInterface {
    /**
     * Shared configuration applied to all build variants.
     *
     * @remarks
     * Optional common settings that are merged with each variant's configuration.
     * Variants can override these settings with their own specific values.
     *
     * @see {@link CommonBuildInterface}
     *
     * @since 2.0.0
     */
    common?: CommonBuildInterface;
    /**
     * Enable verbose logging output during builds.
     *
     * @remarks
     * When true, outputs detailed build information including file processing,
     * hook execution, and timing information. Useful for debugging build issues.
     *
     * @example
     * ```ts
     * verbose: true  // Detailed output
     * verbose: false // Minimal output
     * ```
     *
     * @since 2.0.0
     */
    verbose?: boolean;
    /**
     * Build variant definitions mapping names to configurations.
     *
     * @remarks
     * Required field defining all build targets. At least one variant must be defined.
     * Each variant specifies its own entry points and can override common settings.
     *
     * @see {@link VariantsType}
     *
     * @since 2.0.0
     */
    variants: VariantsType;
}
/**
 * Partial build configuration for incremental or programmatic configuration building.
 * Allows omitting variants and userArgv while making other fields optional.
 *
 * @remarks
 * This type is useful when building configuration programmatically or when providing
 * configuration fragments that will be merged with a base configuration. It makes
 * all properties optional except `variants` and `userArgv` which are completely omitted.
 *
 * Common use cases:
 * - Configuration presets or templates
 * - Programmatic configuration generation
 * - Configuration merging utilities
 * - Partial overrides in build scripts
 *
 * @example
 * ```ts
 * const preset: PartialBuildConfigType = {
 *   verbose: true,
 *   common: {
 *     types: { failOnError: true },
 *     declaration: true
 *   }
 * };
 *
 * // Merge with full config
 * const fullConfig: BuildConfigInterface = {
 *   ...preset,
 *   variants: { ... }
 * };
 * ```
 *
 * @see {@link BuildConfigInterface}
 *
 * @since 2.0.0
 */
type PartialBuildConfigType = Partial<BuildConfigInterface>;
/**
 * Represents a value that may be synchronous, asynchronous, void, null, or the specified type.
 *
 * @template T - The actual value type when present
 *
 * @remarks
 * This utility type is used for hook handlers that may return values in multiple forms:
 * - Synchronous return: `T`, `void`, or `null`
 * - Asynchronous return: `Promise<T>`, `Promise<void>`, or `Promise<null>`
 *
 * This flexibility allows hooks to be implemented as sync or async functions and to optionally
 * return results. Handlers that don't need to return data can return `void` or `null`.
 *
 * @example
 * ```ts
 * // All valid implementations
 * const sync: MaybeVoidPromiseType<string> = 'result';
 * const voidSync: MaybeVoidPromiseType<string> = null;
 * const async: MaybeVoidPromiseType<string> = Promise.resolve('result');
 * const voidAsync: MaybeVoidPromiseType<string> = Promise.resolve(null);
 * ```
 *
 * @see {@link OnEndType}
 * @see {@link OnStartType}
 *
 * @since 2.0.0
 */
type MaybeVoidPromiseType<T> = void | null | T | Promise<void | null | T>;
/**
 * Represents a value that may be synchronous, asynchronous, undefined, null, or the specified type.
 *
 * @template T - The actual value type when present
 *
 * @remarks
 * This utility type is used for hook handlers that may return values in multiple forms:
 * - Synchronous return: `T`, `undefined`, or `null`
 * - Asynchronous return: `Promise<T>`, `Promise<undefined>`, or `Promise<null>`
 *
 * Similar to {@link MaybeVoidPromiseType} but uses `undefined` instead of `void`, allowing handlers
 * to explicitly return nothing or optionally return results. This distinction is important for
 * hooks where the absence of a return value has semantic meaning (like allowing default behavior).
 *
 * @example
 * ```ts
 * // All valid implementations
 * const sync: MaybeUndefinedPromiseType<object> = { path: '/file.ts' };
 * const undefinedSync: MaybeUndefinedPromiseType<object> = undefined;
 * const async: MaybeUndefinedPromiseType<object> = Promise.resolve({ path: '/file.ts' });
 * const undefinedAsync: MaybeUndefinedPromiseType<object> = Promise.resolve(undefined);
 * ```
 *
 * @see {@link OnLoadType}
 * @see {@link OnResolveType}
 *
 * @since 2.0.0
 */
type MaybeUndefinedPromiseType<T> = undefined | null | T | Promise<undefined | null | T>;
/**
 * Represents a transient build stage state shared across hook handlers during a single build.
 *
 * @remarks
 * This interface provides a flexible container for storing temporary data during the build lifecycle.
 * It's reset at the start of each build and is available to all hooks through the plugin context.
 *
 * The `startTime` property is always present and set when the build begins, allowing hooks to
 * calculate durations and timing information. Additional properties can be added dynamically
 * using the index signature to facilitate cross-handler communication.
 *
 * Common use cases:
 * - Storing build start time for duration calculations
 * - Passing data between different hook handlers
 * - Accumulating statistics during the build
 * - Caching computed values for reuse across hooks
 *
 * @example
 * ```ts
 * // In onStart hook
 * context.stage.startTime = new Date();
 * context.stage.fileCount = 0;
 *
 * // In onLoad hook
 * context.stage.fileCount++;
 *
 * // In onEnd hook
 * const duration = Date.now() - context.stage.startTime.getTime();
 * console.log(`Processed ${context.stage.fileCount} files in ${duration}ms`);
 * ```
 *
 * @see {@link LifecycleContextInterface}
 *
 * @since 2.0.0
 */
interface LifecycleStageInterface {
    /**
     * Timestamp when the build process started.
     *
     * @remarks
     * Set during the first `onStart` hook execution and available throughout the build lifecycle.
     * Used to calculate build duration and timing information.
     *
     * @since 2.0.0
     */
    startTime: Date;
    /**
     * Additional dynamic properties for cross-handler communication.
     *
     * @remarks
     * Handlers can store arbitrary data in the stage object using any string key.
     * This allows passing information between hooks during a single build.
     *
     * @since 2.0.0
     */
    [key: string]: unknown;
}
/**
 * Base context interface shared by all lifecycle hook handlers.
 * Provides access to plugin configuration, command-line arguments, and transient build state.
 *
 * @remarks
 * This context is initialized during the `onStart` phase and remains available throughout the
 * entire build lifecycle. All hook handlers receive a variant of this context, enabling:
 * - Access to command-line arguments and configuration
 * - Cross-handler communication through the stage object
 * - Consistent variant identification across hooks
 *
 * The context is immutable at the top level (variantName and argv don't change during a build),
 * but the stage object is mutable and reset between builds.
 *
 * @example
 * ```ts
 * // In onStart hook
 * const handler: OnStartType = async (context) => {
 *   console.log(`Variant ${context.variantName} starting`);
 *   context.stage.customData = { processed: 0 };
 * };
 * ```
 *
 * @see {@link LoadContextInterface}
 * @see {@link BuildContextInterface}
 * @see {@link ResultContextInterface}
 * @see {@link ResolveContextInterface}
 * @see {@link LifecycleStageInterface}
 *
 * @since 2.0.0
 */
interface LifecycleContextInterface {
    /**
     * Command-line arguments and configuration options passed to the provider.
     *
     * @remarks
     * Contains all CLI options and flags passed when the provider was created.
     * Available to all handlers for accessing build-specific configuration like
     * debug flags, output paths, or custom settings.
     *
     * @example
     * ```ts
     * context.argv; // { debug: true, verbose: false, outdir: 'dist' }
     * ```
     *
     * @since 2.0.0
     */
    argv: Record<string, unknown>;
    /**
     * Transient state object for cross-handler communication during a single build.
     *
     * @remarks
     * Reset to contain only `startTime` at the beginning of each build. Handlers can store
     * and retrieve temporary data during the build lifecycle through this object.
     *
     * Common patterns:
     * - Accumulating statistics across multiple hooks
     * - Passing processed data between different hook types
     * - Caching expensive computations for reuse
     *
     * @example
     * ```ts
     * // Store data in onLoad
     * context.stage.transformedFiles = [];
     *
     * // Access in onEnd
     * console.log(`Transformed ${context.stage.transformedFiles.length} files`);
     * ```
     *
     * @see {@link LifecycleStageInterface}
     *
     * @since 2.0.0
     */
    stage: LifecycleStageInterface;
    /**
     * Identifier for the build variant or plugin instance.
     *
     * @remarks
     * Used for identification and logging. Same as the variant name passed to
     * the HooksProvider constructor or build configuration.
     *
     * @example
     * ```ts
     * context.variantName; // 'production' or 'development'
     * ```
     *
     * @since 2.0.0
     */
    variantName: string;
    /**
     * esbuild configuration options used for this lifecycle execution.
     *
     * @remarks
     * These options represent the active build configuration for the provider and
     * are intended to be read by lifecycle handlers when build behavior depends on
     * entry points, output settings, plugins, or other esbuild flags.
     *
     * @since 2.2.0
     */
    options: BuildOptions;
}
/**
 * Context interface for `onStart` hooks, providing access to the esbuild plugin build object.
 *
 * @remarks
 * This specialized context extends the base lifecycle context with the esbuild `PluginBuild`
 * object, giving start hooks access to build configuration, utilities, and the ability to
 * register additional esbuild hooks dynamically.
 *
 * Start hooks are the only lifecycle phase that receives the build object, as they execute
 * before file processing begins and may need to configure or inspect build settings.
 *
 * @example
 * ```ts
 * const handler: OnStartType = async (context) => {
 *   const { build, variantName, argv } = context;
 *   console.log(`Starting ${variantName} build`);
 *
 *   // Access build configuration
 *   console.log(`Platform: ${build.initialOptions.platform}`);
 *
 *   return { errors: [], warnings: [] };
 * };
 * ```
 *
 * @see {@link OnStartType}
 * @see {@link LifecycleContextInterface}
 *
 * @since 2.0.0
 */
interface BuildContextInterface extends LifecycleContextInterface {
    /**
     * The esbuild plugin build object providing build configuration and utilities.
     *
     * @remarks
     * Provides access to:
     * - `initialOptions`: Build configuration options
     * - `resolve`: Path resolution utilities
     * - Dynamic hook registration methods
     * - Build environment information
     *
     * Available only in `onStart` hooks, as later phases don't require build-level access.
     *
     * @example
     * ```ts
     * // Access initial options
     * const outdir = context.build.initialOptions.outdir;
     *
     * // Resolve a path
     * const resolved = await context.build.resolve('./module', {
     *   resolveDir: '/src'
     * });
     * ```
     *
     * @since 2.0.0
     */
    build: PluginBuild;
}
/**
 * Context interface for `onEnd` and `onSuccess` hooks, providing access to build results and duration.
 *
 * @remarks
 * This specialized context extends the base lifecycle context with the final build result
 * and calculated build duration, giving end hooks access to a build outcome, errors, warnings,
 * and metadata.
 *
 * The duration is automatically calculated from the start time in the stage object, providing
 * a convenient way to measure build performance without manual timestamp calculations.
 *
 * @example
 * ```ts
 * const handler: OnEndType = async (context) => {
 *   const { buildResult, duration, variantName } = context;
 *
 *   console.log(`${variantName} build completed in ${duration}ms`);
 *
 *   if (buildResult.errors.length > 0) {
 *     console.error(`Build failed with ${buildResult.errors.length} errors`);
 *   }
 *
 *   // Access metafile for dependency analysis
 *   if (buildResult.metafile) {
 *     console.log('Outputs:', Object.keys(buildResult.metafile.outputs));
 *   }
 * };
 * ```
 *
 * @see {@link OnEndType}
 * @see {@link LifecycleContextInterface}
 *
 * @since 2.0.0
 */
interface ResultContextInterface extends LifecycleContextInterface {
    /**
     * Build duration in milliseconds.
     *
     * @remarks
     * Automatically calculated as the time elapsed from `context.stage.startTime` to
     * when the build completed. Useful for performance monitoring and reporting.
     *
     * @example
     * ```ts
     * console.log(`Build took ${context.duration}ms`);
     * ```
     *
     * @since 2.0.0
     */
    duration: number;
    /**
     * The final build result from esbuild containing errors, warnings, and metadata.
     *
     * @remarks
     * Provides access to:
     * - `errors`: Array of build errors
     * - `warnings`: Array of build warnings
     * - `metafile`: Build metadata including inputs, outputs, and dependencies
     * - `outputFiles`: Generated file contents (if `write: false`)
     *
     * @example
     * ```ts
     * // Check for errors
     * if (context.buildResult.errors.length > 0) {
     *   // Handle build failure
     * }
     *
     * // Analyze dependencies
     * const inputs = context.buildResult.metafile?.inputs;
     * ```
     *
     * @since 2.0.0
     */
    buildResult: BuildResult;
}
/**
 * Context interface for `onResolve` hooks, providing access to resolution arguments.
 *
 * @remarks
 * This specialized context extends the base lifecycle context with esbuild's resolution
 * arguments, giving resolve hooks access to the import path, importer information, and
 * resolution context needed to implement custom module resolution logic.
 *
 * Resolve hooks use this context to determine how to resolve import paths, redirect imports,
 * or mark modules as external based on the resolution arguments.
 *
 * @example
 * ```ts
 * const handler: OnResolveType = async (context) => {
 *   const { args, variantName } = context;
 *
 *   // Redirect '@/' imports to 'src/'
 *   if (args.path.startsWith('@/')) {
 *     return {
 *       path: resolve('src', args.path.slice(2)),
 *       namespace: 'file'
 *     };
 *   }
 *
 *   // Mark node_modules as external in development
 *   if (variantName === 'development' && args.path.includes('node_modules')) {
 *     return { path: args.path, external: true };
 *   }
 *
 *   return undefined; // Use default resolution
 * };
 * ```
 *
 * @see {@link OnResolveType}
 * @see {@link LifecycleContextInterface}
 *
 * @since 2.0.0
 */
interface ResolveContextInterface extends LifecycleContextInterface {
    /**
     * Resolution arguments from esbuild containing the import path and resolution context.
     *
     * @remarks
     * Provides access to:
     * - `path`: The import path to resolve (e.g., './module', '\@/utils')
     * - `importer`: The file that contains this import
     * - `namespace`: The namespace of the importer
     * - `resolveDir`: The directory to resolve relative imports from
     * - `kind`: The kind of import (e.g., 'import-statement', 'require-call')
     * - `pluginData`: Data passed from previous plugins
     *
     * @example
     * ```ts
     * console.log(`Resolving ${context.args.path} from ${context.args.importer}`);
     *
     * if (context.args.kind === 'dynamic-import') {
     *   // Handle dynamic imports specially
     * }
     * ```
     *
     * @since 2.0.0
     */
    args: OnResolveArgs;
}
/**
 * Context interface for `onLoad` hooks, providing access to load arguments, current contents, and loader.
 *
 * @remarks
 * This specialized context extends the base lifecycle context with esbuild's load arguments,
 * the current file contents (potentially transformed by previous hooks), and the current loader
 * type. This enables load hooks to implement content transformations in a pipeline pattern.
 *
 * Load hooks receive the output of previous hooks through `contents` and `loader`, allowing
 * sequential transformations where each hook builds on the work of previous hooks.
 *
 * @example
 * ```ts
 * const handler: OnLoadType = async (context) => {
 *   const { contents, loader, args, variantName } = context;
 *
 *   // Transform .custom files to TypeScript
 *   if (args.path.endsWith('.custom')) {
 *     return {
 *       contents: transformCustomSyntax(contents.toString()),
 *       loader: 'ts'
 *     };
 *   }
 *
 *   // Add debugging in development
 *   if (variantName === 'development' && loader === 'ts') {
 *     return {
 *       contents: `console.log('Loading: ${args.path}');\n${contents}`,
 *       loader
 *     };
 *   }
 *
 *   return undefined; // Pass through unchanged
 * };
 * ```
 *
 * @see {@link OnLoadType}
 * @see {@link LifecycleContextInterface}
 *
 * @since 2.0.0
 */
interface LoadContextInterface extends LifecycleContextInterface {
    /**
     * Load arguments from esbuild containing file path and namespace.
     *
     * @remarks
     * Provides access to:
     * - `path`: The absolute path to the file being loaded
     * - `namespace`: The namespace for this module
     * - `suffix`: Optional suffix for special handling
     * - `pluginData`: Data passed from resolve hooks or previous plugins
     *
     * @example
     * ```ts
     * console.log(`Loading ${context.args.path}`);
     *
     * if (context.args.namespace === 'virtual') {
     *   // Handle virtual modules
     * }
     * ```
     *
     * @since 2.0.0
     */
    args: OnLoadArgs;
    /**
     * The current loader type for this file.
     *
     * @remarks
     * Reflects any loader changes made by previous hooks in the pipeline. Can be:
     * - `'js'`, `'ts'`, `'jsx'`, `'tsx'`: JavaScript/TypeScript variants
     * - `'json'`, `'css'`, `'text'`: Special content types
     * - `'base64'`, `'binary'`, `'dataurl'`: Binary content encodings
     * - `'default'`: Let esbuild determine the loader
     * - `undefined`: No loader has been set yet
     *
     * Hooks can change the loader to affect how esbuild processes the contents.
     *
     * @example
     * ```ts
     * if (context.loader === 'json') {
     *   // Transform JSON before esbuild processes it
     * }
     * ```
     *
     * @since 2.0.0
     */
    loader: Loader | undefined;
    /**
     * The current file contents as string or binary data.
     *
     * @remarks
     * Contains the output of previous load hooks in the pipeline, or the initial file
     * contents if this is the first hook. Hooks can transform this content and return
     * new contents for further hooks to process.
     *
     * Content can be:
     * - `string`: Text content (source code, JSON, CSS, etc.)
     * - `Uint8Array`: Binary content (images, fonts, etc.)
     *
     * @example
     * ```ts
     * // Transform string contents
     * const transformed = context.contents.toString().replace(/old/g, 'new');
     *
     * // Check content type
     * if (typeof context.contents === 'string') {
     *   // Handle text
     * } else {
     *   // Handle binary
     * }
     * ```
     *
     * @since 2.0.0
     */
    contents: string | Uint8Array;
}
/**
 * Handler function signature for `onStart` hooks executed when a build begins.
 *
 * @param context - Build context containing the esbuild build object, arguments, and stage state
 *
 * @returns Optional result containing errors and warnings to report, or void/null if none
 *
 * @remarks
 * Start hooks are executed before any file processing occurs and receive a build context
 * with access to the esbuild `PluginBuild` object. They can perform initialization tasks
 * and return errors or warnings that will be aggregated with results from other start hooks.
 *
 * Return value semantics:
 * - Return `void` or `null` if the hook has nothing to report
 * - Return `OnStartResult` with errors/warnings arrays to report issues
 * - Can be synchronous or asynchronous (return a Promise)
 *
 * @example
 * ```ts
 * const onStart: OnStartType = async (context) => {
 *   console.log(`Starting ${context.variantName} build`);
 *   context.stage.startTime = new Date();
 *
 *   // Validate build configuration
 *   if (!context.build.initialOptions.outdir) {
 *     return {
 *       errors: [{
 *         text: 'Output directory not specified',
 *         location: null
 *       }]
 *     };
 *   }
 *
 *   return { errors: [], warnings: [] };
 * };
 * ```
 *
 * @see {@link MaybeVoidPromiseType}
 * @see {@link BuildContextInterface}
 * @see {@link LifecycleProvider.onStart}
 *
 * @since 2.0.0
 */
type OnStartType = (context: BuildContextInterface) => MaybeVoidPromiseType<OnStartResult>;
/**
 * Handler function signature for `onEnd` and `onSuccess` hooks executed when a build completes.
 *
 * @param context - Result context containing the build result, duration, arguments, and stage state
 *
 * @returns Optional result containing additional errors and warnings to report, or void/null if none
 *
 * @remarks
 * End hooks are executed after all build operations are complete, regardless of success or failure.
 * They receive a result context with the final build outcome, calculated duration, and can perform
 * cleanup, logging, or post-processing tasks.
 *
 * Success hooks use the same signature but only execute when `context.buildResult.errors.length === 0`,
 * making them suitable for deployment or success-only operations.
 *
 * Return value semantics:
 * - Return `void` or `null` if the hook has nothing to report
 * - Return `OnEndResult` with errors/warnings arrays to add to build output
 * - Can be synchronous or asynchronous (return a Promise)
 *
 * @example
 * ```ts
 * const onEnd: OnEndType = async (context) => {
 *   console.log(`${context.variantName} build completed in ${context.duration}ms`);
 *
 *   if (context.buildResult.errors.length > 0) {
 *     console.error(`Build failed with ${context.buildResult.errors.length} errors`);
 *   } else {
 *     console.log('Build succeeded!');
 *   }
 *
 *   // Clean up temporary files
 *   await cleanupTempFiles(context.stage.tempDir);
 * };
 * ```
 *
 * @example
 * ```ts
 * const onSuccess: OnEndType = async (context) => {
 *   console.log('Deploying build artifacts...');
 *   await deploy(context.buildResult.metafile);
 * };
 * ```
 *
 * @see {@link MaybeVoidPromiseType}
 * @see {@link ResultContextInterface}
 * @see {@link LifecycleProvider.onEnd}
 * @see {@link LifecycleProvider.onSuccess}
 *
 * @since 2.0.0
 */
type OnEndType = (context: ResultContextInterface) => MaybeVoidPromiseType<OnEndResult>;
/**
 * Handler function signature for `onResolve` hooks executed during module path resolution.
 *
 * @param context - Resolve context containing resolution arguments, variant name, and stage state
 *
 * @returns Optional resolution result to override default resolution, or undefined/null for default behavior
 *
 * @remarks
 * Resolve hooks are executed when esbuild needs to resolve import paths to file system locations.
 * They receive a resolve context with the import path, importer information, and can redirect imports,
 * implement custom resolution algorithms, or provide virtual modules.
 *
 * Return value semantics:
 * - Return `undefined` or `null` to allow default esbuild resolution
 * - Return `OnResolveResult` to override with custom resolution (path, namespace, external flag, etc.)
 * - Can be synchronous or asynchronous (return a Promise)
 *
 * Multiple resolve hooks can execute, and their results are merged, with later hooks able to
 * override properties set by earlier hooks.
 *
 * @example
 * ```ts
 * const onResolve: OnResolveType = async (context) => {
 *   const { args, variantName } = context;
 *
 *   // Redirect '@/' imports to 'src/'
 *   if (args.path.startsWith('@/')) {
 *     return {
 *       path: resolve('src', args.path.slice(2)),
 *       namespace: 'file'
 *     };
 *   }
 *
 *   // Mark dependencies as external in production
 *   if (variantName === 'production' && args.path.startsWith('lodash')) {
 *     return { path: args.path, external: true };
 *   }
 *
 *   // Allow default resolution
 *   return undefined;
 * };
 * ```
 *
 * @see {@link ResolveContextInterface}
 * @see {@link MaybeUndefinedPromiseType}
 * @see {@link LifecycleProvider.onResolve}
 *
 * @since 2.0.0
 */
type OnResolveType = (context: ResolveContextInterface) => MaybeUndefinedPromiseType<OnResolveResult>;
/**
 * Handler function signature for `onLoad` hooks executed when loading file contents.
 *
 * @param context - Load context containing current contents, loader, load arguments, and stage state
 *
 * @returns Optional load result to transform contents or change loader, or undefined/null for no changes
 *
 * @remarks
 * Load hooks are executed when esbuild loads file contents and can transform the contents,
 * change the loader type, or inject additional code. Multiple load hooks execute in a pipeline
 * pattern where each hook receives the transformed output of previous hooks through the context.
 *
 * Return value semantics:
 * - Return `undefined` or `null` to pass contents unchanged to the next hook
 * - Return `OnLoadResult` with `contents` to transform file contents
 * - Return `OnLoadResult` with `loader` to change the loader type
 * - Can be synchronous or asynchronous (return a Promise)
 *
 * The `context.contents` property receives the output of previous hooks, and `context.loader`
 * reflects any loader changes made by previous hooks.
 *
 * @example
 * ```ts
 * const onLoad: OnLoadType = async (context) => {
 *   const { contents, loader, args, variantName } = context;
 *
 *   // Transform .custom files to TypeScript
 *   if (args.path.endsWith('.custom')) {
 *     return {
 *       contents: transformCustomSyntax(contents.toString()),
 *       loader: 'ts'
 *     };
 *   }
 *
 *   // Inject environment variables in development
 *   if (variantName === 'development' && loader === 'js') {
 *     return {
 *       contents: `const ENV = '${variantName}';\n${contents}`,
 *       loader
 *     };
 *   }
 *
 *   // Pass through unchanged
 *   return undefined;
 * };
 * ```
 *
 * @see {@link LoadContextInterface}
 * @see {@link LifecycleProvider.onLoad}
 * @see {@link MaybeUndefinedPromiseType}
 *
 * @since 2.0.0
 */
type OnLoadType = (context: LoadContextInterface) => MaybeUndefinedPromiseType<OnLoadResult>;
/**
 * Represents a cached TypeScript language service instance with reference counting for shared resource management.
 * Enables multiple consumers to share the same language service while tracking active usage through reference counts.
 *
 * @remarks
 * This interface is used internally by {@link TypescriptService} to implement a caching strategy that prevents
 * duplicate language service instances for the same configuration file. The lifecycle follows these rules:
 * - When a new service is created, `refCount` starts at 1
 * - Each additional consumer increments `refCount`
 * - Calling dispose decrements `refCount`
 * - When `refCount` reaches 0, the service is disposed and removed from cache
 *
 * The cached data includes all components needed to maintain a fully functional TypeScript compiler instance:
 * compiled configuration, language service host, and the language service itself.
 *
 * @example
 * ```ts
 * const cached: CachedServiceInterface = {
 *   config: parsedConfig,
 *   host: languageHost,
 *   service: tsLanguageService,
 *   refCount: 1
 * };
 *
 * // Another consumer acquires the same service
 * cached.refCount++; // Now 2
 *
 * // Consumers finish and dispose
 * cached.refCount--; // Now 1
 * cached.refCount--; // Now 0, triggers cleanup
 * ```
 *
 * @see {@link TypescriptService}
 * @see {@link LanguageHostService}
 *
 * @since 2.0.0
 */
interface CachedServiceInterface {
    /**
     * Number of active consumers currently using this cached language service instance.
     *
     * @remarks
     * This counter tracks how many TypeScript service instances are sharing this cached language service.
     * When it reaches zero, the service can be safely disposed of and removed from the cache.
     *
     * @since 2.0.0
     */
    refCount: number;
    /**
     * Language service host managing file system operations and compiler options for this instance.
     * @since 2.0.0
     */
    host: LanguageHostService;
    /**
     * TypeScript language service providing type checking, analysis, and compilation capabilities.
     * @since 2.0.0
     */
    service: LanguageService;
    /**
     * Parsed TypeScript configuration including compiler options, file names, and project references.
     *
     * @remarks
     * This configuration is reloaded when the `tsconfig.json` file changes, ensuring the cached
     * service stays synchronized with the project's compilation settings.
     *
     * @since 2.0.0
     */
    config: ParsedCommandLine;
}
/**
 * Represents formatted diagnostic information from TypeScript compilation, including errors, warnings, and suggestions.
 * Provides a simplified interface for displaying compiler messages with optional source location details.
 *
 * @remarks
 * This interface normalizes TypeScript's diagnostic format into a structure suitable for display in logs,
 * editor integrations, or build output. All location information (file, line, column) is optional because
 * some diagnostics apply globally or lack specific source positions.
 *
 * Line and column numbers are 1-indexed to match standard editor conventions, even though TypeScript
 * internally uses 0-indexed positions.
 *
 * @example
 * ```ts
 * const diagnostic: DiagnosticInterface = {
 *   file: 'src/index.ts',
 *   line: 42,
 *   column: 15,
 *   code: 2304,
 *   message: "Cannot find name 'unknownVariable'."
 * };
 *
 * console.log(`${diagnostic.file}:${diagnostic.line}:${diagnostic.column}`);
 * console.log(`TS${diagnostic.code}: ${diagnostic.message}`);
 * ```
 *
 * @see {@link TypescriptService.check}
 * @see {@link TypescriptService.formatDiagnostic}
 *
 * @since 2.0.0
 */
interface DiagnosticInterface {
    /**
     * File path where the diagnostic occurred.
     *
     * @remarks
     * Optional because some diagnostics are configuration-level errors that don't relate to a specific file.
     *
     * @since 2.0.0
     */
    file?: string;
    /**
     * Line number where the diagnostic occurred, 1-indexed.
     *
     * @remarks
     * Optional because diagnostics without source location (like config errors) won't have line information.
     * When present, this value is 1-indexed to match standard editor conventions.
     *
     * @since 2.0.0
     */
    line?: number;
    /**
     * Column number where the diagnostic occurred, 1-indexed.
     *
     * @remarks
     * Optional because diagnostics without source location won't have column information.
     * When present, this value is 1-indexed to match standard editor conventions.
     *
     * @since 2.0.0
     */
    column?: number;
    /**
     * TypeScript diagnostic code identifying the specific error or warning type.
     *
     * @remarks
     * Optional because not all diagnostics have associated error codes. When present, this can be used
     * to look up detailed documentation or implement diagnostic-specific handling.
     *
     * @example
     * Common codes include 2304 (cannot find name), 2322 (type not assignable), 2307 (cannot find module).
     *
     * @since 2.0.0
     */
    code?: number;
    /**
     * Human-readable diagnostic message describing the error, warning, or suggestion.
     *
     * @remarks
     * This message is flattened from TypeScript's potentially nested diagnostic message structure
     * using newline separators for multi-line messages.
     *
     * @since 2.0.0
     */
    message: string;
    /**
     * Category of the diagnostic indicating its severity level.
     *
     * @remarks
     * Determines how the diagnostic should be treated and displayed. TypeScript uses this to distinguish
     * between different severity levels:
     * - `DiagnosticCategory.Error` (1): Compilation-blocking errors
     * - `DiagnosticCategory.Warning` (0): Non-blocking warnings
     * - `DiagnosticCategory.Suggestion` (2): Code improvement suggestions
     * - `DiagnosticCategory.Message` (3): Informational messages
     *
     * This property is essential for filtering diagnostics by severity and determining whether
     * a build should fail or continue.
     *
     * @example
     * ```ts
     * if (diagnostic.category === DiagnosticCategory.Error) {
     *   console.error(`Error: ${diagnostic.message}`);
     *   process.exit(1);
     * }
     * ```
     *
     * @since 2.0.0
     */
    category: DiagnosticCategory;
}
/**
 * Implements a TypeScript Language Service host with file snapshot caching and module resolution.
 *
 * @remarks
 * The `LanguageHostService` implements the {@link ts.LanguageServiceHost} interface to provide
 * TypeScript's language service with file system access, file snapshots, and compiler configuration.
 *
 * @example
 * ```ts
 * // Initialize with compiler options
 * const host = new LanguageHostService({
 *   target: ts.ScriptTarget.ES2020,
 *   module: ts.ModuleKind.ESNext,
 *   paths: {
 *     '@utils/*': ['src/utils/*'],
 *     '@components/*': ['src/components/*']
 *   }
 * });
 *
 * // Track files for analysis
 * host.touchFile('src/index.ts');
 * host.touchFiles(['src/utils.ts', 'src/types.ts']);
 *
 * // Get file snapshots for language service
 * const snapshot = host.getScriptSnapshot('src/index.ts');
 *
 * // Resolve module imports
 * const resolved = host.resolveModuleName('@utils/helpers', 'src/index.ts');
 *
 * // Check for path aliases
 * const hasAliases = host.aliasRegex !== undefined;
 *
 * // Update configuration
 * host.options = { target: ts.ScriptTarget.ES2022 };
 * ```
 *
 * @see {@link ts.LanguageServiceHost} for the implemented interface specification
 * @see {@link FilesModel} for file snapshot caching implementation
 *
 * @since 2.0.0
 */
declare class LanguageHostService implements ts.LanguageServiceHost {
    private compilerOptions;
    /**
     * Reference to TypeScript's system interface for file operations.
     *
     * @remarks
     * Static reference to `ts.sys` that provides abstracted file system operations
     * (read, write, directory traversal) compatible with different environments (Node.js, browsers, etc.).
     * Used for all file I/O operations in this service to maintain platform independence.
     *
     * @see {@link ts.sys}
     *
     * @since 2.0.0
     */
    private static readonly sys;
    /**
     * Cached regular expression for matching import/export statements with path aliases.
     *
     * @remarks
     * Compiled from `compilerOptions.paths` to efficiently detect imports using path aliases.
     * Regenerated when compiler options change. Undefined if no path aliases are configured.
     *
     * Used by tools that need to identify which import statements use aliases for proper
     * handling during transformation or bundling.
     *
     * @see {@link generateAliasRegex} for pattern generation
     *
     * @since 2.0.0
     */
    private alias;
    /**
     * Cache for resolved module specifiers.
     *
     * @remarks
     * Stores the absolute resolved file path for each module name so repeated lookups
     * do not trigger TypeScript module resolution again. A value of `undefined` means
     * the module could not be resolved and that result is cached too.
     *
     * This cache is keyed by the raw import specifier, so it is only safe when the
     * same specifier is resolved in a compatible context.
     *
     * @since 2.3.0
     */
    private aliasCache;
    /**
     * Cache for TypeScript module resolution results.
     *
     * @remarks
     * TypeScript's internal module resolution cache that stores resolution results to avoid
     * redundant lookups. Improves performance significantly when resolving many imports,
     * especially in large projects with complex path mappings.
     *
     * Recreated when compiler options change (since different options may affect resolution).
     *
     * @see {@link ts.createModuleResolutionCache}
     *
     * @since 2.0.0
     */
    private moduleResolutionCache;
    /**
     * A set containing the file paths of all actively tracked script files.
     *
     * @remarks
     * This set ensures that files are tracked for later operations, such as retrieving script versions
     * or snapshots. Files are added to this set when they are first processed or read by the service.
     *
     * @example
     * ```ts
     * trackFiles.add('/src/main.ts');
     * console.log(trackFiles.has('/src/main.ts')); // true
     * ```
     *
     * @see {@link getScriptFileNames} - Retrieves all tracked files.
     *
     * @since 2.0.0
     */
    private readonly trackFiles;
    /**
     * Model for managing file snapshots and version tracking.
     *
     * @remarks
     * Delegates file snapshot management to {@link FilesModel} for centralized
     * caching and change detection. Snapshots are tracked by modification time
     * to detect file changes efficiently.
     *
     * @see {@link FilesModel}
     *
     * @since 2.0.0
     */
    private readonly filesCache;
    /**
     * Initializes a new {@link LanguageHostService} instance.
     *
     * @param compilerOptions - Optional TypeScript compiler options (defaults to an empty object)
     *
     * @remarks
     * Performs initialization including:
     * 1. Stores compiler options for later use
     * 2. Generates path alias regex from options if configured
     * 3. Creates module resolution cache with appropriate settings
     *
     * The module resolution cache is necessary for efficient resolution of imports in large projects.
     * Path alias regex is generated up-front and cached for performance.
     *
     * @example
     * ```ts
     * // Create host with default options
     * const host = new LanguageHostService();
     *
     * // Create host with specific compiler options
     * const host = new LanguageHostService({
     *   target: ts.ScriptTarget.ES2020,
     *   module: ts.ModuleKind.ESNext,
     *   paths: {
     *     '@utils/*': ['src/utils/*']
     *   }
     * });
     * ```
     *
     * @since 2.0.0
     */
    constructor(compilerOptions?: CompilerOptions);
    /**
     * Regular expression that matches import/export statements using path aliases (if `paths` is configured).
     *
     * @remarks
     * Used mainly for advanced refactoring or rewrite tools that need to identify aliased imports.
     *
     * @since 2.0.0
     */
    get aliasRegex(): RegExp | undefined;
    /**
     * Replaces current compiler options and regenerates derived state (alias regex, module cache).
     *
     * @param options - new compiler configuration
     *
     * @since 2.0.0
     */
    set options(options: CompilerOptions);
    /**
     * Reloads all tracked file snapshots in the shared {@link FilesModel} cache.
     *
     * @remarks
     * This method iterates over every currently tracked file path and touches each file again so
     * the cache can refresh its stored modification time, version, and content snapshot when needed.
     * It is useful in watch-mode or manual refresh scenarios where the underlying files may have changed
     * and dependent services need to observe the updated state.
     *
     * @since 2.3.0
     */
    static reload(): void;
    /**
     * Updates file snapshot in the cache and returns the current state.
     *
     * @param path - file path (relative or absolute)
     * @returns current snapshot data (version, mtime, content snapshot)
     *
     * @see {@link FilesModel#touchFile}
     * @since 2.0.0
     */
    touchFile(path: string): FileSnapshotInterface;
    /**
     * Ensures multiple files are tracked and their snapshots are up to date.
     *
     * @param filesPath - list of file paths to touch
     *
     * @since 2.0.0
     */
    touchFiles(filesPath: Array<string>): void;
    /**
     * Returns current compiler options used by this host.
     *
     * @returns active TypeScript compiler configuration
     *
     * @since 2.0.0
     */
    getCompilationSettings(): CompilerOptions;
    /**
     * Checks whether a file exists on disk.
     *
     * @param path - absolute path
     * @returns `true` if file exists
     *
     * @since 2.0.0
     */
    fileExists(path: string): boolean;
    /**
     * Reads file content from disk.
     *
     * @param path - absolute path
     * @param encoding - optional encoding (defaults to UTF-8)
     * @returns file content or `undefined` if read fails
     *
     * @since 2.0.0
     */
    readFile(path: string, encoding?: string): string | undefined;
    /**
     * Lists files and/or directories matching criteria.
     *
     * @param path - starting directory
     * @param extensions - allowed file extensions
     * @param exclude - glob exclude patterns
     * @param include - glob include patterns
     * @param depth - max recursion depth
     * @returns matching file paths
     *
     * @since 2.0.0
     */
    readDirectory(path: string, extensions?: Array<string>, exclude?: Array<string>, include?: Array<string>, depth?: number): Array<string>;
    /**
     * Returns immediate subdirectories of a given path.
     *
     * @param path - directory to list
     * @returns subdirectory names
     *
     * @since 2.0.0
     */
    getDirectories(path: string): Array<string>;
    /**
     * Checks whether a directory exists.
     *
     * @param path - absolute path
     * @returns `true` if directory exists
     *
     * @since 2.0.0
     */
    directoryExists(path: string): boolean;
    /**
     * Returns the current working directory used as resolution base.
     *
     * @returns absolute path of cwd
     *
     * @since 2.0.0
     */
    getCurrentDirectory(): string;
    /**
     * Returns names of all known script files tracked by this host.
     *
     * @returns array of resolved absolute paths
     *
     * @remarks
     * Only includes files previously requested via `getScriptSnapshot` or explicitly `touchFile`/`touchFiles`.
     *
     * @since 2.0.0
     */
    getScriptFileNames(): Array<string>;
    /**
     * Returns a path to a default lib `.d.ts` file matching the given target.
     *
     * @param options - compiler options (mainly `target`)
     * @returns absolute path to lib.d.ts / lib.esxxxx.d.ts
     *
     * @since 2.0.0
     */
    getDefaultLibFileName(options: CompilerOptions): string;
    /**
     * Returns string version identifier for the given file.
     *
     * @param path - file path
     * @returns version as string (usually `"0"`, `"1"`, `"2"`, …)
     *
     * @remarks
     * Tracks file in `trackFiles` set as a side effect so it appears in `getScriptFileNames()`.
     *
     * @since 2.0.0
     */
    getScriptVersion(path: string): string;
    /**
     * Checks whether a file is actively tracked (has been requested before).
     *
     * @param path - file path
     * @returns `true` if the file is known to this host
     *
     * @since 2.0.0
     */
    hasScriptSnapshot(path: string): boolean;
    /**
     * Returns an up-to-date script snapshot for the file.
     *
     * @param path - file path
     * @returns `IScriptSnapshot` or `undefined` if a file is missing/empty
     *
     * @remarks
     * Automatically touches the file (reads disk if needed) when no snapshot exists yet.
     *
     * @since 2.0.0
     */
    getScriptSnapshot(path: string): IScriptSnapshot | undefined;
    /**
     * Resolves module import using current compiler options and cache.
     *
     * @param moduleName - module specifier
     * @param containingFile - path of a file containing the import
     * @returns resolution result (success and failed lookups)
     *
     * @since 2.0.0
     */
    resolveModuleName(moduleName: string, containingFile: string): ResolvedModuleWithFailedLookupLocations;
    /**
     * Resolves a module specifier to its absolute file path using the host.
     *
     * @param moduleName - import/export specifier (e.g. "lodash", "./utils")
     * @param containingFile - path of a file containing the import
     * @returns resolved absolute path or `undefined` if resolution fails
     *
     * @since 2.0.0
     */
    resolveModuleFileName(moduleName: string, containingFile: string): string | undefined;
    /**
     * Rewrites path aliases in declaration content to relative paths.
     *
     * @param content - raw declaration text
     * @param fileName - source file name
     * @param type - file extension to append to resolved paths (e.g., `'.d.ts'`, `'.js'`), defaults to empty string
     * @returns content with aliases replaced by relative paths
     *
     * @remarks
     * Ensures emitted files use portable relative imports instead of aliases.
     * The `type` parameter allows flexible transformation of resolved TypeScript source file extensions
     * (`.ts`, `.tsx`) to any target extension.
     *
     * **Common use cases**:
     * - Pass `'.d.ts'` for declaration file generation
     * - Pass `'.js'` for JavaScript output paths
     * - Pass `''` (default) to preserve the resolved file extension
     *
     * @example
     * ```ts
     * // For regular source files (preserve extension)
     * const code = host.resolveAliases(content, 'src/index.ts');
     *
     * // For declaration files
     * const dts = host.resolveAliases(content, 'src/index.ts', '.d.ts');
     * // '@utils/helpers' -> './utils/helpers.d.ts'
     *
     * // For JavaScript output
     * const js = host.resolveAliases(content, 'src/index.ts', '.js');
     * // '@utils/helpers' -> './utils/helpers.js'
     * ```
     *
     * @since 2.0.0
     */
    resolveAliases(content: string, fileName: string, type?: string): string;
    /**
     * Builds regex that matches import/export declarations using any configured path alias.
     *
     * @param config - compiler options containing `paths`
     * @returns regex or `undefined` if no `paths` configured
     *
     * @since 2.0.0
     */
    private static generateAliasRegex;
}
/**
 * Extended TypeScript script snapshot that includes direct access to the underlying text content.
 *
 * @remarks
 * This type augments TypeScript's standard `IScriptSnapshot` interface with a `text` property,
 * providing direct access to the original source text without requiring method calls.
 *
 * TypeScript's native `IScriptSnapshot` only exposes text through the `getText()` method.
 * This extended type adds a `text` property for more convenient access to the full content,
 * particularly useful in caching scenarios where the source text is frequently referenced.
 *
 * Primarily used by {@link FilesModel} to store file content snapshots in an efficient,
 * readily accessible format for incremental compilation and language service operations.
 *
 * @example
 * ```ts
 * const snapshot: ScriptSnapshotType = {
 *   ...ts.ScriptSnapshot.fromString(content),
 *   text: content
 * };
 *
 * // Direct text access (convenient)
 * console.log(snapshot.text);
 *
 * // Method-based access (standard IScriptSnapshot)
 * console.log(snapshot.getText(0, snapshot.getLength()));
 * ```
 *
 * @see {@link IScriptSnapshot}
 * @see {@link FilesModel.touchFile}
 * @see {@link FileSnapshotInterface}
 *
 * @since 2.0.0
 */
type ScriptSnapshotType = IScriptSnapshot & {
    text: string;
};
/**
 * Represents the cached state of a single file for incremental TypeScript processing.
 *
 * Stores the modification timestamp, a version counter that increments on every meaningful change,
 * and an optional TypeScript `ScriptSnapshot` containing the file content in a memory-efficient form.
 *
 * Used by language services and build tools to quickly determine whether a file needs to be reparsed.
 *
 * @since 2.0.0
 */
interface FileSnapshotInterface {
    /**
     * Last known modification time of the file in milliseconds since epoch.
     *
     * Set to `0` when the file no longer exists or cannot be accessed.
     *
     * @remarks
     * Compared directly against `fs.stat().mtimeMs` to detect changes without reading content.
     *
     * @since 2.0.0
     */
    mtimeMs: number;
    /**
     * Monotonically increasing integer that changes whenever the file content or accessibility status changes.
     *
     * Used by TypeScript language services as the script version identifier.
     *
     * @remarks
     * - Incremented on every successful content read with changed mtime
     * - Incremented when a file becomes unreadable (if it previously had content or version bigger than 0)
     * - Not incremented on no-op accesses (unchanged mtime)
     *
     * @example
     * ```ts
     * // Typical usage in LanguageServiceHost
     * getScriptVersion(fileName: string): string {
     *   const snapshot = cache.touchFile(fileName);
     *   return String(snapshot.version);
     * }
     * ```
     *
     * @since 2.0.0
     */
    version: number;
    /**
     * TypeScript script snapshot containing the file's source text, or `undefined` if the file is missing,
     * empty, or inaccessible.
     *
     * @remarks
     * - Created via `ts.ScriptSnapshot.fromString(content)`
     * - Kept `undefined` for zero-length or non-readable files to save memory
     * - Consumers should check existence before calling methods like `getText()`
     *
     * @see ScriptSnapshotType
     * @see {@link https://github.com/microsoft/TypeScript/wiki/Using-the-Compiler-API#script-snapshot | TypeScript Compiler API – Script Snapshots}
     *
     * @since 2.0.0
     */
    contentSnapshot: ScriptSnapshotType | undefined;
}
/**
 * Provides a file-watching service that tracks changes in the framework's root directory.
 *
 * @remarks
 * This service sets up a recursive file system watcher, filters excluded files,
 * and debounces changes to optimize performance. It is mainly used for monitoring
 * source files or test files and triggering callbacks on changes.
 *
 * @example
 * ```ts
 * const watcher = new WatchService(['**\/node_modules\/**']);
 * await watcher.start((changedFiles) => {
 *   console.log('Changed files:', changedFiles);
 * });
 * ```
 *
 * @see FrameworkService
 * @since 2.0.0
 */
declare class WatchService {
    /**
     * Glob patterns that **exclude** paths from being emitted.
     *
     * @remarks
     * Patterns use **Node.js native glob semantics** via `matchesGlob`.
     * Negation syntax (`!pattern`) is **not supported** and must be expressed
     * through explicit include/exclude separation.
     *
     * Typical examples:
     *
     * - `**\/node_modules\/**`
     * - `**\/dist\/**`
     * - `**\/*.spec.ts`
     *
     * @since 2.0.0
     */
    readonly excludes: Array<string>;
    /**
     * Glob patterns that **allow** paths to be emitted.
     *
     * @remarks
     * A file must match **at least one** an include pattern to be considered.
     * Defaults to `['**\/*']`, meaning all files are eligible unless excluded.
     *
     * @since 2.0.0
     */
    readonly include: Array<string>;
    /**
     * Timer used for debouncing file change events.
     *
     * @remarks
     * When multiple file changes occur in quick succession, this timer ensures that
     * the `handleChangedFiles` method is called only once after a short delay,
     * preventing redundant executions and improving performance.
     *
     * @since 2.0.0
     */
    private debounceTimer;
    /**
     * Reference to the core {@link FrameworkService}.
     *
     * @remarks
     * Injected via the {@link inject} helper, this service provides access to
     * framework-level configuration such as the project root path, runtime
     * environment, and shared utilities.
     * It is used here for resolving relative paths and coordinating with the
     * broader testing infrastructure.
     *
     * @see inject
     * @see FrameworkService
     *
     * @since 2.0.0
     */
    private readonly framework;
    /**
     * Creates a new {@link WatchService}.
     *
     * @param excludes - Glob patterns to ignore.
     * @param include - Glob patterns to allow. Defaults to `['**\/*']`.
     *
     * @remarks
     * Include and exclude rules are evaluated as:
     *
     * ```
     * included AND NOT excluded
     * ```
     *
     * @since 2.0.0
     */
    constructor(excludes?: Array<string>, include?: Array<string>);
    /**
     * Start the file watcher.
     *
     * @param callback - Function to call with the changed file paths.
     * Expects a callback that accepts an array of files.
     * @returns A promise that resolves when the watcher is ready.
     *
     * @remarks
     * This method performs the following steps:
     * 1. Sets up a recursive file system watcher on the framework's root directory.
     * 2. On file changes, normalizes paths, filters excluded files, and schedules
     *    handling of changed files with a debouncing to avoid excessive executions.
     *
     * @example
     * ```ts
     * const watcher = new WatchService();
     * await watcher.start((changedFiles) => {
     *   console.log('Files changed:', changedFiles);
     * });
     * ```
     *
     * @see handleChangedFiles
     *
     * @since 2.0.0
     */
    start(callback: (files: Array<string>) => void): Promise<void>;
    /**
     * Handles the changed files after debouncing.
     *
     * @param callback - Function to call with the changed file paths. Expects a callback that accepts an array of files.
     * @param changedFilesSet - Set of changed file paths containing normalized paths of modified files.
     *
     * @remarks
     * Executes the callback with a copy of the changed files and then clears the set
     * for the next batch of changes.
     *
     * @see start
     * @see debounce
     *
     * @since 2.0.0
     */
    private handleChangedFiles;
    /**
     * Debounce the execution of a function to limit how frequently it runs.
     *
     * @param fn - The function to execute after the debounced delay.
     * @param delay - Optional debounce delay in milliseconds (default is 150 ms).
     *
     * @remarks
     * If multiple calls are made within the delay period, only the last one will execute.
     * This is used in the file watcher to prevent excessive calls to handle file changes
     * when multiple filesystem events occur in quick succession.
     *
     * @see debounceTimer
     * @see handleChangedFiles
     *
     * @since 2.0.0
     */
    private debounce;
}
/**
 * Provides a basic HTTP/HTTPS server module with static file serving
 * and directory listing capabilities.
 *
 * @remarks
 * The `ServerModule` supports serving static files, directories, and
 * optional HTTPS configuration. It handles request logging and error
 *  responses and can invoke user-defined hooks via the configuration.
 *
 * @example
 * ```ts
 * const server = new ServerModule({ port: 3000, host: 'localhost' }, '/var/www');
 * server.start();
 * ```
 *
 * @see ServerConfigurationInterface
 * @since 2.0.0
 */
declare class ServerModule {
    readonly config: ServerConfigurationInterface;
    /**
     * The underlying HTTP or HTTPS server instance.
     *
     * @remarks
     * This property holds the active server instance created by either {@link startHttpServer}
     * or {@link startHttpsServer}. It remains undefined until {@link start} is called.
     * The server instance is used to manage the lifecycle of the HTTP/HTTPS server,
     * including stopping and restarting operations.
     *
     * @see start
     * @see stop
     * @see restart
     * @see startHttpServer
     * @see startHttpsServer
     *
     * @since 2.0.0
     */
    private server?;
    /**
     * Normalized absolute root directory for serving files.
     *
     * @readonly
     * @since 2.0.0
     */
    private readonly rootDir;
    /**
     * Injected {@link FrameworkService} instance used for path resolution and framework assets.
     *
     * @readonly
     * @see FrameworkService
     *
     * @since 2.0.0
     */
    private readonly framework;
    /**
     * Initializes a new {@link ServerModule} instance.
     *
     * @param config - Server configuration including host, port, HTTPS options, and hooks.
     * @param dir - Root directory from which files will be served.
     *
     * @example
     * ```ts
     * import { ServerProvider } from './server-provider';
     *
     * const serverConfig = {
     *     port: 8080,
     *     keyfile: './path/to/keyfile',
     *     certfile: './path/to/certfile',
     *     onRequest: (req, res, next) => { /* custom request handling *\/ }
     * };
     * const provider = new ServerProvider(serverConfig, './public');
     * provider.start();
     * ```
     *
     * @since 2.0.0
     */
    constructor(config: ServerConfigurationInterface, dir: string);
    /**
     * Starts the HTTP or HTTPS server based on configuration.
     *
     * @returns A promise that resolves when the server is fully started and listening.
     *
     * @remarks
     * This method performs the following steps:
     * 1. Invokes the optional {@link onStart} hook if provided.
     * 2. Determines whether to start an HTTPS or HTTP server based on the {@link https} flag.
     * 3. Calls {@link startHttpsServer} if HTTPS is enabled, otherwise calls {@link startHttpServer}.
     *
     * @example
     * ```ts
     * const server = new ServerModule({
     *   port: 3000,
     *   host: 'localhost',
     *   https: true,
     *   onStart: () => console.log('Server starting...')
     * }, '/var/www');
     * await server.start();
     * ```
     *
     * @see stop
     * @see restart
     * @see startHttpServer
     * @see startHttpsServer
     * @see ServerConfigurationInterface
     *
     * @since 2.0.0
     */
    start(): Promise<void>;
    /**
     * Stops the running HTTP or HTTPS server.
     *
     * @returns A promise that resolves when the server is fully stopped.
     *
     * @remarks
     * This method gracefully shuts down the server by closing all active connections.
     * If no server is currently running, it logs a message and returns early.
     * Once stopped, the {@link server} instance is set to `undefined`.
     *
     * @example
     * ```ts
     * const server = new ServerModule({ port: 3000, host: 'localhost' }, '/var/www');
     * server.start();
     * // Later...
     * await server.stop();
     * ```
     *
     * @see start
     * @see server
     * @see restart
     *
     * @since 2.0.0
     */
    stop(): Promise<void>;
    /**
     * Restarts the HTTP or HTTPS server.
     *
     * @returns A promise that resolves when the server has been stopped and restarted.
     *
     * @remarks
     * This method performs a graceful restart by first calling {@link stop} to shut down
     * the current server instance, then calling {@link start} to create a new server
     * with the same configuration. This is useful when configuration changes need to be
     * applied or when recovering from errors.
     *
     * @example
     * ```ts
     * const server = new ServerModule({ port: 3000, host: 'localhost' }, '/var/www');
     * server.start();
     * // Later, restart the server...
     * await server.restart();
     * ```
     *
     * @see stop
     * @see start
     *
     * @since 2.0.0
     */
    restart(): Promise<void>;
    /**
     * Updates the configuration with the actual port assigned by the system.
     *
     * @remarks
     * This method is called after the server starts listening to retrieve and store the
     * actual port number when port `0` was specified in the configuration. When port `0`
     * is used, the operating system automatically assigns an available port, and this
     * method captures that assigned port for use throughout the application.
     *
     * **When this method is needed**:
     * - {@link port} is set to `0` (dynamic port allocation)
     * - The server has started and bound to a port
     * - The actual port needs to be known for logging, testing, or external configuration
     *
     * **Behavior**:
     * 1. Checks if the configured port is `0` (indicating dynamic allocation request)
     * 2. Retrieves the address information from the active server using {@link Server.address}
     * 3. Validates that the address is an object containing a port property
     * 4. Updates {@link config.port} with the system-assigned port number
     *
     * This is particularly useful in:
     * - Testing environments where multiple servers run simultaneously
     * - CI/CD pipelines where port conflicts must be avoided
     * - Containerized deployments with dynamic port mapping
     * - Development tools that spawn multiple server instances
     *
     * The method safely handles cases where the server address might not be available
     * or might not be in the expected format, preventing runtime errors.
     *
     * @example
     * ```ts
     * // Configuration with dynamic port
     * const config = { port: 0, host: 'localhost' };
     * const server = new ServerModule(config, '/var/www');
     *
     * await server.start();
     * // After start, setActualPort() is called internally
     *
     * console.log(config.port); // Now shows actual assigned port, e.g., 54321
     *
     * // Use case: Testing with dynamic ports
     * async function createTestServer() {
     *   const config = { port: 0, host: 'localhost' };
     *   const server = new ServerModule(config, './public');
     *   await server.start();
     *   // setActualPort() has updated config.port
     *   return { server, port: config.port }; // Return actual port for tests
     * }
     *
     * const { server, port } = await createTestServer();
     * console.log(`Test server running on port ${port}`);
     * ```
     *
     * @see Server.address
     * @see startHttpServer
     * @see startHttpsServer
     * @see port
     *
     * @since 2.0.0
     */
    private setActualPort;
    /**
     * Starts an HTTP server.
     *
     * @returns A promise that resolves when the server is listening and ready to accept connections.
     *
     * @remarks
     * Creates an HTTP server instance using Node.js's built-in {@link http} module.
     * All incoming requests are passed to {@link handleRequest}, which routes them to
     * {@link defaultResponse} for serving static files or directories.
     *
     * The server listens on the configured {@link host} and
     * {@link port} from the {@link config}.
     *
     * @example
     * ```ts
     * const server = new ServerModule({ port: 3000, host: 'localhost' }, '/var/www');
     * await server.start(); // Internally calls startHttpServer if HTTPS is not configured
     * ```
     *
     * @see start
     * @see handleRequest
     * @see defaultResponse
     * @see ServerConfigurationInterface
     *
     * @since 2.0.0
     */
    private startHttpServer;
    /**
     * Starts an HTTPS server using configured certificate and key files.
     *
     * @returns A promise that resolves when the server is listening and ready to accept connections.
     *
     * @remarks
     * Creates an HTTPS server instance using Node.js's built-in {@link https} module.
     * If {@link key} or {@link cert}
     * are not provided in the configuration, defaults are loaded from the framework's
     * distribution path at `certs/server.key` and `certs/server.crt`.
     *
     * All incoming requests are passed to {@link handleRequest}, which routes them to
     * {@link defaultResponse} for serving static files or directories.
     *
     * The server listens on the configured {@link host} and
     * {@link port} from the {@link config}.
     *
     * @example
     * ```ts
     * const server = new ServerModule({
     *   port: 3000,
     *   host: 'localhost',
     *   https: true,
     *   key: './path/to/key.pem',
     *   cert: './path/to/cert.pem'
     * }, '/var/www');
     * await server.start(); // Internally calls startHttpsServer
     * ```
     *
     * @see start
     * @see handleRequest
     * @see defaultResponse
     * @see FrameworkService
     * @see ServerConfigurationInterface
     *
     * @since 2.0.0
     */
    private startHttpsServer;
    /**
     * Handles incoming HTTP/HTTPS requests, optionally invoking user-defined hooks.
     *
     * @param req - Incoming HTTP request.
     * @param res - Server response object.
     * @param defaultHandler - Callback for default request handling.
     *
     * @remarks
     * If `config.verbose` is true, logs requests to the console.
     * Errors during handling are forwarded to {@link sendError}.
     *
     * @see sendError
     * @since 2.0.0
     */
    private handleRequest;
    /**
     * Returns the MIME content type for a given file extension.
     *
     * @param ext - File extension without the leading dot.
     * @returns MIME type string for the provided extension.
     *
     * @since 2.0.0
     */
    private getContentType;
    /**
     * Handles default responses for requests by serving files or directories.
     *
     * @param req - Incoming HTTP request.
     * @param res - Server response.
     *
     * @remarks
     * Ensures the requested path is within the server root.
     * Calls {@link handleDirectory} or {@link handleFile} depending on resource type.
     *
     * @see handleFile
     * @see sendNotFound
     * @see handleDirectory
     *
     * @since 2.0.0
     */
    private defaultResponse;
    /**
     * Handles directory listing for a request path.
     *
     * @param fullPath - Absolute directory path.
     * @param requestPath - Relative path from the server root.
     * @param res - Server response.
     *
     * @remarks
     * Generates an HTML listing with icons
     * Invalid filenames are skipped.
     *
     * @see fileIcons
     * @since 2.0.0
     */
    private handleDirectory;
    /**
     * Serves a static file.
     *
     * @param fullPath - Absolute path to the file.
     * @param res - Server response.
     *
     * @remarks
     * Determines MIME type using {@link getContentType}.
     *
     * @see getContentType
     * @since 2.0.0
     */
    private handleFile;
    /**
     * Sends a 404 Not Found response.
     *
     * @param res - Server response.
     *
     * @since 2.0.0
     */
    private sendNotFound;
    /**
     * Sends a 500 Internal Server Error response and logs the error.
     *
     * @param res - Server response.
     * @param error - Error object to log.
     *
     * @since 2.0.0
     */
    private sendError;
}
/**
 * Represents the configuration options for a server instance.
 *
 * @remarks
 * These options control server behavior, including host, port,
 * HTTPS settings, verbosity, and lifecycle hooks.
 *
 * @since 2.0.0
 */
interface ServerConfigurationInterface {
    /**
     * The port number the server will listen to.
     *
     * @remarks
     * Specifies which port the server should bind to. Port behavior:
     * - If not specified: Defaults to `0`
     * - If set to `0`: The system will automatically assign an available port
     * - If not specified: Uses the default port configuration
     * - Valid range: 0-65535
     *
     * Using port `0` is useful for:
     * - Running multiple server instances without port conflicts
     * - Testing environments where specific ports aren't required
     * - Dynamic port allocation in containerized deployments
     *
     *
     * @since 2.0.0
     */
    port?: number;
    /**
     * The hostname or IP address the server will bind to.
     *
     * @remarks
     * Specifies the network interface the server should listen on:
     * - If not specified: Defaults to `localhost` (127.0.0.1)
     * - Use `'0.0.0.0'`: Listen on all network interfaces (accessible externally)
     * - Use `'localhost'` or `'127.0.0.1'`: Local machine only
     * - Use specific IP: Bind to a particular network interface
     *
     * Common configurations:
     * - Development: `localhost` (default) - local access only
     * - Production: `0.0.0.0` - accessible from network
     * - Docker: `0.0.0.0` - allow container external access
     *
     * @since 2.0.0
     */
    host?: string;
    /**
     * Optional path to the SSL key file, required if HTTPS is enabled
     * @since 2.0.0
     */
    key?: string;
    /**
     * Optional path to the SSL certificate file, required if HTTPS is enabled
     * @since 2.0.0
     */
    cert?: string;
    /**
     * If true, the server will run using HTTPS
     * @since 2.0.0
     */
    https?: boolean;
    /**
     * If true, enables verbose logging of server activity
     * @since 2.0.0
     */
    verbose?: boolean;
    /**
     * Hook called on every incoming request.
     *
     * @param req - The incoming HTTP request.
     * @param res - The server response object.
     * @param next - Callback to pass control to the next middleware or handler.
     *
     * @remarks
     * Can be used to implement custom logging, request modification,
     * or authentication before request handling.
     *
     * @since 2.0.0
     */
    onRequest?: (req: IncomingMessage, res: ServerResponse, next: () => void) => void;
    /**
     * Hook called once the server has started and is listening.
     *
     * @remarks
     * Useful for initialization tasks or logging server start events.
     *
     * @since 2.0.0
     */
    onStart?: (config: {
        host: string;
        port: number;
        url: string;
    }) => void;
}
/**
 * Converts an esbuild message to a normalized Error instance.
 *
 * @param msg - The esbuild message object containing error or warning details
 * @returns A normalized Error instance appropriate for the message type
 *
 * @remarks
 * This function handles different types of esbuild messages and converts them to the appropriate
 * error classes used throughout the xBuild system. It prioritizes preserving existing error
 * instances while wrapping raw messages in appropriate error types.
 *
 * **Conversion priority**:
 * 1. If `msg.detail` is already an `xBuildBaseError` or `TypesError`, return it unchanged
 * 2. If `msg.detail` is any other Error, wrap it in `VMRuntimeError` with framework frames
 * 3. If `msg.location` exists, create an `esBuildError` with a formatted code snippet
 * 4. Otherwise, wrap the message text in a `VMRuntimeError`
 *
 * This normalization ensures consistent error handling and reporting throughout the build
 * pipeline, with appropriate context and formatting for each error type.
 *
 * @example
 * ```ts
 * // Message with location information
 * const msg: Message = {
 *   text: 'Unexpected token',
 *   location: { file: 'src/index.ts', line: 10, column: 5 }
 * };
 * const error = normalizeMessageToError(msg);
 * // Returns esBuildError with formatted code snippet
 *
 * // Message with existing error detail
 * const msgWithError: Message = {
 *   text: 'Build failed',
 *   detail: new TypesError('Type checking failed', [])
 * };
 * const error2 = normalizeMessageToError(msgWithError);
 * // Returns the TypesError unchanged
 * ```
 *
 * @see {@link TypesError}
 * @see {@link esBuildError}
 * @see {@link VMRuntimeError}
 * @see {@link xBuildBaseError}
 *
 * @since 2.0.0
 */
declare function normalizeMessageToError(msg: Message | esBuildError): Error | undefined;
/**
 * Processes an array of esbuild messages and converts them to normalized errors.
 *
 * @param messages - Array of esbuild message objects to process
 * @param target - Array to populate with normalized error instances
 *
 * @remarks
 * This function iterates through esbuild messages and converts each one to a normalized
 * Error instance using {@link normalizeMessageToError}, appending the results to the
 * target array.
 *
 * The target array is modified in place, allowing errors and warnings from different
 * sources to be aggregated into the same collection.
 *
 * **Processing behavior**:
 * - Each message is converted independently
 * - Conversion failures do not stop processing of remaining messages
 * - a Target array is modified in place (no return value)
 * - Empty message arrays are handled gracefully
 *
 * Common use cases:
 * - Converting esbuild error arrays to normalized errors
 * - Converting esbuild warning arrays to normalized errors
 * - Aggregating messages from multiple build results
 *
 * @example
 * ```ts
 * const buildResult: BuildResult = await build({ ... });
 * const errors: Array<Error> = [];
 * const warnings: Array<Error> = [];
 *
 * // Process errors and warnings
 * processEsbuildMessages(buildResult.errors, errors);
 * processEsbuildMessages(buildResult.warnings, warnings);
 *
 * console.log(`Build completed with ${errors.length} errors and ${warnings.length} warnings`);
 * ```
 *
 * @see {@link enhancedBuildResult}
 * @see {@link normalizeMessageToError}
 *
 * @since 2.0.0
 */
declare function processEsbuildMessages(messages: Array<Message> | undefined, target: Array<Error>): void;
/**
 * Converts esbuild's BuildResult into xBuild's BuildResultInterface with normalized errors.
 *
 * @param source - Partial esbuild BuildResult containing build artifacts and messages
 * @returns A BuildResultInterface with normalized errors and warnings
 *
 * @remarks
 * This function transforms esbuild's build result into the xBuild-specific result interface,
 * converting all error and warning messages to normalized Error instances while preserving
 * build artifacts like metafiles, output files, and mangle cache.
 *
 * **Transformation process**:
 * 1. Creates a new BuildResultInterface with empty error/warning arrays
 * 2. Copies build artifacts (metafile, outputFiles, mangleCache) directly
 * 3. Processes errors array through {@link processEsbuildMessages}
 * 4. Processes warnings array through {@link processEsbuildMessages}
 * 5. Returns the fully populated result object
 *
 * **Preserved artifacts**:
 * - `metafile`: Build metadata including inputs, outputs, and dependencies
 * - `outputFiles`: Generated file contents when `write: false`
 * - `mangleCache`: Identifier mangling cache for consistent minification
 *
 * All esbuild Message objects are converted to Error instances, providing consistent
 * error handling throughout the xBuild system with proper stack traces, formatting,
 * and error classification.
 *
 * @example
 * ```ts
 * const esbuildResult = await build({
 *   entryPoints: ['src/index.ts'],
 *   write: false,
 *   metafile: true
 * });
 *
 * const result = enhancedBuildResult(esbuildResult);
 * // result.errors: Array<Error> (normalized)
 * // result.warnings: Array<Error> (normalized)
 * // result.metafile: Metafile (preserved)
 * // result.outputFiles: OutputFile[] (preserved)
 *
 * console.log(`Build produced ${result.errors.length} errors`);
 * ```
 *
 * @see {@link BuildResultInterface}
 * @see {@link processEsbuildMessages}
 * @see {@link normalizeMessageToError}
 *
 * @since 2.0.0
 */
declare function enhancedBuildResult(source: Partial<BuildResult>): BuildResultInterface;
/**
 * Type guard that checks if an unknown value is an esbuild BuildResult error object.
 *
 * @param error - The value to check, typically from a catch block
 * @returns `true` if the value is a BuildResult with errors property, `false` otherwise
 *
 * @remarks
 * This type guard validates that an error object follows the esbuild BuildResult structure,
 * which includes an `errors` property. It's useful for distinguishing between esbuild-specific
 * errors and other error types during error handling.
 *
 * The function performs two checks:
 * 1. Verifies the value is an object (not null)
 * 2. Checks for the presence of an `errors` property
 *
 * When the function returns `true`, TypeScript will narrow the type of the parameter to
 * `BuildResult`, allowing type-safe access to BuildResult properties like `errors`,
 * `warnings`, `metafile`, etc.
 *
 * Common use cases:
 * - Catch block error type discrimination
 * - Conditional error handling based on an error source
 * - Type narrowing for BuildResult-specific error processing
 *
 * @example
 * ```ts
 * try {
 *   await build({ entryPoints: ['src/index.ts'] });
 * } catch (error) {
 *   if (isBuildResultError(error)) {
 *     // TypeScript knows error is BuildResult here
 *     console.error(`Build failed with ${error.errors.length} errors`);
 *     processEsbuildMessages(error.errors, errorList);
 *   } else if (error instanceof Error) {
 *     // Handle generic errors
 *     console.error(error.message);
 *   }
 * }
 * ```
 *
 * @example
 * ```ts
 * // In error aggregation
 * const errors: Array<Error> = [];
 *
 * if (isBuildResultError(caughtError)) {
 *   const result = enhancedBuildResult(caughtError);
 *   errors.push(...result.errors);
 * } else {
 *   errors.push(new Error(String(caughtError)));
 * }
 * ```
 *
 * @see {@link BuildResult}
 * @see {@link enhancedBuildResult}
 * @see {@link processEsbuildMessages}
 *
 * @since 2.0.0
 */
declare function isBuildResultError(error: unknown): error is BuildResult;
/**
 * Normalized runtime error wrapper for esbuild diagnostics.
 *
 * @remarks
 * `esBuildError` converts an esbuild {@link PartialMessage} into an {@link xBuildBaseError}
 * with framework-aware metadata and a formatted stack string.
 *
 * Construction behavior:
 * - Uses `message.text` as the runtime error message (defaults to empty string)
 * - Copies `message.id` to {@link id} (defaults to empty string)
 * - Builds structured metadata via {@link getErrorMetadata}
 * - Replaces `stack` using {@link formatStack}, including any diagnostic notes
 *
 * @example
 * ```ts
 * const message = {
 *   id: 'transform',
 *   text: 'Unexpected token',
 *   location: { file: 'src/index.ts', line: 1, column: 5 },
 *   notes: [{ text: 'Check syntax near this token' }]
 * };
 *
 * const error = new esBuildError(message);
 * console.error(error.id); // "transform"
 * console.error(error.stack);
 * ```
 *
 * @see {@link xBuildBaseError}
 * @see {@link getErrorMetadata}
 * @see {@link formatStack}
 *
 * @since 2.0.0
 */
declare class esBuildError extends xBuildBaseError {
    /**
     * Optional esbuild diagnostic identifier copied from `PartialMessage.id`.
     *
     * @remarks
     * This value is useful for categorizing diagnostics by producer (for example,
     * plugin- or phase-specific IDs). When absent in the source message, it defaults
     * to an empty string.
     *
     * @since 2.0.0
     */
    readonly id: string;
    /**
     * Creates a new esbuild error with formatted output and metadata.
     *
     * @param message - The esbuild {@link PartialMessage} containing diagnostic details
     * @param options - Optional stack parsing/formatting options used when deriving metadata
     *
     * @remarks
     * The constructor:
     * 1. Initializes the base error with `message.text ?? ''`
     * 2. Persists `message.id ?? ''` on {@link id}
     * 3. If `message.detail` is an `Error`, uses its `message` and `stack` as runtime values
     * 4. Builds structured metadata from either the original message or `detail` error
     * 5. Produces formatted output (stack replacement for message-based diagnostics, or
     *    formatted inspector output for `detail`-based diagnostics)
     *
     * The error name is always set to `'esBuildError'`. Formatted output includes:
     * - Error name and message with color coding
     * - Any diagnostic notes from esbuild
     * - Highlighted code snippet showing the error location
     * - Enhanced stack trace with file path and position
     *
     * @see {@link getErrorMetadata} for formatting logic
     * @see {@link PartialMessage} for esbuild message structure
     *
     * @since 2.0.0
     */
    constructor(message: PartialMessage, options?: StackTraceInterface);
}
/**
 * A base class for custom errors with enhanced stack trace formatting and source code information.
 *
 * @remarks
 * The `xBuildBaseError` class extends the native `Error` class, adding functionality to:
 * - Parse and store structured stack trace metadata via {@link ResolveMetadataInterface}
 * - Format stack traces with syntax highlighting and source mapping
 * - Provide enhanced console output through custom Node.js inspection
 *
 * This is particularly useful for debugging errors in compiled or transpiled code by providing
 * clearer information about the original source of the error, including
 * - Original source file paths (from source maps)
 * - Highlighted code snippets showing the error location
 * - Enhanced stack frame formatting with proper indentation
 *
 * @example
 * ```ts
 * class ValidationError extends xBuildBaseError {
 *   constructor(message: string, field: string) {
 *     super(message, 'ValidationError');
 *     this.reformatStack(this, { withFrameworkFrames: false });
 *   }
 * }
 *
 * throw new ValidationError('Invalid email format', 'email');
 * ```
 *
 * @see {@link formatStack} for stack formatting
 * @see {@link getErrorMetadata} for stack parsing
 * @see {@link StackTraceInterface} for formatting options
 * @see {@link ResolveMetadataInterface} for the metadata structure
 *
 * @since 2.0.0
 */
declare abstract class xBuildBaseError extends Error {
    /**
     * Structured metadata from the parsed stack trace.
     *
     * @remarks
     * Contains the parsed stack information including
     * - Original source code snippet
     * - Line and column numbers
     * - Source file path (from source maps)
     * - Formatted stack frames
     * - Syntax-highlighted code
     *
     * This property is populated by calling {@link reformatStack}.
     *
     * @since 2.0.0
     */
    protected errorMetadata: ResolveMetadataInterface | undefined;
    /**
     * Pre-formatted stack trace string ready for display.
     *
     * @remarks
     * Contains the complete formatted output including
     * - Error name and message
     * - Syntax-highlighted code snippet (if available)
     * - Enhanced stack trace with proper indentation
     *
     * This is generated by {@link formatStack} and used by the custom
     * Node.js inspector for console output.
     *
     * @since 2.0.0
     */
    protected formattedStack: string | undefined;
    /**
     * Creates a new instance of the base error class.
     *
     * @param message - The error message describing the problem
     * @param name - The error type name; defaults to `'xBuildBaseError'`
     *
     * @remarks
     * This constructor:
     * - Properly sets up the prototype chain to ensure `instanceof` checks work for derived classes
     * - Captures the stack trace if supported by the runtime environment
     * - Sets the error name for identification
     *
     * **Important:** This is a protected constructor and should only be called by derived classes.
     * Subclasses should call {@link reformatStack} after construction to enable enhanced formatting.
     *
     * @example
     * ```ts
     * class DatabaseError extends xBuildBaseError {
     *   constructor(message: string, public readonly query: string) {
     *     super(message, 'DatabaseError');
     *     this.reformatStack(this);
     *   }
     * }
     * ```
     *
     * @since 2.0.0
     */
    protected constructor(message: string, name?: string);
    /**
     * Gets the structured stack trace metadata.
     *
     * @returns The parsed stack metadata, or `undefined` if {@link reformatStack} has not been called
     *
     * @remarks
     * Provides read-only access to the error's structured stack information,
     * which can be used for:
     * - Custom error logging
     * - Error reporting services
     * - Debugging tools
     * - Stack analysis
     *
     * @example
     * ```ts
     * try {
     *   throw new ValidationError('Invalid input');
     * } catch (error) {
     *   if (error instanceof xBuildBaseError) {
     *     const meta = error.metadata;
     *     console.log(`Error at ${meta?.source}:${meta?.line}:${meta?.column}`);
     *   }
     * }
     * ```
     *
     * @since 2.0.0
     */
    get metadata(): ResolveMetadataInterface | undefined;
    /**
     * Parses the error stack trace and generates enhanced formatting with metadata.
     *
     * @param error - The error object to parse and format
     * @param options - Optional configuration for stack trace parsing and formatting
     *
     * @remarks
     * This method performs two operations:
     * 1. Parses the error's stack trace using {@link getErrorMetadata} to extract structured metadata
     * 2. Formats the metadata using {@link formatStack} to create a styled, human-readable output
     *
     * The parsed metadata is stored in {@link errorMetadata} and the formatted string in {@link formattedStack}.
     *
     * **Typical usage:** Call this method in the constructor of derived error classes to enable
     * enhanced stack trace formatting.
     *
     * @example
     * ```ts
     * class NetworkError extends xBuildBaseError {
     *   constructor(message: string, public readonly statusCode: number) {
     *     super(message, 'NetworkError');
     *     // Enable enhanced formatting without framework frames
     *     this.reformatStack(this, {
     *       withFrameworkFrames: false,
     *       withNativeFrames: true
     *     });
     *   }
     * }
     * ```
     *
     * @example
     * ```ts
     * class CustomError extends xBuildBaseError {
     *   constructor(message: string) {
     *     super(message, 'CustomError');
     *     // Use default options
     *     this.reformatStack(this);
     *   }
     * }
     * ```
     *
     * @see {@link formatStack} for formatting logic
     * @see {@link getErrorMetadata} for parsing logic
     * @see {@link StackTraceInterface} for available options
     *
     * @since 2.0.0
     */
    protected reformatStack(error: Error, options?: StackTraceInterface): void;
}
/**
 * Configuration options for parsing and formatting stack traces.
 *
 * @remarks
 * These options control how stack traces are parsed, what frames are included,
 * and how much source code context is displayed. Used by {@link getErrorMetadata}
 * to customize stack trace output.
 *
 * @see stackEntry
 * @see getErrorMetadata
 *
 * @since 2.0.0
 */
interface StackTraceInterface extends Omit<ResolveOptionsInterface, 'getSource'> {
    /**
     * Whether to include framework-internal stack frames in the output.
     *
     * @defaultValue Based on `ConfigurationService.verbose` setting
     *
     * @remarks
     * Framework frames are identified by {@link FrameworkService.isFrameworkFile}.
     * When false, these frames are filtered out to reduce noise in stack traces.
     * Automatically set based on the `verbose` configuration setting if not
     * explicitly provided.
     *
     * @see FrameworkService.isFrameworkFile
     * @since 2.0.0
     */
    withFrameworkFrames?: boolean;
}
/**
 * Additional metadata used when resolving and formatting source output.
 *
 * @remarks
 * Extends the base xMap resolution metadata with optional formatted code text
 * that can be attached to the resolution result.
 *
 * @since 2.2.5
 */
interface ResolveMetadataInterface extends xMapResolveMetadataInterface {
    /**
     * Formatted source code associated with the resolved item.
     *
     * @remarks
     * Typically used when a resolved file needs to preserve or expose its
     * transformed code representation for later processing or display.
     *
     * @since 2.2.5
     */
    formatCode?: string;
}
/**
 * Separates glob patterns into include and exclude arrays.
 *
 * @param globs - Array of glob patterns (patterns starting with '!' are treated as excludes)
 * @returns Object containing separate include and exclude pattern arrays
 *
 * @example
 * ```ts
 * const { include, exclude } = parseGlobs([
 *   '**\/*.ts',
 *   '!**\/*.test.ts',
 *   '**\/*.js',
 *   '!node_modules/**'
 * ]);
 * // include: ['**\/*.ts', '**\/*.js']
 * // exclude: ['**\/*.test.ts', 'node_modules/**']
 * ```
 *
 * @since 2.0.0
 */
declare function parseGlobs(globs: Array<string>): ParseGlobInterface;
/**
 * Checks if a path matches any pattern in the provided array.
 *
 * @param p - Path to test against patterns
 * @param patterns - Array of glob patterns to match against
 * @returns True if a path matches at least one pattern, false otherwise
 *
 * @remarks
 * Uses early exit optimization - stops checking as soon as a match is found.
 * A pattern is treated as a match when either:
 * - The pattern string ends with the provided path
 * - `matchesGlob(p, pattern)` returns true
 *
 * @example
 * ```ts
 * matchesAny('src/app.ts', ['**\/*.ts', '**\/*.js']); // true
 * matchesAny('src/app.ts', ['prefix/src/app.ts']); // true (suffix check)
 * matchesAny('README.md', ['**\/*.ts', '**\/*.js']); // false
 * ```
 *
 * @see matchesGlob
 * @since 2.0.0
 */
declare function matchesAny(p: string, patterns: Array<string>): boolean;
/**
 * Determines if a directory should be excluded from traversal.
 *
 * @param relativePath - Relative path of the directory to check
 * @param exclude - Array of glob patterns for exclusion
 * @returns True if directory matches any exclude pattern, false otherwise
 *
 * @remarks
 * Checks both the directory path itself and the directory with `/**` appended
 * to properly handle patterns like `node_modules/**`.
 *
 * @example
 * ```ts
 * isDirectoryExcluded('node_modules', ['node_modules/**']); // true
 * isDirectoryExcluded('src', ['node_modules/**']); // false
 * ```
 *
 * @see matchesGlob
 * @since 2.0.0
 */
declare function isDirectoryExcluded(relativePath: string, exclude: Array<string>): boolean;
/**
 * Determines if a file should be included based on include and exclude patterns.
 *
 * @param relativePath - Relative path of the file to check
 * @param include - Array of glob patterns for inclusion
 * @param exclude - Array of glob patterns for exclusion
 * @returns True if file matches include patterns and not exclude patterns, false otherwise
 *
 * @remarks
 * A file must match at least one include pattern AND not match any exclude pattern
 * to be considered for inclusion.
 *
 * @example
 * ```ts
 * shouldIncludeFile('src/app.ts', ['**\/*.ts'], ['**\/*.test.ts']); // true
 * shouldIncludeFile('src/app.test.ts', ['**\/*.ts'], ['**\/*.test.ts']); // false
 * ```
 *
 * @see matchesAny
 * @since 2.0.0
 */
declare function shouldIncludeFile(relativePath: string, include: Array<string>, exclude: Array<string>): boolean;
/**
 * Collects files matching glob patterns from a directory tree.
 *
 * @param baseDir - Base directory to start searching from
 * @param globs - Array of glob patterns (use '!' prefix to exclude)
 * @returns Record mapping file paths without extension to full file paths
 *
 * @remarks
 * This function performs a depth-first traversal with several optimizations:
 * - Separates include/exclude patterns once upfront
 * - Early exits on excluded directories to avoid unnecessary traversal
 * - Returns Record instead of Array for O(1) lookups
 * - Keys are relative to baseDir (without extension)
 * - Values are relative to process.cwd() (with extension)
 * - Optimized with cached length calculations and index-based loops
 * - Avoids unnecessary string allocations
 *
 * @example
 * ```ts
 * // If baseDir is 'src' and file is at <cwd>/src/errors/uncaught-error.spec.ts
 * const files = collectFilesFromGlob('src', ['**\/*.ts']);
 * // Returns: { 'errors/uncaught-error.spec': 'src/errors/uncaught-error.spec.ts' }
 * ```
 *
 * @since 2.0.0
 */
declare function collectFilesFromGlob(baseDir: string, globs: Array<string>): Record<string, string>;
/**
 * Result of parsing glob patterns into include and exclude arrays.
 *
 * @remarks
 * This interface is returned by the {@link parseGlobs} function to separate
 * glob patterns based on their prefix. Patterns without a prefix are included,
 * while patterns starting with '!' are excluded (with the '!' removed).
 *
 * @example
 * ```ts
 * const result: ParseGlobInterface = {
 *   include: ['**\/*.ts', '**\/*.js'],
 *   exclude: ['**\/*.test.ts', 'node_modules/**']
 * };
 * ```
 *
 * @see {@link parseGlobs}
 *
 * @since 2.0.0
 */
interface ParseGlobInterface {
    /**
     * Array of glob patterns for files to include.
     *
     * @remarks
     * These patterns do not have the '!' prefix and represent
     * files that should be matched and included in results.
     *
     * @since 2.0.0
     */
    include: Array<string>;
    /**
     * Array of glob patterns for files to exclude.
     *
     * @remarks
     * These patterns originally had the '!' prefix (which is removed)
     * and represent files that should be excluded from results.
     *
     * @since 2.0.0
     */
    exclude: Array<string>;
}
/**
 * Type alias for build-time definition values used in conditional compilation.
 *
 * @remarks
 * This type represents the structure of the `define` configuration object that controls
 * conditional macro behavior. Each key is a definition name referenced by `$$ifdef` or
 * `$$ifndef` macros, and the value determines whether the macro is included or excluded.
 *
 * **Value interpretation**:
 * - Truthy values (`true`, non-zero numbers, non-empty strings): Definition is considered "defined"
 * - Falsy values (`false`, `0`, `''`, `null`, `undefined`): Definition is considered "not defined"
 *
 * The values can be any type, but are typically booleans for clarity. JavaScript's truthiness
 * rules are applied when evaluating macro conditions.
 *
 * @example Basic boolean definitions
 * ```ts
 * const defines: DefinesType = {
 *   DEBUG: true,
 *   PRODUCTION: false,
 *   TEST: false
 * };
 * ```
 *
 * @example Mixed value types
 * ```ts
 * const defines: DefinesType = {
 *   DEBUG: true,
 *   LOG_LEVEL: 'info',        // Truthy (non-empty string)
 *   MAX_RETRIES: 3,            // Truthy (non-zero number)
 *   EXPERIMENTAL: 0,           // Falsy
 *   FEATURE_FLAG: undefined    // Falsy
 * };
 * ```
 *
 * @example Usage in configuration
 * ```ts
 * const config = {
 *   define: {
 *     DEBUG: process.env.NODE_ENV !== 'production',
 *     API_URL: process.env.API_URL || 'http://localhost:3000'
 *   }
 * };
 * ```
 *
 * @see {@link StateInterface.defines} for usage context
 * @see {@link isDefinitionMet} for condition evaluation logic
 *
 * @since 2.0.0
 */
type DefinesType = Record<string, unknown>;
/**
 * Build execution context available to macro transformation logic.
 *
 * @remarks
 * Groups runtime build metadata and configuration needed by macros during AST processing:
 * - `variantName`: active build variant identifier
 * - `argv`: provider command-line/config arguments
 * - `options`: effective esbuild `BuildOptions` for the current build
 *
 * This object is read by macro handlers to make variant-aware and build-aware decisions.
 *
 * @since 2.2.0
 */
interface MacroContextInterface {
    /**
     * The current build variant name.
     *
     * @remarks
     * Identifies which variant is being transformed (for example, `development`
     * or `production`). This value is propagated through macro processing so
     * diagnostics and generated output can be associated with the correct variant.
     *
     * @example
     * ```ts
     * $$inline(() => {
     *     console.log(variantName);
     * });
     * ```
     *
     * @since 2.2.0
     */
    variantName: string;
    /**
     * Command-line arguments and configuration options passed to the provider.
     *
     * @remarks
     * Contains all CLI options and flags passed when the provider was created.
     * Available to all handlers for accessing build-specific configuration like
     * debug flags, output paths, or custom settings.
     *
     * @example
     * ```ts
     * context.argv; // { debug: true, verbose: false, outdir: 'dist' }
     * ```
     *
     * @since 2.2.0
     */
    argv: Record<string, unknown>;
    /**
     * esbuild configuration options used for this lifecycle execution.
     *
     * @remarks
     * These options represent the active build configuration for the provider and
     * are intended to be read by lifecycle handlers when build behavior depends on
     * entry points, output settings, plugins, or other esbuild flags.
     *
     * @since 2.2.0
     */
    options: BuildOptions;
}
/**
 * Represents the complete state during macro transformation of a source file.
 *
 * @remarks
 * This interface encapsulates all data needed during AST traversal and macro transformation.
 * It provides:
 * - **Metadata access**: Build stage information including disabled macro names
 * - **Configuration**: Build-time definitions controlling conditional compilation
 * - **Source information**: TypeScript AST and original file content
 * - **Diagnostic collection**: Arrays for warnings and errors during transformation
 *
 * The state is passed through the entire transformation pipeline, allowing functions
 * to access configuration, collect diagnostics, and track the transformation process.
 *
 * **State lifecycle**:
 * 1. Created in {@link transformerDirective} with initial configuration
 * 2. Passed to {@link astProcess} for transformation
 * 3. Passed to individual node processors ({@link isVariableStatement}, {@link isCallExpression})
 * 4. Passed to macro transformers ({@link astInlineVariable}, {@link astDefineVariable})
 * 5. Diagnostics extracted and returned in the final result
 *
 * @example State initialization
 * ```ts
 * const state: StateInterface = {
 *   stage: stage as MacrosStaeInterface,
 *   defines: { DEBUG: true, PRODUCTION: false },
 *   sourceFile: languageService.getProgram()?.getSourceFile(path)!,
 *   contents: fileContents,
 *   errors: [],
 *   warnings: []
 * };
 * ```
 *
 * @example Collecting diagnostics during transformation
 * ```ts
 * function processNode(node: Node, state: StateInterface): void {
 *   if (isInvalidMacro(node)) {
 *     state.warnings.push({
 *       text: 'Invalid macro usage',
 *       location: getLocation(node, state.sourceFile)
 *     });
 *   }
 * }
 * ```
 *
 * @example Accessing definitions
 * ```ts
 * function shouldIncludeMacro(name: string, state: StateInterface): boolean {
 *   const value = state.defines[name];
 *   return name in state.defines && !!value;
 * }
 * ```
 *
 * @see {@link transformerDirective} for state creation
 * @see {@link astProcess} for state usage during transformation
 * @see {@link MacrosStateInterface} for stage metadata structure
 *
 * @since 2.0.0
 */
interface StateInterface {
    /**
     * The build stage containing macro analysis metadata.
     *
     * @remarks
     * Provides access to metadata collected during the analysis phase, including:
     * - Set of files containing macros
     * - Set of disabled macro names (based on definitions)
     *
     * This metadata is used to optimize transformation by skipping files without
     * macros and replacing disabled macro references with `undefined`.
     *
     * @see {@link MacrosStateInterface} for metadata structure
     * @see {@link analyzeMacroMetadata} for metadata generation
     *
     * @since 2.0.0
     */
    stage: MacrosStateInterface;
    /**
     * Array of error messages collected during transformation.
     *
     * @remarks
     * Contains partial esbuild messages representing errors that occurred during
     * macro processing. Common error sources include:
     * - Invalid macro syntax
     * - Runtime errors during inline code evaluation
     * - TypeScript compilation errors
     *
     * Errors are non-fatal during transformation but are reported in the final result
     * and may cause the build to fail.
     *
     * @example Adding an error
     * ```ts
     * state.errors.push({
     *   text: 'Cannot evaluate inline macro',
     *   location: { file: filePath, line: 42, column: 10 }
     * });
     * ```
     *
     * @since 2.0.0
     */
    errors: Array<PartialMessage>;
    /**
     * Build-time definitions controlling conditional macro inclusion.
     *
     * @remarks
     * A record mapping definition names to their values. Used by `$$ifdef` and `$$ifndef`
     * macros to determine whether code should be included in the build output.
     *
     * Typically sourced from `variant.config.define` in the build configuration.
     *
     * @example
     * ```ts
     * const state: StateInterface = {
     *   defines: {
     *     DEBUG: true,
     *     PRODUCTION: false,
     *     API_URL: 'https://api.example.com'
     *   },
     *   // ... other properties
     * };
     * ```
     *
     * @see {@link DefinesType} for type structure
     * @see {@link isDefinitionMet} for evaluation logic
     *
     * @since 2.0.0
     */
    defines: DefinesType;
    /**
     * Array of warning messages collected during transformation.
     *
     * @remarks
     * Contains partial esbuild messages representing non-fatal issues discovered
     * during macro processing. Common warning sources include:
     * - Macro names missing the `$$` prefix convention
     * - References to undefined functions in inline macros
     * - Deprecated macro patterns
     *
     * Warnings do not prevent successful transformation but indicate potential issues.
     *
     * @example Adding a warning
     * ```ts
     * state.warnings.push({
     *   text: `Function ${functionName} not found`,
     *   location: { file: filePath, line: 10, column: 5 }
     * });
     * ```
     *
     * @since 2.0.0
     */
    warnings: Array<PartialMessage>;
    /**
     * The current file content being transformed.
     *
     * @remarks
     * Contains the complete source file text. During transformation, this content
     * is modified by applying replacement operations. The final transformed content
     * is returned in the build result.
     *
     * Updated during the transformation process as macros are replaced with their
     * expanded or evaluated forms.
     *
     * @since 2.0.0
     */
    contents: string;
    /**
     * The TypeScript source file AST.
     *
     * @remarks
     * Provides the parsed Abstract Syntax Tree of the source file, used for:
     * - AST traversal to locate macro calls
     * - Text extraction from AST nodes
     * - Position calculation for diagnostics
     * - Source location mapping
     *
     * Obtained from TypeScript's language service and represents the current
     * state of the file in the compilation.
     *
     * @since 2.0.0
     */
    sourceFile: SourceFile;
    /**
     * Build execution context available to macro transformation logic.
     *
     * @remarks
     * Groups runtime build metadata and configuration needed by macros during AST processing:
     * - `variantName`: active build variant identifier
     * - `argv`: provider command-line/config arguments
     * - `options`: effective esbuild `BuildOptions` for the current build
     *
     * This object is read by macro handlers to make variant-aware and build-aware decisions.
     *
     * @since 2.2.0
     */
    context: MacroContextInterface;
}
/**
 * Represents a text substitution operation for macro replacement.
 *
 * @remarks
 * This interface defines a single replacement operation to be performed on source code
 * during macro transformation. Each substitution specifies:
 * - The region of text to replace (via start and end positions)
 * - The replacement text to insert
 *
 * Substitutions are collected during AST traversal and applied in reverse order
 * (from end to start) to avoid position invalidation as earlier replacements
 * are applied.
 *
 * **Position handling**:
 * - Positions are character offsets from the start of the file (0-based)
 * - `start` is inclusive (first character to replace)
 * - `end` is exclusive (one past the last character to replace)
 * - Region length: `end - start`
 *
 * **Application strategy**:
 * Replacements are sorted by `start` position in descending order before application,
 * ensuring that later positions are replaced first, preventing earlier replacements
 * from shifting positions of subsequent replacements.
 *
 * @example Basic substitution
 * ```ts
 * const subst: SubstInterface = {
 *   start: 50,  // Start of the macro call
 *   end: 85,    // End of macro call
 *   replacement: 'function $$debug() { return console.log; }'
 * };
 * ```
 *
 * @example Replacing a macro with undefined
 * ```ts
 * // Replace disabled macro reference
 * const subst: SubstInterface = {
 *   start: 120,
 *   end: 127,  // Length of '$$debug'
 *   replacement: 'undefined'
 * };
 * ```
 *
 * @example Multiple substitutions
 * ```ts
 * const replacements: SubstInterface[] = [
 *   { start: 100, end: 150, replacement: 'transformed1' },
 *   { start: 50, end: 80, replacement: 'transformed2' }
 * ];
 *
 * // Sort by start position (descending)
 * replacements.sort((a, b) => b.start - a.start);
 *
 * // Apply in reverse order
 * for (const subst of replacements) {
 *   content = content.slice(0, subst.start) +
 *             subst.replacement +
 *             content.slice(subst.end);
 * }
 * ```
 *
 * @see {@link isVariableStatement} for substitution creation
 * @see {@link astProcess} for substitution collection and application
 *
 * @since 2.0.0
 */
interface SubstInterface {
    /**
     * The exclusive end position of the text region to replace.
     *
     * @remarks
     * Character offset representing one position past the last character to replace.
     * The character at this position is not included in the replacement.
     *
     * Obtained from `node.getEnd()` on the AST node being replaced.
     *
     * @since 2.0.0
     */
    end: number;
    /**
     * The inclusive start position of the text region to replace.
     *
     * @remarks
     * Character offset representing the first character to replace in the source text.
     * The character at this position is included in the replacement.
     *
     * Obtained from `node.getStart(sourceFile)` on the AST node being replaced.
     *
     * @since 2.0.0
     */
    start: number;
    /**
     * The replacement text to insert at the specified position.
     *
     * @remarks
     * The complete text that will replace the region defined by `start` and `end`.
     * Can be:
     * - Transformed macro code (function declarations, constants)
     * - Evaluated inline results
     * - The string `'undefined'` for disabled macros
     * - Empty string for removed macros
     *
     * @example
     * ```ts
     * replacement: 'function $$debug() { return console.log; }'
     * replacement: 'undefined'
     * replacement: 'export const API_URL = "https://api.example.com";'
     * replacement: ''
     * ```
     *
     * @since 2.0.0
     */
    replacement: string;
}
/**
 * Metadata collected during macro analysis for a build variant.
 *
 * @remarks
 * This interface stores essential information about macro usage across the project,
 * used during the transformation phase to:
 * - Determine which files need macro processing
 * - Identify which macro functions should be removed
 * - Optimize build performance by skipping files without macros
 *
 * Both sets use absolute file paths for accurate file identification.
 *
 * @example Metadata after analyzing a project
 * ```ts
 * const metadata: MacrosMetadataInterface = {
 *   filesWithMacros: new Set([
 *     '/project/src/index.ts',
 *     '/project/src/config.ts',
 *     '/project/src/features/analytics.ts'
 *   ]),
 *   disabledMacroNames: new Set([
 *     '$$noProd',      // from $$ifndef('PRODUCTION') when PRODUCTION=true
 *     '$$devOnly',     // from $$ifdef('DEVELOPMENT') when DEVELOPMENT=false
 *     '$$testMode'     // from $$ifdef('TEST') when TEST=false
 *   ])
 * };
 * ```
 *
 * @example Using metadata for optimization
 * ```ts
 * function shouldProcessFile(filePath: string, metadata: MacrosMetadataInterface): boolean {
 *   // Skip files that don't contain any macros
 *   return metadata.filesWithMacros.has(filePath);
 * }
 *
 * function shouldRemoveMacro(macroName: string, metadata: MacrosMetadataInterface): boolean {
 *   // Check if macro should be stripped from output
 *   return metadata.disabledMacroNames.has(macroName);
 * }
 * ```
 *
 * @example Building metadata incrementally
 * ```ts
 * const metadata: MacrosMetadataInterface = {
 *   filesWithMacros: new Set(),
 *   disabledMacroNames: new Set()
 * };
 *
 * // During analysis
 * if (fileContainsMacros(file)) {
 *   metadata.filesWithMacros.add(file);
 * }
 *
 * // When a macro is disabled by definitions
 * if (shouldDisableMacro(macro, defines)) {
 *   metadata.disabledMacroNames.add(macro);
 * }
 * ```
 *
 * @see {@link analyzeMacroMetadata} for the function that generates this metadata
 * @see {@link MacrosStateInterface} for the stage interface that contains this metadata
 *
 * @since 2.0.0
 */
interface MacrosMetadataInterface {
    /**
     * Set of absolute file paths that contain macro expressions.
     *
     * @remarks
     * Files in this set require macro transformation during the build process.
     * Files not in this set can skip macro processing entirely, improving build performance.
     *
     * Includes files with any of:
     * - `$$ifdef` expressions
     * - `$$ifndef` expressions
     * - Macro variable declarations
     * - Inline macro calls
     *
     * @example
     * ```ts
     * filesWithMacros: new Set([
     *   '/project/src/config.ts', // Has: const $$debug = $$ifdef('DEBUG', ...)
     *   '/project/src/features.ts', // Has: $$ifdef('ANALYTICS', ...)
     *   '/project/src/utils/logger.ts' // Has: export const $$log = $$ifndef('PROD', ...)
     * ])
     * ```
     *
     * @since 2.0.0
     */
    filesWithMacros: Set<string>;
    /**
     * Set of macro function names that should be removed from the output.
     *
     * @remarks
     * Contains macro names that evaluated to false based on the current build definitions.
     * These macros and their calls will be replaced with `undefined` during transformation.
     *
     * A macro is disabled when:
     * - `$$ifdef('X', ...)` and X is false or undefined
     * - `$$ifndef('X', ...)` and X is true
     *
     * @example
     * ```ts
     * // With definitions: { DEBUG: false, PRODUCTION: true, TEST: false }
     * disabledMacroNames: new Set([
     *   '$$hasDebug', // from $$ifdef('DEBUG', ...) - DEBUG is false
     *   '$$noProd', // from $$ifndef('PRODUCTION', ...) - PRODUCTION is true
     *   '$$testMode' // from $$ifdef('TEST', ...) - TEST is false
     * ])
     * ```
     *
     * @since 2.0.0
     */
    disabledMacroNames: Set<string>;
}
/**
 * Describes a single text replacement produced by macro analysis/transformation.
 *
 * @remarks
 * This is a small helper contract used to capture:
 * - the original source fragment ({@link MacroReplacementInterface.source}), and
 * - the text that should replace it ({@link MacroReplacementInterface.replacement}).
 *
 * It is useful for debugging, reporting, and applying deterministic transformations.
 *
 * @example Recording a replacement
 * ```ts
 * const r: MacroReplacementInterface = {
 *   source: "$$ifdef('DEBUG', () => log())",
 *   replacement: "undefined"
 * };
 * ```
 *
 * @since 2.0.0
 */
interface MacroReplacementInterface {
    /**
     * Original source text that should be replaced.
     *
     * @remarks
     * Typically, this is an exact substring extracted from a file (e.g., a macro call,
     * a macro variable initializer, or any other segment discovered during analysis).
     *
     * Consumers can use this to:
     * - build diagnostics ("what was replaced?")
     * - provide debug output / reports
     * - verify transformations are deterministic
     *
     * @since 2.0.0
     */
    source: string;
    /**
     * Replacement text that should be substituted in place of {@link source}.
     *
     * @remarks
     * This is the final text representation that should appear in the transformed output.
     * For disabled macros this is often `'undefined'`, but it may also be an inlined constant,
     * rewritten function body, or other generated code.
     *
     * @since 2.0.0
     */
    replacement: string;
}
/**
 * Extended lifecycle stage interface with macro-specific metadata.
 *
 * @remarks
 * This interface extends the base {@link LifecycleStageInterface} to include
 * macro analysis metadata, making it available throughout the build lifecycle.
 *
 * The metadata is:
 * - Populated during the analysis phase by {@link analyzeMacroMetadata}
 * - Consumed during the transformation phase by {@link transformerDirective}
 * - Accessible to all lifecycle hooks that need macro information
 *
 * @example Using in build lifecycle
 * ```ts
 * async function onBuild(context: { stage: MacrosStateInterface }) {
 *   const { defineMetadata } = context.stage;
 *
 *   console.log(`Files with macros: ${defineMetadata.filesWithMacros.size}`);
 *   console.log(`Disabled macros: ${defineMetadata.disabledMacroNames.size}`);
 * }
 * ```
 *
 * @example Checking macro status in plugin
 * ```ts
 * function myPlugin(stage: MacrosStateInterface) {
 *   return {
 *     name: 'my-plugin',
 *     setup(build) {
 *       build.onLoad({ filter: /\.ts$/ }, (args) => {
 *         if (!stage.defineMetadata.filesWithMacros.has(args.path)) {
 *           // Skip macro processing for this file
 *           return null;
 *         }
 *
 *         // Process macros...
 *       });
 *     }
 *   };
 * }
 * ```
 *
 * @example Accessing in transformer
 * ```ts
 * function transform(code: string, stage: MacrosStateInterface): string {
 *   const { disabledMacroNames } = stage.defineMetadata;
 *
 *   // Remove disabled macros
 *   for (const macroName of disabledMacroNames) {
 *     code = code.replace(new RegExp(macroName, 'g'), 'undefined');
 *   }
 *
 *   return code;
 * }
 * ```
 *
 * @see {@link analyzeMacroMetadata} for metadata generation
 * @see {@link MacrosMetadataInterface} for metadata structure
 * @see {@link LifecycleStageInterface} for base stage properties
 *
 * @since 2.0.0
 */
interface MacrosStateInterface extends LifecycleStageInterface {
    /**
     * Macro analysis metadata for the current build.
     *
     * @remarks
     * Contains information about:
     * - Which files contain macros and need processing
     * - Which macro names should be removed based on definitions
     *
     * This metadata is shared across all build plugins and transformers
     * to ensure consistent macro handling throughout the build process.
     *
     * @since 2.0.0
     */
    defineMetadata: MacrosMetadataInterface;
    /**
     * Optional map of macro-driven source replacements recorded during transformation.
     *
     * @remarks
     * When present, this can be used for:
     * - debugging ("what exactly changed?"),
     * - producing transformation reports, or
     * - testing/verifying deterministic output.
     *
     * The keys are the name of the variant, and each value is an array of replacements made.
     * Each entry describes the original fragment and its replacement via
     * {@link MacroReplacementInterface}.
     *
     * @example
     * ```ts
     * stage.replacementInfo = {
     *   'index': [
     *     { source: "$$inline(() => 1 + 1)", replacement: "2" },
     *     { source: "$$debug()", replacement: "undefined" }
     *   ],
     *   'config': [
     *     { source: "$$ifdef('PROD', ...)", replacement: "undefined" }
     *   ]
     * };
     * ```
     *
     * @since 2.0.0
     */
    replacementInfo?: Record<string, Array<MacroReplacementInterface>>;
}
/**
 * User-defined command-line options that extend the base xBuild CLI.
 *
 * @remarks
 * This interface allows build configurations to define custom CLI arguments beyond
 * xBuild's built-in options. Each key represents an option name, and each value
 * is a yargs `Options` object defining the argument's type, description, aliases,
 * and validation rules.
 *
 * User extensions enable:
 * - Project-specific build flags (e.g., `--env`, `--feature`)
 * - Custom output configurations
 * - Integration with external tools
 * - Conditional build behavior based on CLI arguments
 *
 * These options are merged with xBuild's default options and appear in the help
 * output under a separate "User Options" section for clarity.
 *
 * The parsed values are accessible in lifecycle hooks and configuration functions,
 * allowing dynamic build behavior based on command-line input.
 *
 * @example
 * ```ts
 * const userExtensions: UserExtensionInterface = {
 *   env: {
 *     describe: 'Build environment',
 *     type: 'string',
 *     choices: ['dev', 'staging', 'prod'],
 *     default: 'dev'
 *   },
 *   feature: {
 *     describe: 'Enable experimental features',
 *     type: 'boolean',
 *     alias: 'f'
 *   }
 * };
 * ```
 *
 * @example
 * ```ts
 * // In build configuration
 * export default {
 *   userArgv: {
 *     deploy: {
 *       describe: 'Deploy after build',
 *       type: 'boolean'
 *     },
 *     target: {
 *       describe: 'Deployment target',
 *       type: 'string',
 *       choices: ['staging', 'production']
 *     }
 *   },
 *   variants: { ... }
 * };
 * ```
 *
 * @see {@link ArgumentsInterface}
 * @see {@link ArgvModule.enhancedParse}
 *
 * @since 2.0.0
 */
interface UserExtensionInterface {
    /**
     * Custom CLI option definition.
     *
     * @remarks
     * Each property defines a command-line argument with its type, description,
     * aliases, and validation using yargs `Options` format.
     *
     * @since 2.0.0
     */
    [key: string]: Options;
}
/**
 * Base structure for parsed command-line arguments from yargs.
 *
 * @remarks
 * This interface represents the minimal structure that all yargs-parsed argument
 * objects contain, regardless of specific options. It includes the standard yargs
 * metadata fields that are always present after parsing.
 *
 * **Standard fields:**
 * - `_`: Positional arguments (non-option values)
 * - `$0`: The script name or path that was executed
 * - Additional dynamic properties for named options
 *
 * This interface serves as the foundation for more specific argument interfaces
 * like `ArgumentsInterface`, which extends it with xBuild-specific options.
 *
 * The index signature allows any additional properties to accommodate both
 * xBuild's default options and user-defined extensions without losing type safety
 * for the core yargs metadata.
 *
 * @example
 * ```ts
 * // Minimal parsed arguments
 * const args: BaseArgumentsInterface = {
 *   _: ['src/index.ts'],
 *   $0: 'xBuild',
 *   config: 'custom.config.ts'
 * };
 * ```
 *
 * @example
 * ```ts
 * // With positional arguments
 * // Command: xBuild src/app.ts src/worker.ts
 * const args: BaseArgumentsInterface = {
 *   _: ['src/app.ts', 'src/worker.ts'],
 *   $0: '/usr/local/bin/xBuild'
 * };
 * ```
 *
 * @see {@link ArgumentsInterface}
 * @see {@link ArgvModule.parseConfigFile}
 *
 * @since 2.0.0
 */
interface BaseArgumentsInterface {
    /**
     * Positional arguments (non-option values).
     *
     * @remarks
     * Contains values provided without option flags. Typically, it includes
     * file paths or commands. Can be strings or numbers depending on parsing context.
     *
     * @example
     * ```ts
     * // Command: xBuild src/index.ts src/utils.ts
     * // _: ['src/index.ts', 'src/utils.ts']
     * ```
     *
     * @since 2.0.0
     */
    _: Array<string | number>;
    /**
     * The script name or path that was executed.
     *
     * @remarks
     * Represents the command used to invoke the script, typically the executable
     * name or full path. Used by yargs to help text generation.
     *
     * @example
     * ```ts
     * $0: 'xBuild'              // When invoked as 'xBuild'
     * $0: '/usr/bin/xBuild'     // Full path
     * $0: 'node build.js'       // When run with Node.js
     * ```
     *
     * @since 2.0.0
     */
    $0: string;
    /**
     * Dynamic properties for parsed command-line options.
     *
     * @remarks
     * Allows any additional properties to represent both xBuild's default options
     * and user-defined extensions. The actual properties present depend on the
     * options configuration and arguments provided.
     *
     * @since 2.0.0
     */
    [argName: string]: unknown;
}
/**
 * Complete parsed command-line arguments including all xBuild options.
 *
 * @remarks
 * This interface extends the base yargs structure with all xBuild-specific CLI
 * options. It represents the fully parsed arguments after running `enhancedParse`
 * with both default options and any user extensions.
 *
 * **Argument categories:**
 *
 * **Input/Output:**
 * - `entryPoints`: Source files to compile
 * - `outdir`: Output directory path
 *
 * **Build Modes:**
 * - `watch`: Enable watch mode for auto-rebuild
 * - `serve`: Start development server (with optional directory)
 * - `typeCheck`: Type check only without output
 *
 * **Build Configuration:**
 * - `bundle`: Bundle dependencies into output
 * - `minify`: Minify output code
 * - `format`: Module format (cjs, esm, iife)
 * - `platform`: Target platform (browser, node, neutral)
 *
 * **TypeScript:**
 * - `types`: Enable type checking during build
 * - `declaration`: Generate .d.ts files
 * - `failOnError`: Fail build on type errors
 * - `tsconfig`: Custom tsconfig path
 *
 * **Configuration:**
 * - `config`: Build configuration file path
 * - `verbose`: Enable detailed logging
 * - `debug`: Debug-specific entry points
 * - `dev`: Development-specific entry points
 *
 * All properties are optional since they may not be provided on the command line.
 * Default values are applied during configuration processing, not during parsing.
 *
 * @example
 * ```ts
 * // Production build
 * const args: ArgumentsInterface = {
 *   _: [],
 *   $0: 'xBuild',
 *   entryPoints: ['src/index.ts'],
 *   bundle: true,
 *   minify: true,
 *   format: 'esm',
 *   outdir: 'dist',
 *   declaration: true
 * };
 * ```
 *
 * @example
 * ```ts
 * // Development mode
 * const args: ArgumentsInterface = {
 *   _: [],
 *   $0: 'xBuild',
 *   entryPoints: ['src/app.ts'],
 *   watch: true,
 *   serve: 'dist',
 *   types: true
 * };
 * ```
 *
 * @example
 * ```ts
 * // Type check only
 * const args: ArgumentsInterface = {
 *   _: [],
 *   $0: 'xBuild',
 *   typeCheck: true,
 *   tsconfig: 'tsconfig.strict.json'
 * };
 * ```
 *
 * @see {@link BaseArgumentsInterface}
 * @see {@link UserExtensionInterface}
 * @see {@link ArgvModule.enhancedParse}
 * @see {@link CLI_DEFAULT_OPTIONS}
 *
 * @since 2.0.0
 */
interface ArgumentsInterface extends BaseArgumentsInterface {
    /**
     * Development-specific entry points for conditional builds.
     *
     * @remarks
     * Optional array of file paths used only in development builds. Allows
     * including additional files (like dev tools, mock data) that shouldn't
     * be in production builds.
     *
     * @example
     * ```ts
     * dev: ['src/dev-tools.ts', 'src/mocks.ts']
     * ```
     *
     * @since 2.0.0
     */
    dev?: Array<string>;
    /**
     * Enable TypeScript type checking during the build process.
     *
     * @remarks
     * When true, runs TypeScript type checker in parallel with esbuild compilation.
     * Type errors are reported but may not fail the build depending on `failOnError`.
     *
     * @example
     * ```ts
     * types: true  // Enable type checking
     * ```
     *
     * @since 2.0.0
     */
    types?: boolean;
    /**
     * Debug-specific entry points for conditional builds.
     *
     * @remarks
     * Optional array of file paths used only in debug builds. Useful for including
     * debugging utilities, loggers, or diagnostic tools.
     *
     * @example
     * ```ts
     * debug: ['src/debug-logger.ts']
     * ```
     *
     * @since 2.0.0
     */
    debug?: Array<string>;
    /**
     * Start development server serving from specified directory.
     *
     * @remarks
     * When provided, starts a local HTTP server to serve build output. The value
     * specifies which directory to serve. Commonly used with watch mode for
     * live development.
     *
     * @example
     * ```ts
     * serve: 'dist'        // Serve from dist/
     * serve: 'public'      // Serve from public/
     * ```
     *
     * @since 2.0.0
     */
    serve?: string;
    /**
     * Directory for build output files.
     *
     * @remarks
     * Specifies where compiled files should be written. Overrides the `outdir`
     * setting in esbuild configuration when provided.
     *
     * @example
     * ```ts
     * outdir: 'dist'
     * outdir: 'build/output'
     * ```
     *
     * @since 2.0.0
     */
    outdir?: string;
    /**
     * Enable watch mode to rebuild on file changes.
     *
     * @remarks
     * When true, the build system watches source files and automatically rebuilds
     * when changes are detected. Often used with `serve` for development workflows.
     *
     * @example
     * ```ts
     * watch: true  // Enable watch mode
     * ```
     *
     * @since 2.0.0
     */
    watch?: boolean;
    /**
     * Path to build a configuration file.
     *
     * @remarks
     * Specifies a custom configuration file instead of the default `config.xbuild.ts`.
     * The file must export a valid `BuildConfigInterface` object.
     *
     * @example
     * ```ts
     * config: 'build/custom.xbuild.ts'
     * config: 'configs/prod.config.ts'
     * ```
     *
     * @since 2.0.0
     */
    config?: string;
    /**
     * Enable minification of build output.
     *
     * @remarks
     * When true, applies code minification including whitespace removal, name
     * mangling, and dead code elimination. Typically used for production builds.
     *
     * @example
     * ```ts
     * minify: true  // Minify output
     * ```
     *
     * @since 2.0.0
     */
    minify?: boolean;
    /**
     * Bundle dependencies into output files.
     *
     * @remarks
     * When true, includes all imported modules in the output. When false, preserves
     * module structure and requires dependencies to be available at runtime.
     *
     * @example
     * ```ts
     * bundle: true   // Bundle everything
     * bundle: false  // Preserve module structure
     * ```
     *
     * @since 2.0.0
     */
    bundle?: boolean;
    /**
     * Output module format for generated code.
     *
     * @remarks
     * Specifies the JavaScript module system to use:
     * - `cjs`: CommonJS (require/module.exports)
     * - `esm`: ECMAScript modules (import/export)
     * - `iife`: Immediately Invoked Function Expression (for browsers)
     *
     * @example
     * ```ts
     * format: 'esm'   // ES modules
     * format: 'cjs'   // CommonJS
     * format: 'iife'  // Browser bundle
     * ```
     *
     * @since 2.0.0
     */
    format?: 'cjs' | 'esm' | 'iife';
    /**
     * Enable verbose logging output during builds.
     *
     * @remarks
     * When true, outputs detailed build information including file processing,
     * hook execution, timing, and diagnostic messages. Useful for debugging.
     *
     * @example
     * ```ts
     * verbose: true  // Detailed output
     * ```
     *
     * @since 2.0.0
     */
    verbose?: boolean;
    /**
     * Target platform for the build output.
     *
     * @remarks
     * Specifies the runtime environment:
     * - `browser`: Web browser environment
     * - `node`: Node.js environment
     * - `neutral`: Platform-agnostic (no platform-specific APIs)
     *
     * Affects module resolution, built-in polyfills, and output format.
     *
     * @example
     * ```ts
     * platform: 'node'     // Node.js target
     * platform: 'browser'  // Browser target
     * platform: 'neutral'  // Universal
     * ```
     *
     * @since 2.0.0
     */
    platform?: Platform;
    /**
     * Path to TypeScript configuration file.
     *
     * @remarks
     * Specifies a custom tsconfig.json instead of the default. Used for both
     * type checking and declaration generation.
     *
     * @example
     * ```ts
     * tsconfig: 'tsconfig.build.json'
     * tsconfig: 'configs/tsconfig.strict.json'
     * ```
     *
     * @since 2.0.0
     */
    tsconfig?: string;
    /**
     * Perform type checking without building output.
     *
     * @remarks
     * When true, runs TypeScript type checker only without executing esbuild
     * compilation. Useful for validating types in CI/CD pipelines or pre-commit hooks.
     *
     * @example
     * ```ts
     * typeCheck: true  // Type check only, no output
     * ```
     *
     * @since 2.0.0
     */
    typeCheck?: boolean;
    /**
     * Generate TypeScript declaration files (.d.ts).
     *
     * @remarks
     * When true, emits TypeScript declaration files alongside JavaScript output.
     * Used for library builds to provide type information to consumers.
     *
     * @example
     * ```ts
     * declaration: true  // Generate .d.ts files
     * ```
     *
     * @since 2.0.0
     */
    declaration?: boolean;
    /**
     * Source files to build (supports glob patterns).
     *
     * @remarks
     * Array of file paths or glob patterns identifying build entry points.
     * Can be provided as positional arguments or via the `--entryPoints` flag.
     *
     * @example
     * ```ts
     * entryPoints: ['src/index.ts']
     * entryPoints: ['src/*.ts', 'src/workers/*.ts']
     * ```
     *
     * @since 2.0.0
     */
    entryPoints?: Array<string>;
    /**
     * Fail build when TypeScript errors are detected.
     *
     * @remarks
     * When true, exits with non-zero code if type checking finds errors.
     * When false, logs errors but continues the build. Used with `types: true`.
     *
     * @example
     * ```ts
     * failOnError: true   // Fail on type errors
     * failOnError: false  // Log errors, continue build
     * ```
     *
     * @since 2.0.0
     */
    failOnError?: boolean;
    /**
     * Array of build variant names to compile from the configuration file.
     *
     * @remarks
     * Specifies which build variants defined in the xBuild configuration should be executed.
     * Build variants allow you to define multiple build configurations (e.g., production, development,
     * testing) in a single configuration file and selectively compile them via the CLI.
     *
     * **Behavior:**
     * - If not specified: All variants in the configuration file are built
     * - If specified: Only the named variants are compiled
     * - Supports multiple values: Can specify multiple variants in a single command
     * - Non-existent variants: Will result in a build error if specified variant doesn't exist
     *
     * **Common use cases:**
     * - Building-only production bundles: `--build production`
     * - Building multiple specific variants: `--build development --build staging`
     * - Selective compilation in CI/CD pipelines
     * - Testing specific build configurations during development
     *
     * Build variants are defined in the xBuild configuration file and can include different:
     * - Entry points and output directories
     * - Compiler options (minification, bundling, source maps)
     * - Target platforms and formats
     * - Environment-specific settings
     *
     * @example
     * ```ts
     * // Build only the production variant
     * xBuild --build production
     * ```
     *
     * @example
     * ```ts
     * // Build multiple specific variants
     * xBuild --build development --build staging
     * // Or using the alias:
     * xBuild --xb development --xb staging
     * ```
     *
     * @example
     * ```ts
     * // Configuration file with variants
     * export default {
     *   variants: {
     *     production: {
     *       entryPoints: ['src/index.ts'],
     *       minify: true,
     *       bundle: true
     *     },
     *     development: {
     *       entryPoints: ['src/index.ts'],
     *       sourcemap: true
     *     }
     *   }
     * };
     *
     * // Build only production
     * xBuild --build production
     * ```
     *
     * @see {@link CLI_CONFIG_PATH} for configuration file location
     *
     * @since 2.0.0
     */
    build?: Array<string>;
}
/**
 * Extended build configuration interface with user-defined CLI arguments and server settings.
 *
 * @remarks
 * This interface extends the base build configuration with xBuild-specific features
 * that aren't part of the core build system but provide additional development and
 * deployment capabilities.
 *
 * **Additional features:**
 * - **User-defined CLI arguments**: Extend the command-line interface with custom options
 * - **Development server**: Configure and control the built-in HTTP server
 *
 * This is the top-level configuration interface used by configuration files and represents
 * the complete set of options available in `config.xbuild.ts` files.
 *
 * The interface combines:
 * - Build variant definitions from {@link PartialBuildConfigType}
 * - Common build settings
 * - Custom CLI arguments via `userArgv`
 * - Development server configuration via `serve`
 *
 * @example
 * ```ts
 * // Complete configuration file
 * const config: xBuildConfigInterface = {
 *   verbose: true,
 *   common: {
 *     types: true,
 *     declaration: { bundle: true }
 *   },
 *   variants: {
 *     esm: {
 *       esbuild: {
 *         entryPoints: ['src/index.ts'],
 *         format: 'esm',
 *         outdir: 'dist'
 *       }
 *     }
 *   },
 *   userArgv: {
 *     env: {
 *       type: 'string',
 *       choices: ['dev', 'prod'],
 *       default: 'dev'
 *     }
 *   },
 *   serve: {
 *     dir: 'dist',
 *     port: 3000,
 *     start: true
 *   }
 * };
 * ```
 *
 * @see {@link configFileProvider}
 * @see {@link PartialBuildConfigType}
 * @see {@link ServerConfigurationInterface}
 *
 * @since 2.0.0
 */
interface xBuildConfigInterface extends PartialBuildConfigType {
    /**
     * Custom command-line argument definitions for the build system.
     *
     * @remarks
     * Defines additional CLI flags and options beyond xBuild's defaults using the yargs
     * options format. These arguments are parsed from the command line and made available
     * throughout the build system via the `argv` context parameter.
     *
     * **Use cases:**
     * - Project-specific build modes (e.g., `--env`, `--target`)
     * - Feature flags for conditional compilation
     * - Custom output configurations
     * - Integration parameters for external tools
     * - Deployment targets and options
     *
     * Each option can specify:
     * - `type`: Data type (string, number, boolean, array)
     * - `description`: Help text displayed in `--help` output
     * - `alias`: Short flag alternatives
     * - `default`: Default value when not provided
     * - `choices`: Valid values for validation
     * - `demandOption`: Whether the option is required
     *
     * Parsed values are accessible in lifecycle hooks via `context.argv`, enabling
     * dynamic build behavior based on command-line input.
     *
     * These options appear in the CLI help output under a dedicated "User Options"
     * section, separate from xBuild's core options.
     *
     * @example
     * ```ts
     * userArgv: {
     *   watch: {
     *     type: 'boolean',
     *     description: 'Enable watch mode',
     *     default: false,
     *     alias: 'w'
     *   },
     *   env: {
     *     type: 'string',
     *     description: 'Target environment',
     *     choices: ['development', 'staging', 'production'],
     *     default: 'development'
     *   },
     *   deploy: {
     *     type: 'boolean',
     *     description: 'Deploy after successful build',
     *     default: false
     *   }
     * }
     * ```
     *
     * @example
     * ```ts
     * // Access in lifecycle hooks
     * {
     *   lifecycle: {
     *     onSuccess: async (context) => {
     *       if (context.argv.deploy) {
     *         await deployToEnvironment(context.argv.env);
     *       }
     *     }
     *   },
     *   userArgv: {
     *     deploy: { type: 'boolean' },
     *     env: { type: 'string', choices: ['dev', 'prod'] }
     *   }
     * }
     * ```
     *
     * @example
     * ```ts
     * // Command line usage
     * // xBuild --env production --deploy
     * // Parsed as: { env: 'production', deploy: true }
     * ```
     *
     * @see {@link Options}
     * @see {@link UserExtensionInterface}
     * @see {@link ArgvModule.enhancedParse}
     *
     * @since 2.0.0
     */
    userArgv?: Record<string, Options>;
    /**
     * Development server configuration and control.
     *
     * @remarks
     * Configures the built-in HTTP development server for serving build output during
     * development. The server supports live reloading, static file serving, and can be
     * integrated with watch mode for an efficient development workflow.
     *
     * **Configuration options:**
     * - `dir`: Directory to serve files from (required)
     * - `start`: Whether to automatically start the server (optional)
     * - Additional server options from {@link ServerConfigurationInterface}:
     *   - Port number
     *   - Host address
     *   - HTTPS configuration
     *   - CORS settings
     *   - Custom middleware
     *
     * The server is particularly useful when combined with watch mode, automatically
     * serving updated builds as files change.
     *
     * When `start` is true, the server starts automatically after the initial build.
     * When false or omitted, the server configuration is available but must be started
     * manually or via CLI flags.
     *
     * @example
     * ```ts
     * // Basic server configuration
     * serve: {
     *   dir: 'dist',
     *   port: 3000,
     *   start: true
     * }
     * ```
     *
     * @example
     * ```ts
     * // Advanced server with HTTPS
     * serve: {
     *   dir: 'public',
     *   port: 8080,
     *   host: '0.0.0.0',
     *   start: true,
     *   https: {
     *     key: './certs/key.pem',
     *     cert: './certs/cert.pem'
     *   }
     * }
     * ```
     *
     * @example
     * ```ts
     * // Combined with watch mode
     * {
     *   variants: {
     *     dev: {
     *       esbuild: {
     *         entryPoints: ['src/app.ts'],
     *         outdir: 'dist'
     *       }
     *     }
     *   },
     *   serve: {
     *     dir: 'dist',
     *     port: 3000,
     *     start: true
     *   }
     * }
     * // Command: xBuild --watch
     * // Serves from dist/ with auto-reload on file changes
     * ```
     *
     * @see {@link ServerConfigurationInterface}
     *
     * @since 2.0.0
     */
    serve?: ServerConfigurationInterface & {
        dir: string;
        start?: boolean;
    };
}
/**
 * Type alias for xBuild configuration objects.
 *
 * @remarks
 * Provides a shorter, more conventional name for the configuration interface.
 * Used primarily in configuration files to declare configuration object types
 * with TypeScript's `satisfies` operator or type annotations.
 *
 * **Properties include**:
 * - `variants`: Build variant configurations (dev, prod, etc.)
 * - `common`: Shared settings across all variants
 * - `serve`: Development server configuration
 * - `userArgv`: Custom CLI argument definitions
 * - `verbose`: Detailed logging flag
 *
 * @example Type annotation
 * ```ts
 * const config: xBuildConfig = {
 *   variants: {
 *     production: {
 *       esbuild: { minify: true, outdir: 'dist' }
 *     }
 *   }
 * };
 * ```
 *
 * @example With satisfies operator (recommended)
 * ```ts
 * export default {
 *   common: { esbuild: { platform: 'node' } },
 *   variants: {
 *     dev: { esbuild: { minify: false } },
 *     prod: { esbuild: { minify: true } }
 *   }
 * } satisfies xBuildConfig;
 * ```
 *
 * @see {@link xBuildConfigInterface} for detailed property documentation
 *
 * @since 2.0.0
 */
type xBuildConfig = xBuildConfigInterface;
/**
 * Global type declarations for xBuild's build-time macro system.
 *
 * @remarks
 * Declares globally available macro functions that are transformed at build time.
 * These functions provide conditional compilation and inline evaluation capabilities
 * without requiring explicit imports.
 *
 * **Macro functions**:
 * - `$$ifdef`: Include code when definition is truthy
 * - `$$ifndef`: Include code when definition is falsy/undefined
 * - `$$inline`: Evaluate expressions at build time
 *
 * All macro functions are:
 * - Prefixed with `$$` to avoid naming conflicts
 * - Transformed during the build process (not runtime functions)
 * - Available globally without imports
 * - Type-safe with TypeScript
 *
 * **DefineType**: String literal union representing common definition names,
 * extensible with custom strings via `| string`.
 *
 * @example Conditional compilation
 * ```ts
 * const logger = $$ifdef('DEBUG', () => console.log);
 * // In production (DEBUG=false), becomes: const logger = undefined;
 * // In development (DEBUG=true), becomes: function logger() { return console.log; }
 * ```
 *
 * @example Negated conditional
 * ```ts
 * const optimized = $$ifndef('DEBUG', () => fastImplementation());
 * // Included only when DEBUG is not defined or false
 * ```
 *
 * @example Inline evaluation
 * ```ts
 * const version = $$inline(() => process.env.VERSION);
 * // Evaluates at build time, replaces with actual value
 * ```
 *
 * @see {@link transformerDirective} for macro transformation implementation
 *
 * @since 2.0.0
 */
declare global {
    /**
     * Type representing valid definition names for conditional macros.
     *
     * @remarks
     * Provides autocomplete for common definition names while allowing
     * custom strings. Definitions are typically set via:
     * - `config.variants[name].define` in configuration
     * - `--define` CLI flag
     * - Environment variables
     *
     * **Common definitions**:
     * - `DEBUG`: Development/debugging features
     * - `PRODUCTION`: Production-only optimizations
     * - `TEST`: Test environment features
     * - `DEV`: Development mode
     * - `CI`: Continuous integration environment
     * - `LOCAL`: Local development
     *
     * @example
     * ```ts
     * // With type checking
     * const fn = $$ifdef('DEBUG', log); // 'DEBUG' autocompletes
     * const custom = $$ifdef('MY_FEATURE', impl); // Custom string also allowed
     * ```
     *
     * @since 2.0.0
     */
    type DefineType = 'DEBUG' | 'PRODUCTION' | 'TEST' | 'DEV' | 'CI' | 'LOCAL' | string;
    /**
     * Conditional inclusion macro that includes code when a definition is truthy.
     *
     * @template T - The type of the callback return value
     * @param define - The definition name to check
     * @param callback - The code to include when definition is truthy
     *
     * @returns The callback value when condition is true, `undefined` when false
     *
     * @remarks
     * Transformed at build time based on the variant's `define` configuration.
     * When the specified definition is truthy, the callback is included in the
     * output; otherwise, the entire expression is replaced with `undefined`.
     *
     * **Transformation behavior**:
     * - Definition is truthy → Callback is included as-is
     * - Definition is falsy/undefined → Replaced with `undefined`
     * - Works with functions, objects, primitives, or any expression
     *
     * **Variable declarations**:
     * ```ts
     * const $$debug = $$ifdef('DEBUG', () => console.log);
     * // DEBUG=true → function $$debug() { return console.log; }
     * // DEBUG=false → undefined (entire declaration removed)
     * ```
     *
     * **Expression statements**:
     * ```ts
     * $$ifdef('DEBUG', () => initDebugTools());
     * // DEBUG=true → (() => initDebugTools())()
     * // DEBUG=false → (removed)
     * ```
     *
     * @example Function inclusion
     * ```ts
     * const logger = $$ifdef('DEBUG', () => console.log);
     *
     * // With DEBUG=true
     * logger('test'); // Works: logs 'test'
     *
     * // With DEBUG=false
     * logger('test'); // TypeError: logger is undefined
     * ```
     *
     * @example Object inclusion
     * ```ts
     * const config = {
     *   apiUrl: 'https://api.example.com',
     *   debug: $$ifdef('DEBUG', { verbose: true, logLevel: 'trace' })
     * };
     *
     * // With DEBUG=true
     * // config.debug = { verbose: true, logLevel: 'trace' }
     *
     * // With DEBUG=false
     * // config.debug = undefined
     * ```
     *
     * @example Guards in code
     * ```ts
     * if ($$ifdef('DEBUG', true)) {
     *   console.log('Debug mode active');
     * }
     * // DEBUG=false → if (undefined) { ... } (block never executes)
     * ```
     *
     * @see {@link DefineType} for valid definition names
     * @since 2.0.0
     */
    function $$ifdef<T>(define: DefineType, callback: T): T extends (...args: infer A) => infer R ? (...args: A) => R | undefined : T | undefined;
    /**
     * Conditional inclusion macro that includes code when a definition is falsy or undefined.
     *
     * @template T - The type of the callback return value
     * @param define - The definition name to check
     * @param callback - The code to include when definition is falsy/undefined
     *
     * @returns The callback value when condition is false, `undefined` when true
     *
     * @remarks
     * The inverse of `$$ifdef`. Transformed at build time based on the
     * variant's `define` configuration. When the specified definition is falsy
     * or undefined, the callback is included; otherwise, replaced with `undefined`.
     *
     * **Transformation behavior**:
     * - Definition is falsy/undefined → Callback is included as-is
     * - Definition is truthy → Replaced with `undefined`
     * - Works with functions, objects, primitives, or any expression
     *
     * **Use cases**:
     * - Development-only features (disabled in production)
     * - Fallback implementations (when optimized version unavailable)
     * - Debugging tools (removed in release builds)
     *
     * @example Development-only features
     * ```ts
     * const devTools = $$ifndef('PRODUCTION', () => initDevTools());
     *
     * // With PRODUCTION=false (dev mode)
     * devTools(); // Works: initializes dev tools
     *
     * // With PRODUCTION=true (production)
     * devTools(); // TypeError: devTools is undefined
     * ```
     *
     * @example Fallback implementation
     * ```ts
     * const optimizer = $$ifndef('NATIVE_OPTIMIZER', () => jsOptimizer());
     *
     * // With NATIVE_OPTIMIZER undefined
     * // Uses JavaScript fallback implementation
     *
     * // With NATIVE_OPTIMIZER=true
     * // optimizer is undefined, use native implementation elsewhere
     * ```
     *
     * @example Conditional exports
     * ```ts
     * export const debug = $$ifndef('PRODUCTION', {
     *   log: console.log,
     *   trace: console.trace
     * });
     *
     * // In development: exports debug object
     * // In production: export const debug = undefined;
     * ```
     *
     * @see {@link DefineType} for valid definition names
     * @since 2.0.0
     */
    function $$ifndef<T>(define: DefineType, callback: T): T extends (...args: infer A) => infer R ? (...args: A) => R | undefined : T | undefined;
    /**
     * Inline evaluation macro that executes code at build time and replaces it with the result.
     *
     * @template T - The return type of the callback function
     * @param callback - Expression to evaluate at build time
     *
     * @returns The evaluated result with its original type, or `undefined` on evaluation failure
     *
     * @remarks
     * Executes the provided callback during the build process (not at runtime) and
     * replaces the macro call with the evaluated result. This enables:
     * - Injecting build-time environment variables
     * - Computing values during compilation
     * - Generating code from external sources
     * - Eliminating runtime overhead for static values
     *
     * **Execution context**:
     * - Runs in the Node.js build environment
     * - Has access to process.env and Node.js APIs
     * - Executes once per build, not per file or variant
     * - Errors during evaluation cause build failure
     *
     * **Return value handling**:
     * - The result preserves the original return type from the callback
     * - Primitives (string, number, boolean) are properly typed
     * - Objects and arrays maintain their structure and types
     * - Functions are toString()'d (use carefully)
     * - Returns `undefined` if evaluation fails or callback returns undefined
     *
     * **Common use cases**:
     * - Environment variable injection
     * - Build timestamp generation
     * - Package version embedding
     * - Configuration value computation
     *
     * @example Environment variable injection
     * ```ts
     * const apiUrl = $$inline(() => process.env.API_URL);
     * // Type: string | undefined
     * // Becomes: const apiUrl = "https://api.example.com";
     * ```
     *
     * @example Build metadata
     * ```ts
     * const buildInfo = {
     *   version: $$inline(() => require('./package.json').version),
     *   timestamp: $$inline(() => new Date().toISOString()),
     *   commit: $$inline(() => process.env.GIT_COMMIT)
     * };
     * // Each value retains its type (string | undefined)
     * ```
     *
     * @example Computed configuration
     * ```ts
     * const maxWorkers = $$inline(() => {
     *   const cpus = require('os').cpus().length;
     *   return Math.max(1, cpus - 1);
     * });
     * // Type: number | undefined
     * // Computes optimal worker count during build
     * ```
     *
     * @example Feature flags from environment
     * ```ts
     * const features = {
     *   betaFeatures: $$inline(() => process.env.ENABLE_BETA === 'true'),
     *   debugMode: $$inline(() => process.env.NODE_ENV !== 'production')
     * };
     * // Boolean values computed at build time, typed as boolean | undefined
     * ```
     *
     * @see {@link astInlineCallExpression} for evaluation implementation
     *
     * @since 2.0.0
     */
    function $$inline<T>(callback: () => T): T | undefined;
    /**
     * Pre-configuration CLI arguments snapshot (bootstrap argv).
     *
     * @remarks
     * A globally accessible object used during early CLI bootstrap to store the result of
     * the *minimal* argument parse (typically just enough to locate the config file).
     *
     * This is useful when later stages need access to the initial argv values before the
     * full, enhanced parse (with user extensions) is performed.
     *
     * **Intended usage:**
     * - Set once at startup (e.g., right after parsing `--config`)
     * - Read later by services/modules that need bootstrap context
     *
     * **Shape:**
     * Uses `Record<string, unknown>` because the exact keys depend on the CLI parser and
     * configuration-defined options.
     *
     * @example
     * ```ts
     * // After minimal parsing
     * globalThis.$argv = { config: 'xbuild.config.ts', _: [], $0: 'xbuild' };
     *
     * // Later
     * const configPath = String($argv.config);
     * ```
     *
     * @since 2.0.0
     */
    var $argv: Record<string, unknown>;
}
/**
 * Replaces the entire xBuild configuration with a new configuration.
 *
 * @param config - New configuration to apply
 *
 * @remarks
 * Completely overwrites the current configuration with the provided configuration.
 * This is a destructive operation that discards all existing settings, including:
 * - All variant configurations
 * - Common settings
 * - Server configuration
 * - User-defined CLI arguments
 *
 * **Use cases**:
 * - Programmatic build scripts that fully control configuration
 * - Testing scenarios requiring isolated configuration
 * - Dynamic configuration generation
 * - Configuration hot-reloading in watch mode
 *
 * **Timing considerations**:
 * - Must be called before creating `BuildService` instances
 * - In watch mode, triggers rebuild with new configuration
 * - Settings take effect immediately for subsequent builds
 *
 * **Difference from {@link patchConfig}**:
 * - `overwriteConfig`: Replaces entire configuration (destructive)
 * - `patchConfig`: Merges with existing configuration (additive)
 *
 * @example Programmatic configuration
 * ```ts
 * import { overwriteConfig, BuildService } from '@remotex-labs/xbuild';
 *
 * overwriteConfig({
 *   variants: {
 *     production: {
 *       esbuild: {
 *         minify: true,
 *         outdir: 'dist',
 *         platform: 'node'
 *       }
 *     }
 *   }
 * });
 *
 * const service = new BuildService();
 * await service.build('production');
 * ```
 *
 * @example Dynamic configuration
 * ```ts
 * const isProd = process.env.NODE_ENV === 'production';
 *
 * overwriteConfig({
 *   variants: {
 *     main: {
 *       esbuild: {
 *         minify: isProd,
 *         sourcemap: !isProd,
 *         outdir: isProd ? 'dist' : 'dev'
 *       }
 *     }
 *   }
 * });
 * ```
 *
 * @example Configuration reload in watch mode
 * ```ts
 * // In file change handler
 * if (changedFile === 'xbuild.config.ts') {
 *   const newConfig = await loadConfig();
 *   overwriteConfig(newConfig);
 *   // Next build uses new configuration
 * }
 * ```
 *
 * @see {@link PartialBuildConfigType} for configuration structure
 * @see {@link patchConfig} for non-destructive configuration updates
 * @see {@link ConfigurationService.reload} for implementation details
 *
 * @since 2.0.0
 */
declare function overwriteConfig(config: PartialBuildConfigType): void;
/**
 * Merges the provided configuration with the existing xBuild configuration.
 *
 * @param config - Partial configuration to merge
 *
 * @remarks
 * Performs a deep merge of the provided configuration with the current configuration,
 * preserving existing settings not specified in the patch. This is a non-destructive
 * operation that allows incremental configuration updates.
 *
 * **Merge behavior**:
 * - Object properties are deeply merged (not replaced)
 * - Array properties are replaced (not concatenated)
 * - Undefined values in patch are ignored (don't remove existing values)
 * - Null values in patch replace existing values
 *
 * **Use cases**:
 * - Adding new variants without affecting existing ones
 * - Updating specific settings while preserving others
 * - Applying conditional configuration overlays
 * - Plugin-based configuration extension
 *
 * **Timing considerations**:
 * - Can be called before or after creating `BuildService` instances
 * - Settings take effect immediately for subsequent builds
 * - Useful for progressive configuration in build scripts
 *
 * **Difference from {@link overwriteConfig}**:
 * - `patchConfig`: Merges with existing configuration (additive)
 * - `overwriteConfig`: Replaces entire configuration (destructive)
 *
 * @example Adding a new variant
 * ```ts
 * import { patchConfig } from '@remotex-labs/xbuild';
 *
 * // Existing config has 'dev' and 'prod' variants
 * patchConfig({
 *   variants: {
 *     staging: {
 *       esbuild: {
 *         minify: true,
 *         outdir: 'staging'
 *       }
 *     }
 *   }
 * });
 * // Now has 'dev', 'prod', and 'staging' variants
 * ```
 *
 * @example Updating specific settings
 * ```ts
 * // Update only output directory, preserve other settings
 * patchConfig({
 *   variants: {
 *     production: {
 *       esbuild: {
 *         outdir: 'build'
 *       }
 *     }
 *   }
 * });
 * // Other production settings (minify, platform, etc.) unchanged
 * ```
 *
 * @example Conditional configuration
 * ```ts
 * if (process.env.ENABLE_SOURCE_MAPS === 'true') {
 *   patchConfig({
 *     common: {
 *       esbuild: {
 *         sourcemap: 'linked'
 *       }
 *     }
 *   });
 * }
 * ```
 *
 * @example Plugin pattern
 * ```ts
 * function addTypeScriptPaths(paths: Record<string, string[]>) {
 *   patchConfig({
 *     common: {
 *       esbuild: {
 *         tsconfig: './tsconfig.json'
 *       }
 *     }
 *   });
 * }
 *
 * addTypeScriptPaths({ '@/*': ['src/*'] });
 * ```
 *
 * @see {@link overwriteConfig} for full configuration replacement
 * @see {@link PartialBuildConfigType} for configuration structure
 * @see {@link ConfigurationService.patch} for implementation details
 *
 * @since 2.0.0
 */
declare function patchConfig(config: PartialBuildConfigType): void;

export {
	ArgumentsInterface,
	BuildContextInterface,
	BuildService,
	DiagnosticInterface,
	LifecycleContextInterface,
	LifecycleStageInterface,
	LoadContextInterface,
	MacroContextInterface,
	MaybeUndefinedPromiseType,
	MaybeVoidPromiseType,
	OnEndType,
	OnLoadType,
	OnResolveType,
	OnStartType,
	ResolveContextInterface,
	ResultContextInterface,
	ServerConfigurationInterface,
	ServerModule,
	WatchService,
	collectFilesFromGlob,
	enhancedBuildResult,
	isBuildResultError,
	isDirectoryExcluded,
	matchesAny,
	normalizeMessageToError,
	overwriteConfig,
	parseGlobs,
	patchConfig,
	processEsbuildMessages,
	shouldIncludeFile,
	xBuildConfig
};