import { ParsedEnvSpecDecorator, ParsedEnvSpecStaticValue, ParsedEnvSpecFunctionCall, ParsedEnvSpecFunctionArgs, ParsedEnvSpecObjectLiteral, ParsedEnvSpecArrayLiteral, ParsedEnvSpecFile } from '@env-spec/parser';
import { FallbackIfUnknown } from '@env-spec/utils/type-utils';

type CacheStoreLike = {
    get(cacheKey: string): Promise<{
        value: any;
        cachedAt: number;
        expiresAt: number;
    } | undefined>;
    getOrSet(cacheKey: string, ttlMs: number, producer: () => Promise<any> | any): Promise<{
        value: any;
        cachedAt: number;
        expiresAt: number;
        cacheHit: boolean;
    } | undefined>;
    set(cacheKey: string, value: any, ttlMs: number): Promise<{
        cachedAt: number;
        expiresAt: number;
    } | undefined>;
    delete(cacheKey: string): Promise<void>;
    clearAll(): Promise<number>;
};

type VarlockErrorLocationDetails = {
    /** file path or url */
    id: string;
    /** 1-based line number */
    lineNumber: number;
    /** 1-based column number */
    colNumber: number;
    /** full line string */
    lineStr: string;
};
type ErrorSeverity = 'warning' | 'error' | 'fatal';
declare class VarlockError extends Error {
    readonly more?: {
        tip?: string | Array<string>;
        err?: Error;
        severity?: ErrorSeverity;
        /** @deprecated use severity: 'warning' instead */
        isWarning?: boolean;
        /** machine-friendly error code if needed for anything else */
        code?: string;
        location?: VarlockErrorLocationDetails;
        /** free-form additional metadata */
        extraMetadata?: Record<string, any>;
    } | undefined;
    originalError?: Error;
    get isUnexpected(): boolean;
    get type(): string;
    static defaultIcon: string;
    icon: string;
    private _severity;
    constructor(errOrMessage: string | Error, more?: {
        tip?: string | Array<string>;
        err?: Error;
        severity?: ErrorSeverity;
        /** @deprecated use severity: 'warning' instead */
        isWarning?: boolean;
        /** machine-friendly error code if needed for anything else */
        code?: string;
        location?: VarlockErrorLocationDetails;
        /** free-form additional metadata */
        extraMetadata?: Record<string, any>;
    } | undefined);
    get tip(): string | undefined;
    get location(): VarlockErrorLocationDetails | undefined;
    get code(): string | undefined;
    get extraMetadata(): Record<string, any> | undefined;
    get severity(): ErrorSeverity;
    set severity(s: ErrorSeverity);
    get isWarning(): boolean;
    set isWarning(w: boolean);
    get isFatal(): boolean;
    toJSON(): {
        isWarning?: boolean | undefined;
        tip?: string | undefined;
        icon: string;
        type: string;
        name: string;
        message: string;
        severity: ErrorSeverity;
        isUnexpected: boolean;
    };
}
declare class ConfigLoadError extends VarlockError {
    readonly cleanedStack: Array<string>;
    constructor(err: Error);
    toJSON(): {
        cleanedStack: string[];
        isWarning?: boolean | undefined;
        tip?: string | undefined;
        icon: string;
        type: string;
        name: string;
        message: string;
        severity: ErrorSeverity;
        isUnexpected: boolean;
    };
}
declare class SchemaError extends VarlockError {
    static defaultIcon: string;
}
declare class ValidationError extends VarlockError {
    static defaultIcon: string;
}
declare class CoercionError extends VarlockError {
    static defaultIcon: string;
}
declare class ResolutionError extends VarlockError {
    static defaultIcon: string;
    protected _retryable?: boolean;
    set retryable(val: boolean);
    get retryable(): boolean;
}

type MaybePromise<T> = T | Promise<T>;
type EnvGraphDataTypeDef<CoerceReturnType, ValidateInputType = FallbackIfUnknown<CoerceReturnType, string>> = {
    /** this will be the name of the type, used to reference it when using it in a schema */
    name: string;
    /** optional description of the type itself */
    typeDescription?: string;
    /** icon see https://icones.js.org for available options
     * @example mdi:aws
     * */
    icon?: string;
    /** coerce function - should take in any value and return a value of the correct type if possible */
    coerce?: (value: any) => CoerceReturnType | CoercionError | undefined;
    /**
     * validate function - we can assume that coercion has already succeded, or this will not be called
     * - if validation passes, should return true
     * - if validation fails, should return a ValidationError or array of errors - or throw an error
     * */
    validate?: (value: ValidateInputType) => MaybePromise<(true | undefined | void | Error | Array<Error>)>;
    /** will make items of this type sensitive, unless overridden specifically on that item */
    sensitive?: boolean;
    /** adds docs info for these  */
    docs?: Array<string | {
        url: string;
        description: string;
    }>;
};
/**
 * holds a specific instance of a data type, along with specific settings which affect validation/coercion etc
 */
declare class EnvGraphDataType {
    private def;
    /** reference back to the factory function, which we can use like a constructor to check the type of the instance */
    private factory;
    constructor(def: EnvGraphDataTypeDef<any, any>, 
    /** reference back to the factory function, which we can use like a constructor to check the type of the instance */
    factory: any);
    get name(): string;
    get icon(): string | undefined;
    get isSensitive(): boolean | undefined;
    get docsEntries(): (string | {
        url: string;
        description: string;
    })[] | undefined;
    /** @internal */
    get _rawDef(): EnvGraphDataTypeDef<any, any>;
    coerce(val: any): any;
    validate(val: any): MaybePromise<true | void | Error | Error[] | undefined>;
}
declare function createEnvGraphDataType<TsType, InstanceSettingsArgs extends Array<any>>(dataTypeDef: EnvGraphDataTypeDef<TsType> | ((...args: InstanceSettingsArgs) => EnvGraphDataTypeDef<TsType>)): {
    (...usageOpts: InstanceSettingsArgs): EnvGraphDataType;
    _isEnvGraphDataTypeFactory: boolean;
    dataTypeName: string;
};
type EnvGraphDataTypeFactory = ReturnType<typeof createEnvGraphDataType>;

type CacheHitInfo = {
    cacheKey: string;
    cachedAt: number;
    expiresAt: number;
};

declare abstract class DecoratorInstance {
    get name(): string;
    get isFunctionCall(): boolean;
    _decValueResolver?: Resolver;
    get decValueResolver(): Resolver | undefined;
    abstract readonly isRootDecorator: boolean;
    abstract readonly dataSource: EnvGraphDataSource;
    abstract readonly parsedDecorator: ParsedEnvSpecDecorator;
    abstract graph: EnvGraph;
    _errors: Array<VarlockError>;
    get schemaErrors(): Array<VarlockError>;
    get _executionError(): VarlockError | undefined;
    get errors(): Array<VarlockError>;
    private decoratorDef?;
    get incompatibleWith(): string[] | undefined;
    private processed;
    private processedData;
    process(): Promise<void>;
    execute(): Promise<void>;
    resolvedValue?: any;
    isResolved: boolean;
    resolve(): Promise<any>;
}
declare class ItemDecoratorInstance extends DecoratorInstance {
    readonly configItem: ConfigItem;
    readonly dataSource: EnvGraphDataSource;
    readonly parsedDecorator: ParsedEnvSpecDecorator;
    isRootDecorator: boolean;
    constructor(configItem: ConfigItem, dataSource: EnvGraphDataSource, parsedDecorator: ParsedEnvSpecDecorator);
    get graph(): EnvGraph;
}
declare class RootDecoratorInstance extends DecoratorInstance {
    readonly dataSource: EnvGraphDataSource;
    readonly parsedDecorator: ParsedEnvSpecDecorator;
    isRootDecorator: boolean;
    constructor(dataSource: EnvGraphDataSource, parsedDecorator: ParsedEnvSpecDecorator);
    get graph(): EnvGraph;
}
type RootDecoratorDef<Processed = any> = {
    name: string;
    description?: string;
    isFunction?: boolean;
    deprecated?: boolean | string;
    incompatibleWith?: Array<string>;
    process?: (decoratorValue: Resolver) => (Processed | Promise<Processed>);
    execute?: (executeInput: Processed) => void | Promise<void>;
    useFnArgsResolver?: boolean;
};
type ItemDecoratorDef<T = any> = {
    name: string;
    incompatibleWith?: Array<string>;
    isFunction?: boolean;
    deprecated?: boolean | string;
    process?: (decoratorValue: Resolver) => T | Promise<T>;
    execute?: (executeInput: T) => void | Promise<void>;
    useFnArgsResolver?: boolean;
};

type ResolvedValue = undefined | string | number | boolean | RegExp | {
    [key: string]: ResolvedValue;
} | Array<ResolvedValue>;
declare class Resolver {
    readonly arrArgs?: Array<Resolver> | undefined;
    readonly objArgs?: Record<string, Resolver> | undefined;
    readonly dataSource?: EnvGraphDataSource | undefined;
    static def: ResolverDef;
    constructor(arrArgs?: Array<Resolver> | undefined, objArgs?: Record<string, Resolver> | undefined, dataSource?: EnvGraphDataSource | undefined);
    static get fnName(): string;
    get def(): ResolverDef<any>;
    get fnName(): string;
    get label(): string | undefined;
    get icon(): string | undefined;
    get isStatic(): boolean;
    get staticValue(): ResolvedValue;
    inferredType?: string;
    /** reference to the parsed node that created this resolver, used for error location tracking */
    _parsedNode?: ParsedEnvSpecStaticValue | ParsedEnvSpecFunctionCall | ParsedEnvSpecFunctionArgs | ParsedEnvSpecObjectLiteral | ParsedEnvSpecArrayLiteral;
    _errors: Array<SchemaError>;
    private _depsObj;
    get childResolvers(): Array<Resolver>;
    get schemaErrors(): Array<SchemaError>;
    get depsObj(): Record<string, boolean>;
    get deps(): string[];
    private parent?;
    private meta;
    process(parent?: ConfigItem | DecoratorInstance): void;
    protected addDep(key: string): void;
    protected getCurrentEnv(): Promise<string | undefined>;
    resolve(): Promise<ResolvedValue>;
    get envGraph(): EnvGraph | undefined;
    protected getDepValue(key: string): ResolvedValue;
}
type ResolverDef<T = any> = {
    name: string;
    description?: string;
    label?: string;
    icon?: string;
    inferredType?: string;
    /** If true, using this resolver implies the item is sensitive (unless explicitly overridden) */
    impliesSensitive?: boolean;
    argsSchema?: {
        type: 'array' | 'object' | 'mixed';
        arrayExactLength?: number;
        arrayMinLength?: number;
        arrayMaxLength?: number;
        objKeyMinLength?: number;
    };
    process?: (this: Resolver) => T;
    resolve: (this: Resolver, state: T) => ResolvedValue | Promise<ResolvedValue>;
};
type ResolverChildClass<ChildClass extends Resolver = Resolver> = ({
    new (...args: Array<any>): ChildClass;
} & typeof Resolver);

/**
 * A reusable allow/deny key filter, shared by any decorator that selects a subset of keys
 * via `pick=[...]` / `omit=[...]` named args (e.g. `@setValuesBulk`, `@import`).
 *
 * `pick` keeps only matching keys; `omit` drops them. Patterns support simple globs
 * (`*`, `?`) via {@link globToRegExp} and match case-sensitively.
 */
type KeyFilter = {
    mode: 'pick' | 'omit';
    patterns: Array<string>;
};

declare const DATA_SOURCE_TYPES: Readonly<{
    schema: {
        fileSuffixes: string[];
    };
    example: {
        fileSuffixes: string[];
    };
    defaults: {
        fileSuffixes: string[];
    };
    values: {
        fileSuffixes: Array<string>;
    };
    overrides: {
        fileSuffixes: string[];
    };
    container: {};
    'import-alias': {};
}>;
type DataSourceType = keyof typeof DATA_SOURCE_TYPES;
declare abstract class EnvGraphDataSource {
    static DATA_SOURCE_TYPES: Readonly<{
        schema: {
            fileSuffixes: string[];
        };
        example: {
            fileSuffixes: string[];
        };
        defaults: {
            fileSuffixes: string[];
        };
        values: {
            fileSuffixes: Array<string>;
        };
        overrides: {
            fileSuffixes: string[];
        };
        container: {};
        'import-alias': {};
    }>;
    /** reference back to the graph */
    graph?: EnvGraph;
    /** parent data source - everything except the root will have a parent */
    parent?: EnvGraphDataSource;
    /** child data sources */
    children: Array<EnvGraphDataSource>;
    /**
     * tracks if this data source was imported, and additional settings about the import (restricting keys)
     * */
    importMeta?: {
        isImport?: boolean;
        /** deprecated positional allowlist (exact match) - prefer `importFilter` */
        importKeys?: Array<string>;
        /** pick/omit key filter (glob-aware) */
        importFilter?: KeyFilter;
        /** true when the @import had a non-static `enabled` parameter (e.g. `enabled=forEnv("dev")`) */
        isConditionallyEnabled?: boolean;
    };
    get isImport(): boolean;
    /** true when any import in this source's chain restricts which keys are brought in */
    get isPartialImport(): boolean;
    /**
     * Whether `key` is visible through this source's full import chain. A key must pass every
     * import filter between this source and the root (nested imports intersect).
     */
    isKeyImported(key: string): boolean;
    /** shared child-setup logic: wire up parent/graph refs, finishInit (but no import processing) */
    protected _initChild(child: EnvGraphDataSource, importMeta?: EnvGraphDataSource['importMeta']): Promise<void>;
    /** adds a child data source, running both finishInit and import processing */
    addChild(child: EnvGraphDataSource, importMeta?: EnvGraphDataSource['importMeta']): Promise<void>;
    /**
     * When true, direct children of this data source are treated as top-level entry points:
     * they inherit the "no parent" semantics and are never classified as env-specific
     * solely because of their filename (e.g. `.env.production` used as an explicit entry
     * point would not be env-specific, but one auto-loaded inside a directory would be).
     * Only `MultiplePathsContainerDataSource` sets this to true.
     */
    childrenAreRoots?: boolean;
    /**
     * Whether this data source is environment-specific.
     * A source is env-specific if:
     * - it was auto-loaded for a specific env (e.g., `.env.production` loaded by a DirectoryDataSource)
     * - it has a conditional `@disable` decorator (e.g., `@disable=forEnv(test)`)
     * - it was conditionally imported (e.g., `@import(..., enabled=forEnv("dev"))`)
     * - any of its ancestors are env-specific
     * Used by type generation to filter out env-dependent definitions.
     *
     * Note: `applyForEnv` from filename parsing is only relevant for auto-loaded files.
     * Explicitly imported files (via `@import`) are controlled by the import mechanism,
     * not the auto-load-by-env logic, so their `applyForEnv` is ignored here.
     * Similarly, a file that is the explicit root entry point (no parent, or whose parent
     * has `childrenAreRoots` set) is never treated as env-specific even if its filename
     * contains an env qualifier.
     */
    get isEnvSpecific(): boolean;
    /** true when the source has a `@disable` decorator whose value is not static */
    _hasConditionalDisable?: boolean;
    /** environment flag key (as set by @envFlag decorator) - only if set within this source */
    _envFlagKey?: string;
    /** environment flag key getter that will follow up the parent chain */
    get envFlagKey(): string | undefined;
    /** helper to set the current envFlag key, also propogating upwards */
    setEnvFlag(key: string): void;
    /** environment flag config item getter (follows up the parent chain) */
    get envFlagConfigItem(): ConfigItem | undefined;
    /** environment flag value getter (follows up the parent chain), and checks the graph-level fallback */
    get envFlagValue(): ResolvedValue;
    /** helper to resolve the envFlag value */
    resolveCurrentEnv(): Promise<string | number | boolean | RegExp | {
        [key: string]: ResolvedValue;
    } | ResolvedValue[] | undefined>;
    /** finish init process for this data source */
    finishInit(): Promise<void>;
    /**
     * Process @import decorators for this data source.
     * Separated from finishInit() so that DirectoryDataSource can load all
     * auto-loaded files first, then process imports once values from
     * .env, .env.local, etc. are available for import conditions.
     */
    _processImports(): Promise<void>;
    /**
     * called by the finishInit - meant to be overridden by subclasses
     * to add specific behaviour for that data source type
     * @internal
     * */
    _finishInit(): Promise<void>;
    abstract typeLabel: string;
    abstract get label(): string;
    type: DataSourceType;
    applyForEnv?: string;
    _disabled?: boolean;
    get disabled(): boolean | undefined;
    _errors: Array<VarlockError>;
    /** first loading/parse error on this data source (including plugin loading errors) */
    get loadingError(): VarlockError | undefined;
    get schemaErrors(): VarlockError[];
    get resolutionErrors(): VarlockError[];
    /** all errors from this data source (own + decorator schema + decorator execution + plugin loading) */
    get errors(): Array<VarlockError>;
    get isValid(): boolean;
    configItemDefs: Record<string, ConfigItemDef>;
    decorators: Array<ParsedEnvSpecDecorator>;
    getRootDecorators(decName: string): ParsedEnvSpecDecorator[];
    getRootDecoratorSimpleValue(decName: string): any;
    rootDecorators: Array<RootDecoratorInstance>;
    getRootDec(decName: string): RootDecoratorInstance | undefined;
    getRootDecFns(decName: string): RootDecoratorInstance[];
}
declare abstract class FileBasedDataSource extends EnvGraphDataSource {
    fullPath: string;
    fileName: string;
    rawContents?: string;
    get typeLabel(): string;
    private relativePath;
    get label(): string;
    static format: string;
    static validFileExtensions: Array<string>;
    get validFileExtensions(): string[];
    constructor(fullPath: string, opts?: {
        overrideContents?: string;
    });
    _finishInit(): Promise<void>;
    abstract _parseContents(): Promise<void>;
}
declare class DotEnvFileDataSource extends FileBasedDataSource {
    static format: string;
    static validFileExtensions: never[];
    parsedFile?: ParsedEnvSpecFile;
    _parseContents(): Promise<void>;
    private _validateDecoratorPlacement;
    private _locationFromParsed;
}

type ConfigItemDef = {
    description?: string;
    parsedDecorators?: Array<ParsedEnvSpecDecorator>;
    parsedValue: ParsedEnvSpecStaticValue | ParsedEnvSpecFunctionCall | undefined;
    resolver?: Resolver;
    decorators?: Array<ItemDecoratorInstance>;
};
type ConfigItemDefAndSource = {
    itemDef: ConfigItemDef;
    source?: EnvGraphDataSource;
};
declare class ConfigItem {
    readonly envGraph: EnvGraph;
    readonly key: string;
    /** Whether this is a builtin VARLOCK_* variable */
    isBuiltin?: boolean;
    /** Cache hits recorded during resolution (rolled up from potentially multiple cache() resolvers) */
    _cacheHits: Array<CacheHitInfo>;
    /** Whether any value was served from cache */
    get isCacheHit(): boolean;
    /** Whether this item uses cache(). */
    get isCached(): boolean;
    /** TTL string from the cache() resolver (for display in explain command). undefined = forever. */
    get cacheTtl(): string | number | undefined;
    private _findCacheResolver;
    /** Programmatic definitions not tied to a data source (e.g. builtin vars) */
    _internalDefs: Array<ConfigItemDefAndSource>;
    constructor(envGraph: EnvGraph, key: string);
    /**
     * fetch ordered list of definitions for this item, by following the sorted definition sources list
     * internal defs (builtins) are appended last (lowest priority)
     */
    get defs(): ConfigItemDefAndSource[];
    /**
     * Like `defs` but filtered to exclude environment-specific data sources.
     * Used by type generation so that generated types are deterministic
     * regardless of which environment is being loaded.
     */
    get defsForTypeGeneration(): ConfigItemDefAndSource[];
    get description(): string | undefined;
    get icon(): any;
    get isDeprecated(): boolean;
    get deprecationMessage(): string | undefined;
    get docsLinks(): {
        url: string;
        description?: string;
    }[];
    /** Whether the resolved value came from a process.env override rather than file definitions */
    get isOverridden(): boolean;
    /**
     * Returns the definition+source that would provide the value resolver
     * (i.e. the "winning" definition), or undefined if no definition has a resolver.
     * This is useful for explaining where a value comes from regardless of overrides.
     */
    get activeValueDef(): ConfigItemDefAndSource | undefined;
    get valueResolver(): Resolver | undefined;
    allDecorators: Array<ItemDecoratorInstance>;
    effectiveDecorators: Record<string, ItemDecoratorInstance>;
    effectiveDecoratorFns: Record<string, Array<ItemDecoratorInstance>>;
    getDec(decoratorName: string): ItemDecoratorInstance;
    getDecFns(decoratorName: string): ItemDecoratorInstance[];
    resolveDecorators(): Promise<void>;
    dataType?: EnvGraphDataType;
    _schemaErrors: Array<SchemaError>;
    get resolverSchemaErrors(): SchemaError[];
    get decoratorSchemaErrors(): VarlockError[];
    private isProcessed;
    process(): Promise<void>;
    get dependencyKeys(): string[];
    /**
     * special early resolution helper
     * currently used to resolve the envFlag before everything else has been loaded
     * */
    earlyResolve(): Promise<void>;
    _isRequired: boolean;
    /**
     * need to track if required-ness is dynamic, e.g. based on current env
     * because that will affect type generation (only _always_ required items are never undefined)
     * */
    _isRequiredDynamic: boolean;
    private processRequired;
    get isRequired(): boolean;
    get isRequiredDynamic(): boolean;
    _isSensitive: boolean;
    _sensitiveExplicitlySet: boolean;
    get isSensitive(): boolean;
    /**
     * Whether runtime leak detection scans output (responses, etc.) for this item's value.
     * Defaults to true for sensitive items; can be disabled per-item via
     * `@sensitive={preventLeaks=false}` for secrets that legitimately leave the system
     * (e.g. an API endpoint that returns a secret to another service).
     * Note: this only opts out of leak detection — the value is still redacted in logs.
     */
    _preventLeaks: boolean;
    get preventLeaks(): boolean;
    private processSensitive;
    /**
     * Apply named options from the `@sensitive={...}` form.
     * Returns whether the item is sensitive (the `enabled` option, defaulting to true) —
     * `enabled` may be static or a function, allowing dynamic control of sensitivity.
     */
    private applySensitiveOptions;
    get errors(): VarlockError[];
    get validationState(): 'warn' | 'error' | 'valid';
    /** resolved value _before coercion_ */
    resolvedRawValue?: ResolvedValue;
    isResolved: boolean;
    /** resolved value after coercion */
    resolvedValue?: ResolvedValue;
    isValidated: boolean;
    resolutionError?: ResolutionError;
    coercionError?: CoercionError;
    validationErrors?: Array<ValidationError>;
    get isCoerced(): boolean;
    resolve(reset?: boolean): Promise<void>;
    get isValid(): boolean;
    /**
     * Compute schema-level info for type generation using only non-env-specific definitions.
     * This mirrors the logic of processRequired/processSensitive but:
     * - Uses defsForTypeGeneration (excludes env-specific sources)
     * - Returns a result object instead of mutating item state
     * - Resolves only static decorators from non-env-specific sources
     */
    getTypeGenInfo(): Promise<TypeGenItemInfo>;
}
/** Schema-level info for a config item, computed from non-env-specific definitions only */
type TypeGenItemInfo = {
    key: string;
    description?: string;
    dataType?: EnvGraphDataType;
    isRequired: boolean;
    isRequiredDynamic: boolean;
    isSensitive: boolean;
    icon?: string;
    docsLinks: Array<{
        url: string;
        description?: string;
    }>;
    isDeprecated: boolean;
    deprecationMessage?: string;
};

type GraphNodeId = string;
type GraphAdjacencyList = Record<GraphNodeId, Array<GraphNodeId>>;

/**
 * Scoped cache accessor for plugin authors.
 *
 * All keys are automatically prefixed with `plugin:{pluginName}:` so plugins
 * cannot collide with each other's cache entries.
 *
 * Cache hits are automatically recorded on the current resolution context
 * (if any) so they show up in `varlock load` and `varlock explain` output.
 *
 * Usage in a plugin:
 * ```ts
 * const cached = await plugin.cache.get('vault/MyVault/item/DBCreds');
 * if (!cached) {
 *   const value = await fetchFromAPI();
 *   await plugin.cache.set('vault/MyVault/item/DBCreds', value, '1h');
 * }
 * ```
 */
declare class PluginCacheAccessor {
    private pluginName;
    private cacheStore;
    constructor(pluginName: string, cacheStore: CacheStoreLike);
    private buildKey;
    private recordCacheHit;
    get(key: string): Promise<any | undefined>;
    getOrSet(key: string, ttl: string | number, producer: () => Promise<any> | any): Promise<any | undefined>;
    set(key: string, value: any, ttl: string | number): Promise<void>;
    delete(key: string): void;
}

/**
 * Debug logger with colors, timing, and format string support
 * Enable by setting DEBUG env var with namespaces (e.g., DEBUG=varlock:*)
 */
type DebugFn = (...args: Array<any>) => void;
declare function createDebug(namespace: string): DebugFn;
type Debugger = ReturnType<typeof createDebug>;

declare class VarlockPlugin {
    readonly ERRORS: {
        ValidationError: typeof ValidationError;
        CoercionError: typeof CoercionError;
        SchemaError: typeof SchemaError;
        ResolutionError: typeof ResolutionError;
    };
    private _packageJson?;
    private _name?;
    get name(): string;
    set name(val: string);
    private _version?;
    get version(): string;
    set version(val: string);
    private _icon?;
    get icon(): string;
    set icon(val: string);
    loadingError?: VarlockError;
    warnings: Array<SchemaError>;
    readonly localPath?: string;
    /** reference to the `@plugin()` decorator instance(s) that installed the plugin  */
    installDecoratorInstances: Array<DecoratorInstance>;
    type: 'single-file' | 'package';
    constructor(opts: {
        type: 'single-file' | 'package';
        localPath: string;
        loadingError?: VarlockError;
        packageJson?: {
            name: string;
            version?: string;
            description?: string;
        };
    });
    private debugger;
    get debug(): (...args: Parameters<Debugger>) => void;
    private _cacheAccessor?;
    /** @internal set by EnvGraph when plugins are loaded */
    _cacheStore?: CacheStoreLike;
    /**
     * Scoped cache accessor for this plugin.
     * Keys are automatically namespaced to prevent collisions between plugins.
     */
    get cache(): PluginCacheAccessor;
    readonly dataTypes?: Array<Parameters<typeof createEnvGraphDataType>[0]>;
    registerDataType(dataTypeDef: Parameters<typeof createEnvGraphDataType>[0]): void;
    readonly rootDecorators?: Array<RootDecoratorDef<any>>;
    registerRootDecorator<T>(decoratorDef: RootDecoratorDef<T>): void;
    readonly itemDecorators?: Array<ItemDecoratorDef<any>>;
    registerItemDecorator<T>(decoratorDef: ItemDecoratorDef<T>): void;
    readonly resolverFunctions?: Array<ResolverDef<any>>;
    registerResolverFunction<T>(resolverDef: ResolverDef<T>): void;
    /**
     * Declare standard env vars this plugin uses.
     * Set during plugin init — the loading infrastructure will automatically
     * check for these vars and generate warnings if they are detected but not wired up.
     *
     * `key` accepts a single env var name or an array of alternatives — the first match is used.
     * `dataType` is used to generate `# @type=...` schema lines for vars not in the schema.
     */
    standardVars?: {
        initDecorator: string;
        params: Record<string, {
            key: string | Array<string>;
            dataType?: string;
        }>;
    };
    /** called by the loading infrastructure — checks declared standardVars against the graph */
    _checkStandardVars(graph: {
        overrideValues: Record<string, string | undefined>;
        configSchema: Record<string, any>;
        sortedDataSources: Iterable<{
            rootDecorators: Array<{
                name: string;
                isFunctionCall: boolean;
                decValueResolver?: {
                    deps: Array<string>;
                };
            }>;
        }>;
    }): void;
    get pluginFilePath(): string;
    executePluginModule(): Promise<void>;
}

/**
 * Shared parsers for CI env values: ref → branch, repo string → { owner, name }, env value → deployment enum.
 */
type DeploymentEnvironment = ('development' | 'preview' | 'staging' | 'production' | 'test');
interface RepoParts {
    owner: string;
    name: string;
}
interface CiEnvInfo {
    isCI: boolean;
    name?: string;
    docsUrl?: string;
    isPR?: boolean;
    repo?: RepoParts;
    fullRepoName?: string;
    branch?: string;
    prNumber?: number;
    commitSha?: string;
    commitShaShort?: string;
    environment?: DeploymentEnvironment;
    /** Unique run/build id (e.g. GITHUB_RUN_ID, BUILD_ID) */
    runId?: string;
    /** URL to the run or deploy in the CI/deploy UI */
    buildUrl?: string;
    /** Workflow or pipeline name */
    workflowName?: string;
    /** User or app that triggered the run (e.g. GITHUB_ACTOR) */
    actor?: string;
    /** Event type (e.g. push, pull_request, workflow_dispatch) */
    eventName?: string;
    raw?: Record<string, string>;
}

declare const OVERRIDE_PROVENANCE_SOURCE = "varlock";
declare const OVERRIDE_PROVENANCE_VERSION = 1;
type OverrideProvenanceMetadata = {
    source: typeof OVERRIDE_PROVENANCE_SOURCE;
    version: typeof OVERRIDE_PROVENANCE_VERSION;
    overrideKeys: Array<string>;
};

type SerializedEnvGraphErrors = {
    /** Per-item validation errors, keyed by config item key */
    configItems?: Record<string, string>;
    /** Root-level errors not tied to a specific config item (loading errors, schema errors, plugin errors, etc.) */
    root?: Array<string>;
};
/** Entry in the sorted definition sources list — pairs a data source with the node whose
 * import chain filters which keys are visible at that specific position in the precedence chain */
type DefinitionSourceEntry = {
    source: EnvGraphDataSource;
    /** node whose import chain decides key visibility for this position (undefined = all keys visible) */
    filterNode?: EnvGraphDataSource;
};
type SerializedEnvGraph = {
    basePath?: string;
    sources: Array<{
        type: string;
        label: string;
        enabled: boolean;
        path?: string;
    }>;
    settings: {
        redactLogs?: boolean;
        preventLeaks?: boolean;
        encryptInjectedEnv?: boolean;
        disableProcessEnvInjection?: boolean;
    };
    config: Record<string, {
        value: any;
        isSensitive: boolean;
        /** false = opted out of runtime leak detection (still redacted in logs). Omitted when true (the default). */
        preventLeaks?: boolean;
    }>;
    /** provenance metadata for process.env overrides across nested invocations */
    __varlockOverrideMeta?: OverrideProvenanceMetadata;
    /** Present only when config has errors — consumers can check `if (data.errors)` */
    errors?: SerializedEnvGraphErrors;
};
/** container of the overall graph and current resolution attempt / values */
declare class EnvGraph {
    basePath?: string;
    /** @internal cache store instance, initialized during loading */
    _cacheStore?: CacheStoreLike;
    /** @internal cache mode selected from CLI/loader auto policy */
    _cacheMode: 'auto' | 'memory' | 'disk' | 'disabled';
    /** @internal --clear-cache flag: clear cache then resolve + rewrite */
    _clearCacheMode: boolean;
    /** @internal --skip-cache flag: skip cache entirely */
    _skipCacheMode: boolean;
    /** root data source (.env.schema) */
    rootDataSource?: EnvGraphDataSource;
    /** place to store process.env overrides */
    overrideValues: Record<string, string | undefined>;
    /** config item key of env flag (toggles env-specific data sources enabled) */
    envFlagKey?: string;
    /** graph-level fallback value for environment flag */
    envFlagFallback?: string;
    configSchema: Record<string, ConfigItem>;
    /**
     * Tracks directory/file paths that have already been loaded as imports.
     * Maps each import path to the data source that was created for it.
     * Used to prevent diamond-dependency re-imports (same schema imported via multiple paths),
     * which would otherwise cause plugin init decorators to run multiple times.
     */
    private _loadedImportPaths;
    /** Returns the existing source for a path if already loaded, or undefined */
    getLoadedImportSource(importPath: string): EnvGraphDataSource | undefined;
    /** Records the data source that was created for an import path */
    recordLoadedImportPath(importPath: string, dataSource: EnvGraphDataSource): void;
    /**
     * Register ConfigItems for keys visible through an import
     * that may not have been registered during the original source's finishInit.
     */
    registerItemsForImport(source: EnvGraphDataSource, importSite: EnvGraphDataSource, importMeta?: {
        importKeys?: Array<string>;
        importFilter?: KeyFilter;
    }): void;
    /** Get a data source and all its descendants (DFS) */
    private _getDescendants;
    /** virtual imports for testing */
    virtualImports?: Record<string, string>;
    setVirtualImports(basePath: string, files: Record<string, string>): void;
    get sortedDataSources(): EnvGraphDataSource[];
    /**
     * Precedence-ordered list of definition sources, used by ConfigItem.defs.
     *
     * Unlike `sortedDataSources` (which contains each real source exactly once),
     * this list can contain the same source multiple times at different positions
     * when it's imported from multiple locations (diamond dependency). Each entry
     * carries its own `importKeys` filter for that specific import context.
     *
     * Built from `sortedDataSources` by expanding `ImportAliasSource` nodes into
     * the original source's full subtree at the alias's precedence position.
     */
    get sortedDefinitionSources(): Array<DefinitionSourceEntry>;
    registeredResolverFunctions: Record<string, ResolverChildClass>;
    registerResolver(resolverClass: ResolverChildClass): void;
    dataTypesRegistry: Record<string, EnvGraphDataTypeFactory>;
    registerDataType(factory: EnvGraphDataTypeFactory): void;
    itemDecoratorsRegistry: Record<string, ItemDecoratorDef>;
    registerItemDecorator(decoratorDef: ItemDecoratorDef): void;
    rootDecoratorsRegistry: Record<string, RootDecoratorDef>;
    registerRootDecorator(decoratorDef: RootDecoratorDef): void;
    constructor();
    /**
     * Override for process.env used by builtin var detection.
     * When set, builtin vars use this instead of the real process.env.
     * Primarily useful for testing.
     */
    processEnvOverride?: Record<string, string | undefined>;
    /** Cached CI env info, computed lazily from processEnvOverride or real process.env */
    private _cachedCiEnv?;
    get ciEnvInfo(): CiEnvInfo;
    /** The process env record used for builtin var detection */
    get processEnvForBuiltins(): Record<string, string | undefined>;
    /**
     * Register a builtin VARLOCK_* variable.
     * Attaches an internal def with the builtin resolver so it flows through the normal pipeline.
     * If the item already exists (user-defined), the internal def is added as a fallback.
     */
    registerBuiltinVar(key: string): void;
    setRootDataSource(source: EnvGraphDataSource): Promise<void>;
    finishLoad(): Promise<void>;
    get graphAdjacencyList(): GraphAdjacencyList;
    resolveEnvValues(keys?: Array<string>): Promise<void>;
    resolveItemWithDeps(key: string): Promise<void>;
    /** config keys with builtin vars first, then user-defined in schema order */
    get sortedConfigKeys(): string[];
    getResolvedEnvObject(): Record<string, any>;
    getSerializedGraph(): SerializedEnvGraph;
    get isInvalid(): boolean;
    generateTypes(lang: string, outputPath: string): Promise<void>;
    /**
     * Resolve @generateTypes decorators and generate type files.
     * This should be called after finishLoad() but before resolveEnvValues().
     * The @generateTypes decorator args (lang, path) are static, so we can resolve them
     * without needing full env resolution. Type info is computed from non-env-specific
     * definitions only, so the output is deterministic regardless of environment.
     *
     * @param opts.ignoreAutoFalse - if true, generate types even if `auto=false` is set.
     *   Used by the `varlock typegen` command to force generation.
     */
    generateTypesIfNeeded(opts?: {
        ignoreAutoFalse?: boolean;
    }): Promise<number>;
    getRootDec(decoratorName: string): RootDecoratorInstance | undefined;
    getRootDecFns(decoratorName: string): RootDecoratorInstance[];
    /** plugins installed globally in the graph */
    plugins: Array<VarlockPlugin>;
}

export { CoercionError as C, type Debugger as D, EnvGraph as E, PluginCacheAccessor as P, ResolutionError as R, type SerializedEnvGraph as S, VarlockPlugin as V, Resolver as a, SchemaError as b, ValidationError as c, createDebug as d, DotEnvFileDataSource as e, ConfigLoadError as f };
