@utilarium/cardigantime 0.0.24 → 0.0.26-dev.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"cardigantime.cjs","sources":["../src/error/ArgumentError.ts","../src/configure.ts","../src/constants.ts","../src/error/FileSystemError.ts","../src/util/storage.ts","../src/util/hierarchical.ts","../src/read.ts","../src/error/ConfigurationError.ts","../src/types.ts","../src/validate.ts","../src/util/schema-defaults.ts","../src/cardigantime.ts"],"sourcesContent":["/**\n * Error thrown when CLI arguments or function parameters are invalid.\n * \n * This error provides specific context about which argument failed validation\n * and why, making it easier for users to fix their command-line usage or\n * for developers to debug parameter issues.\n * \n * @example\n * ```typescript\n * throw new ArgumentError('config-directory', 'Path cannot be empty');\n * // Error message: \"Path cannot be empty\"\n * // error.argument: \"config-directory\"\n * ```\n */\nexport class ArgumentError extends Error {\n /** The name of the argument that caused the error */\n private argumentName: string;\n\n /**\n * Creates a new ArgumentError instance.\n * \n * @param argumentName - The name of the invalid argument\n * @param message - Description of why the argument is invalid\n */\n constructor(argumentName: string, message: string) {\n super(`${message}`);\n this.name = 'ArgumentError';\n this.argumentName = argumentName;\n }\n\n /**\n * Gets the name of the argument that caused this error.\n * \n * @returns The argument name\n */\n get argument(): string {\n return this.argumentName;\n }\n}","import { Command } from \"commander\";\nimport { z } from \"zod\";\nimport { ArgumentError } from \"./error/ArgumentError\";\nimport { Options } from \"./types\";\nexport { ArgumentError };\n\n/**\n * Validates a configuration directory path to ensure it's safe and valid.\n * \n * Performs security and safety checks including:\n * - Non-empty string validation\n * - Null byte injection prevention\n * - Path length validation\n * - Type checking\n * \n * @param configDirectory - The configuration directory path to validate\n * @param _testThrowNonArgumentError - Internal testing parameter to simulate non-ArgumentError exceptions\n * @returns The trimmed and validated configuration directory path\n * @throws {ArgumentError} When the directory path is invalid\n * \n * @example\n * ```typescript\n * const validDir = validateConfigDirectory('./config'); // Returns './config'\n * const invalidDir = validateConfigDirectory(''); // Throws ArgumentError\n * ```\n */\nexport function validateConfigDirectory(configDirectory: string, _testThrowNonArgumentError?: boolean): string {\n if (_testThrowNonArgumentError) {\n throw new Error('Test non-ArgumentError for coverage');\n }\n\n if (!configDirectory) {\n throw new ArgumentError('configDirectory', 'Configuration directory cannot be empty');\n }\n\n if (typeof configDirectory !== 'string') {\n throw new ArgumentError('configDirectory', 'Configuration directory must be a string');\n }\n\n const trimmed = configDirectory.trim();\n if (trimmed.length === 0) {\n throw new ArgumentError('configDirectory', 'Configuration directory cannot be empty or whitespace only');\n }\n\n // Check for obviously invalid paths\n if (trimmed.includes('\\0')) {\n throw new ArgumentError('configDirectory', 'Configuration directory contains invalid null character');\n }\n\n // Validate path length (reasonable limit)\n if (trimmed.length > 1000) {\n throw new ArgumentError('configDirectory', 'Configuration directory path is too long (max 1000 characters)');\n }\n\n return trimmed;\n}\n\n/**\n * Configures a Commander.js command with Cardigantime's CLI options.\n * \n * This function adds command-line options that allow users to override\n * configuration settings at runtime, such as:\n * - --config-directory: Override the default configuration directory\n * \n * The function validates both the command object and the options to ensure\n * they meet the requirements for proper integration.\n * \n * @template T - The Zod schema shape type for configuration validation\n * @param command - The Commander.js Command instance to configure\n * @param options - Cardigantime options containing defaults and schema\n * @param _testThrowNonArgumentError - Internal testing parameter\n * @returns Promise resolving to the configured Command instance\n * @throws {ArgumentError} When command or options are invalid\n * \n * @example\n * ```typescript\n * import { Command } from 'commander';\n * import { configure } from './configure';\n * \n * const program = new Command();\n * const configuredProgram = await configure(program, options);\n * \n * // Now the program accepts: --config-directory <path>\n * ```\n */\nexport const configure = async <T extends z.ZodRawShape>(\n command: Command,\n options: Options<T>,\n _testThrowNonArgumentError?: boolean\n): Promise<Command> => {\n // Validate the command object\n if (!command) {\n throw new ArgumentError('command', 'Command instance is required');\n }\n\n if (typeof command.option !== 'function') {\n throw new ArgumentError('command', 'Command must be a valid Commander.js Command instance');\n }\n\n // Validate options\n if (!options) {\n throw new ArgumentError('options', 'Options object is required');\n }\n\n if (!options.defaults) {\n throw new ArgumentError('options.defaults', 'Options must include defaults configuration');\n }\n\n if (!options.defaults.configDirectory) {\n throw new ArgumentError('options.defaults.configDirectory', 'Default config directory is required');\n }\n\n // Validate the default config directory\n const validatedDefaultDir = validateConfigDirectory(options.defaults.configDirectory, _testThrowNonArgumentError);\n\n let retCommand = command;\n\n // Add the config directory option with validation\n retCommand = retCommand.option(\n '-c, --config-directory <configDirectory>',\n 'Configuration directory path',\n (value: string) => {\n try {\n return validateConfigDirectory(value, _testThrowNonArgumentError);\n } catch (error) {\n if (error instanceof ArgumentError) {\n // Re-throw with more specific context for CLI usage\n throw new ArgumentError('config-directory', `Invalid --config-directory: ${error.message}`);\n }\n throw error;\n }\n },\n validatedDefaultDir\n );\n\n // Add the init config option\n retCommand = retCommand.option(\n '--init-config',\n 'Generate initial configuration file and exit'\n );\n\n // Add the check config option\n retCommand = retCommand.option(\n '--check-config',\n 'Display resolved configuration with source tracking and exit'\n );\n\n // Add the config format option\n retCommand = retCommand.option(\n '--config-format <format>',\n 'Force a specific configuration file format (yaml, json, javascript, typescript)',\n (value: string) => {\n const validFormats = ['yaml', 'json', 'javascript', 'typescript'];\n const normalized = value.toLowerCase();\n if (!validFormats.includes(normalized)) {\n throw new ArgumentError(\n 'config-format',\n `Invalid --config-format: must be one of ${validFormats.join(', ')}`\n );\n }\n return normalized;\n }\n );\n\n return retCommand;\n}\n\n\n\n\n","import { DefaultOptions, Feature, Logger } from \"./types\";\n\n/** Version string populated at build time with git and system information */\nexport const VERSION = '__VERSION__ (__GIT_BRANCH__/__GIT_COMMIT__ __GIT_TAGS__ __GIT_COMMIT_DATE__) __SYSTEM_INFO__';\n\n/** The program name used in CLI help and error messages */\nexport const PROGRAM_NAME = 'cardigantime';\n\n/** Default file encoding for reading configuration files */\nexport const DEFAULT_ENCODING = 'utf8';\n\n/** Default configuration file name to look for in the config directory */\nexport const DEFAULT_CONFIG_FILE = 'config.yaml';\n\n/**\n * Default configuration options applied when creating a Cardigantime instance.\n * These provide sensible defaults that work for most use cases.\n */\nexport const DEFAULT_OPTIONS: Partial<DefaultOptions> = {\n configFile: DEFAULT_CONFIG_FILE,\n isRequired: false,\n encoding: DEFAULT_ENCODING,\n pathResolution: undefined, // No path resolution by default\n}\n\n/**\n * Default features enabled when creating a Cardigantime instance.\n * Currently includes only the 'config' feature for configuration file support.\n */\nexport const DEFAULT_FEATURES: Feature[] = ['config'];\n\n/**\n * Default logger implementation using console methods.\n * Provides basic logging functionality when no custom logger is specified.\n * The verbose and silly methods are no-ops to avoid excessive output.\n */\nexport const DEFAULT_LOGGER: Logger = {\n // eslint-disable-next-line no-console\n debug: console.debug,\n // eslint-disable-next-line no-console\n info: console.info,\n // eslint-disable-next-line no-console\n warn: console.warn,\n // eslint-disable-next-line no-console\n error: console.error,\n\n verbose: () => { },\n\n silly: () => { },\n}\n","/**\n * Error thrown when file system operations fail\n */\nexport class FileSystemError extends Error {\n public readonly errorType: 'not_found' | 'not_readable' | 'not_writable' | 'creation_failed' | 'operation_failed';\n public readonly path: string;\n public readonly operation: string;\n public readonly originalError?: Error;\n\n constructor(\n errorType: 'not_found' | 'not_readable' | 'not_writable' | 'creation_failed' | 'operation_failed',\n message: string,\n path: string,\n operation: string,\n originalError?: Error\n ) {\n super(message);\n this.name = 'FileSystemError';\n this.errorType = errorType;\n this.path = path;\n this.operation = operation;\n this.originalError = originalError;\n }\n\n /**\n * Creates an error for when a required directory doesn't exist\n */\n static directoryNotFound(path: string, isRequired: boolean = false): FileSystemError {\n const message = isRequired\n ? 'Configuration directory does not exist and is required'\n : 'Configuration directory not found';\n return new FileSystemError('not_found', message, path, 'directory_access');\n }\n\n /**\n * Creates an error for when a directory exists but isn't readable\n */\n static directoryNotReadable(path: string): FileSystemError {\n const message = 'Configuration directory exists but is not readable';\n return new FileSystemError('not_readable', message, path, 'directory_read');\n }\n\n /**\n * Creates an error for directory creation failures\n */\n static directoryCreationFailed(path: string, originalError: Error): FileSystemError {\n const message = 'Failed to create directory: ' + (originalError.message || 'Unknown error');\n return new FileSystemError('creation_failed', message, path, 'directory_create', originalError);\n }\n\n /**\n * Creates an error for file operation failures (glob, etc.)\n */\n static operationFailed(operation: string, path: string, originalError: Error): FileSystemError {\n const message = `Failed to ${operation}: ${originalError.message || 'Unknown error'}`;\n return new FileSystemError('operation_failed', message, path, operation, originalError);\n }\n\n /**\n * Creates an error for when a file is not found\n */\n static fileNotFound(path: string): FileSystemError {\n const message = 'Configuration file not found';\n return new FileSystemError('not_found', message, path, 'file_read');\n }\n} ","import * as fs from 'node:fs';\nimport { glob } from 'glob';\nimport * as path from 'node:path';\nimport * as crypto from 'node:crypto';\nimport { FileSystemError } from '../error/FileSystemError';\n/**\n * This module exists to isolate filesystem operations from the rest of the codebase.\n * This makes testing easier by avoiding direct fs mocking in jest configuration.\n * \n * Additionally, abstracting storage operations allows for future flexibility - \n * this export utility may need to work with storage systems other than the local filesystem\n * (e.g. S3, Google Cloud Storage, etc).\n */\n\nexport interface Utility {\n exists: (path: string) => Promise<boolean>;\n isDirectory: (path: string) => Promise<boolean>;\n isFile: (path: string) => Promise<boolean>;\n isReadable: (path: string) => Promise<boolean>;\n isWritable: (path: string) => Promise<boolean>;\n isFileReadable: (path: string) => Promise<boolean>;\n isDirectoryWritable: (path: string) => Promise<boolean>;\n isDirectoryReadable: (path: string) => Promise<boolean>;\n createDirectory: (path: string) => Promise<void>;\n readFile: (path: string, encoding: string) => Promise<string>;\n readStream: (path: string) => Promise<fs.ReadStream>;\n writeFile: (path: string, data: string | Buffer, encoding: string) => Promise<void>;\n forEachFileIn: (directory: string, callback: (path: string) => Promise<void>, options?: { pattern: string }) => Promise<void>;\n hashFile: (path: string, length: number) => Promise<string>;\n listFiles: (directory: string) => Promise<string[]>;\n}\n\nexport const create = (params: { log?: (message: string, ...args: any[]) => void }): Utility => {\n\n // eslint-disable-next-line no-console\n const log = params.log || console.log;\n\n const exists = async (path: string): Promise<boolean> => {\n try {\n await fs.promises.stat(path);\n return true;\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (error: any) {\n return false;\n }\n }\n\n const isDirectory = async (path: string): Promise<boolean> => {\n const stats = await fs.promises.stat(path);\n if (!stats.isDirectory()) {\n log(`${path} is not a directory`);\n return false;\n }\n return true;\n }\n\n const isFile = async (path: string): Promise<boolean> => {\n const stats = await fs.promises.stat(path);\n if (!stats.isFile()) {\n log(`${path} is not a file`);\n return false;\n }\n return true;\n }\n\n const isReadable = async (path: string): Promise<boolean> => {\n try {\n await fs.promises.access(path, fs.constants.R_OK);\n } catch (error: any) {\n log(`${path} is not readable: %s %s`, error.message, error.stack);\n return false;\n }\n return true;\n }\n\n const isWritable = async (path: string): Promise<boolean> => {\n try {\n await fs.promises.access(path, fs.constants.W_OK);\n } catch (error: any) {\n log(`${path} is not writable: %s %s`, error.message, error.stack);\n return false;\n }\n return true;\n }\n\n const isFileReadable = async (path: string): Promise<boolean> => {\n return await exists(path) && await isFile(path) && await isReadable(path);\n }\n\n const isDirectoryWritable = async (path: string): Promise<boolean> => {\n return await exists(path) && await isDirectory(path) && await isWritable(path);\n }\n\n const isDirectoryReadable = async (path: string): Promise<boolean> => {\n return await exists(path) && await isDirectory(path) && await isReadable(path);\n }\n\n const createDirectory = async (path: string): Promise<void> => {\n try {\n await fs.promises.mkdir(path, { recursive: true });\n } catch (mkdirError: any) {\n throw FileSystemError.directoryCreationFailed(path, mkdirError);\n }\n }\n\n const readFile = async (path: string, encoding: string): Promise<string> => {\n // Validate encoding parameter\n const validEncodings = ['utf8', 'utf-8', 'ascii', 'latin1', 'base64', 'hex', 'utf16le', 'ucs2', 'ucs-2'];\n if (!validEncodings.includes(encoding.toLowerCase())) {\n throw new Error('Invalid encoding specified');\n }\n\n // Check file size before reading to prevent DoS\n try {\n const stats = await fs.promises.stat(path);\n const maxFileSize = 10 * 1024 * 1024; // 10MB limit\n if (stats.size > maxFileSize) {\n throw new Error('File too large to process');\n }\n } catch (error: any) {\n if (error.code === 'ENOENT') {\n throw FileSystemError.fileNotFound(path);\n }\n throw error;\n }\n\n return await fs.promises.readFile(path, { encoding: encoding as BufferEncoding });\n }\n\n const writeFile = async (path: string, data: string | Buffer, encoding: string): Promise<void> => {\n await fs.promises.writeFile(path, data, { encoding: encoding as BufferEncoding });\n }\n\n const forEachFileIn = async (directory: string, callback: (file: string) => Promise<void>, options: { pattern: string | string[] } = { pattern: '*.*' }): Promise<void> => {\n try {\n const files = await glob(options.pattern, { cwd: directory, nodir: true });\n for (const file of files) {\n await callback(path.join(directory, file));\n }\n } catch (err: any) {\n throw FileSystemError.operationFailed(`glob pattern ${options.pattern}`, directory, err);\n }\n }\n\n const readStream = async (path: string): Promise<fs.ReadStream> => {\n return fs.createReadStream(path);\n }\n\n const hashFile = async (path: string, length: number): Promise<string> => {\n const file = await readFile(path, 'utf8');\n return crypto.createHash('sha256').update(file).digest('hex').slice(0, length);\n }\n\n const listFiles = async (directory: string): Promise<string[]> => {\n return await fs.promises.readdir(directory);\n }\n\n return {\n exists,\n isDirectory,\n isFile,\n isReadable,\n isWritable,\n isFileReadable,\n isDirectoryWritable,\n isDirectoryReadable,\n createDirectory,\n readFile,\n readStream,\n writeFile,\n forEachFileIn,\n hashFile,\n listFiles,\n };\n}","import * as path from 'node:path';\nimport * as yaml from 'js-yaml';\nimport { create as createStorage } from './storage';\nimport { Logger, FieldOverlapOptions, ArrayOverlapMode } from '../types';\n\n/**\n * Resolves relative paths in configuration values relative to the configuration file's directory.\n */\nfunction resolveConfigPaths(\n config: any,\n configDir: string,\n pathFields: string[] = [],\n resolvePathArray: string[] = []\n): any {\n if (!config || typeof config !== 'object' || pathFields.length === 0) {\n return config;\n }\n\n const resolvedConfig = { ...config };\n\n for (const fieldPath of pathFields) {\n const value = getNestedValue(resolvedConfig, fieldPath);\n if (value !== undefined) {\n const shouldResolveArrayElements = resolvePathArray.includes(fieldPath);\n const resolvedValue = resolvePathValue(value, configDir, shouldResolveArrayElements);\n setNestedValue(resolvedConfig, fieldPath, resolvedValue);\n }\n }\n\n return resolvedConfig;\n}\n\n/**\n * Gets a nested value from an object using dot notation.\n */\nfunction getNestedValue(obj: any, path: string): any {\n return path.split('.').reduce((current, key) => current?.[key], obj);\n}\n\n/**\n * Sets a nested value in an object using dot notation.\n */\nfunction isUnsafeKey(key: string): boolean {\n return key === '__proto__' || key === 'constructor' || key === 'prototype';\n}\n\nfunction setNestedValue(obj: any, path: string, value: any): void {\n const keys = path.split('.');\n const lastKey = keys.pop()!;\n\n // Prevent prototype pollution via special property names\n if (isUnsafeKey(lastKey) || keys.some(isUnsafeKey)) {\n return;\n }\n\n const target = keys.reduce((current, key) => {\n // Skip if this is an unsafe key (already checked above, but defensive)\n if (isUnsafeKey(key)) {\n return current;\n }\n if (!(key in current)) {\n current[key] = {};\n }\n return current[key];\n }, obj);\n target[lastKey] = value;\n}\n\n/**\n * Resolves a path value (string or array of strings) relative to the config directory.\n */\nfunction resolvePathValue(value: any, configDir: string, resolveArrayElements: boolean): any {\n if (typeof value === 'string') {\n return resolveSinglePath(value, configDir);\n }\n\n if (Array.isArray(value) && resolveArrayElements) {\n return value.map(item =>\n typeof item === 'string' ? resolveSinglePath(item, configDir) : item\n );\n }\n\n return value;\n}\n\n/**\n * Resolves a single path string relative to the config directory if it's a relative path.\n */\nfunction resolveSinglePath(pathStr: string, configDir: string): string {\n if (!pathStr || path.isAbsolute(pathStr)) {\n return pathStr;\n }\n\n return path.resolve(configDir, pathStr);\n}\n\n/**\n * Represents a discovered configuration directory with its path and precedence level.\n */\nexport interface DiscoveredConfigDir {\n /** Absolute path to the configuration directory */\n path: string;\n /** Distance from the starting directory (0 = closest/highest precedence) */\n level: number;\n}\n\n/**\n * Options for hierarchical configuration discovery.\n */\nexport interface HierarchicalDiscoveryOptions {\n /** Name of the configuration directory to look for (e.g., '.kodrdriv') */\n configDirName: string;\n /** Name of the configuration file within each directory */\n configFileName: string;\n /** Maximum number of parent directories to traverse (default: 10) */\n maxLevels?: number;\n /** Starting directory for discovery (default: process.cwd()) */\n startingDir?: string;\n /** File encoding for reading configuration files */\n encoding?: string;\n /** Logger for debugging */\n logger?: Logger;\n /** Array of field names that contain paths to be resolved */\n pathFields?: string[];\n /** Array of field names whose array elements should all be resolved as paths */\n resolvePathArray?: string[];\n /** Configuration for how array fields should be merged in hierarchical mode */\n fieldOverlaps?: FieldOverlapOptions;\n}\n\n/**\n * Result of loading configurations from multiple directories.\n */\nexport interface HierarchicalConfigResult {\n /** Merged configuration object with proper precedence */\n config: object;\n /** Array of directories where configuration was found */\n discoveredDirs: DiscoveredConfigDir[];\n /** Array of directories that actually contained valid configuration files */\n resolvedConfigDirs: DiscoveredConfigDir[];\n /** Array of any errors encountered during loading (non-fatal) */\n errors: string[];\n}\n\n/**\n * Discovers configuration directories by traversing up the directory tree.\n * \n * Starting from the specified directory (or current working directory),\n * this function searches for directories with the given name, continuing\n * up the directory tree until it reaches the filesystem root or the\n * maximum number of levels.\n * \n * @param options Configuration options for discovery\n * @returns Promise resolving to array of discovered configuration directories\n * \n * @example\n * ```typescript\n * const dirs = await discoverConfigDirectories({\n * configDirName: '.kodrdriv',\n * configFileName: 'config.yaml',\n * maxLevels: 5\n * });\n * // Returns: [\n * // { path: '/project/.kodrdriv', level: 0 },\n * // { path: '/project/parent/.kodrdriv', level: 1 }\n * // ]\n * ```\n */\nexport async function discoverConfigDirectories(\n options: HierarchicalDiscoveryOptions\n): Promise<DiscoveredConfigDir[]> {\n const {\n configDirName,\n maxLevels = 10,\n startingDir = process.cwd(),\n logger\n } = options;\n\n const storage = createStorage({ log: logger?.debug || (() => { }) });\n const discoveredDirs: DiscoveredConfigDir[] = [];\n\n let currentDir = path.resolve(startingDir);\n let level = 0;\n const visited = new Set<string>(); // Prevent infinite loops with symlinks\n\n logger?.debug(`Starting hierarchical discovery from: ${currentDir}`);\n\n while (level < maxLevels) {\n // Prevent infinite loops with symlinks\n const realPath = path.resolve(currentDir);\n if (visited.has(realPath)) {\n logger?.debug(`Already visited ${realPath}, stopping discovery`);\n break;\n }\n visited.add(realPath);\n\n const configDirPath = path.join(currentDir, configDirName);\n logger?.debug(`Checking for config directory: ${configDirPath}`);\n\n try {\n const exists = await storage.exists(configDirPath);\n const isReadable = exists && await storage.isDirectoryReadable(configDirPath);\n\n if (exists && isReadable) {\n discoveredDirs.push({\n path: configDirPath,\n level\n });\n logger?.debug(`Found config directory at level ${level}: ${configDirPath}`);\n } else if (exists && !isReadable) {\n logger?.debug(`Config directory exists but is not readable: ${configDirPath}`);\n }\n } catch (error: any) {\n logger?.debug(`Error checking config directory ${configDirPath}: ${error.message}`);\n }\n\n // Move up one directory level\n const parentDir = path.dirname(currentDir);\n\n // Check if we've reached the root directory\n if (parentDir === currentDir) {\n logger?.debug('Reached filesystem root, stopping discovery');\n break;\n }\n\n currentDir = parentDir;\n level++;\n }\n\n logger?.verbose(`Discovery complete. Found ${discoveredDirs.length} config directories`);\n return discoveredDirs;\n}\n\n/**\n * Tries to find a config file with alternative extensions (.yaml or .yml).\n * \n * @param storage Storage instance to use for file operations\n * @param configDir The directory containing the config file\n * @param configFileName The base config file name (may have .yaml or .yml extension)\n * @param logger Optional logger for debugging\n * @returns Promise resolving to the found config file path or null if not found\n */\nasync function findConfigFileWithExtension(\n storage: any,\n configDir: string,\n configFileName: string,\n logger?: Logger\n): Promise<string | null> {\n const configFilePath = path.join(configDir, configFileName);\n \n // First try the exact filename as specified\n const exists = await storage.exists(configFilePath);\n if (exists) {\n const isReadable = await storage.isFileReadable(configFilePath);\n if (isReadable) {\n return configFilePath;\n }\n }\n \n // If the exact filename doesn't exist or isn't readable, try alternative extensions\n // Only do this if the filename has a .yaml or .yml extension\n const ext = path.extname(configFileName);\n if (ext === '.yaml' || ext === '.yml') {\n const baseName = path.basename(configFileName, ext);\n const alternativeExt = ext === '.yaml' ? '.yml' : '.yaml';\n const alternativePath = path.join(configDir, baseName + alternativeExt);\n \n logger?.debug(`Config file not found at ${configFilePath}, trying alternative: ${alternativePath}`);\n \n const altExists = await storage.exists(alternativePath);\n if (altExists) {\n const altIsReadable = await storage.isFileReadable(alternativePath);\n if (altIsReadable) {\n logger?.debug(`Found config file with alternative extension: ${alternativePath}`);\n return alternativePath;\n }\n }\n }\n \n return null;\n}\n\n/**\n * Loads and parses a configuration file from a directory.\n * \n * @param configDir Path to the configuration directory\n * @param configFileName Name of the configuration file\n * @param encoding File encoding\n * @param logger Optional logger\n * @param pathFields Optional array of field names that contain paths to be resolved\n * @param resolvePathArray Optional array of field names whose array elements should all be resolved as paths\n * @returns Promise resolving to parsed configuration object or null if not found\n */\nexport async function loadConfigFromDirectory(\n configDir: string,\n configFileName: string,\n encoding: string = 'utf8',\n logger?: Logger,\n pathFields?: string[],\n resolvePathArray?: string[]\n): Promise<object | null> {\n const storage = createStorage({ log: logger?.debug || (() => { }) });\n \n try {\n logger?.verbose(`Attempting to load config file: ${path.join(configDir, configFileName)}`);\n\n // Try to find the config file with alternative extensions\n const configFilePath = await findConfigFileWithExtension(storage, configDir, configFileName, logger);\n \n if (!configFilePath) {\n logger?.debug(`Config file does not exist: ${path.join(configDir, configFileName)}`);\n return null;\n }\n\n const yamlContent = await storage.readFile(configFilePath, encoding);\n const parsedYaml = yaml.load(yamlContent);\n\n if (parsedYaml !== null && typeof parsedYaml === 'object') {\n let config = parsedYaml as object;\n\n // Apply path resolution if configured\n if (pathFields && pathFields.length > 0) {\n config = resolveConfigPaths(config, configDir, pathFields, resolvePathArray || []);\n }\n\n logger?.verbose(`Successfully loaded config from: ${configFilePath}`);\n return config;\n } else {\n logger?.debug(`Config file contains invalid format: ${configFilePath}`);\n return null;\n }\n } catch (error: any) {\n logger?.debug(`Error loading config from ${path.join(configDir, configFileName)}: ${error.message}`);\n return null;\n }\n}\n\n/**\n * Deep merges multiple configuration objects with proper precedence and configurable array overlap behavior.\n * \n * Objects are merged from lowest precedence to highest precedence,\n * meaning that properties in later objects override properties in earlier objects.\n * Arrays can be merged using different strategies based on the fieldOverlaps configuration.\n * \n * @param configs Array of configuration objects, ordered from lowest to highest precedence\n * @param fieldOverlaps Configuration for how array fields should be merged (optional)\n * @returns Merged configuration object\n * \n * @example\n * ```typescript\n * const merged = deepMergeConfigs([\n * { api: { timeout: 5000 }, features: ['auth'] }, // Lower precedence\n * { api: { retries: 3 }, features: ['analytics'] }, // Higher precedence\n * ], {\n * 'features': 'append' // Results in features: ['auth', 'analytics']\n * });\n * ```\n */\nexport function deepMergeConfigs(configs: object[], fieldOverlaps?: FieldOverlapOptions): object {\n if (configs.length === 0) {\n return {};\n }\n\n if (configs.length === 1) {\n return { ...configs[0] };\n }\n\n return configs.reduce((merged, current) => {\n return deepMergeTwo(merged, current, fieldOverlaps);\n }, {});\n}\n\n/**\n * Deep merges two objects with proper precedence and configurable array overlap behavior.\n * \n * @param target Target object (lower precedence)\n * @param source Source object (higher precedence)\n * @param fieldOverlaps Configuration for how array fields should be merged (optional)\n * @param currentPath Current field path for nested merging (used internally)\n * @returns Merged object\n */\nfunction deepMergeTwo(target: any, source: any, fieldOverlaps?: FieldOverlapOptions, currentPath: string = ''): any {\n // Handle null/undefined\n if (source == null) return target;\n if (target == null) return source;\n\n // Handle non-objects (primitives, arrays, functions, etc.)\n if (typeof source !== 'object' || typeof target !== 'object') {\n return source; // Source takes precedence\n }\n\n // Handle arrays with configurable overlap behavior\n if (Array.isArray(source)) {\n if (Array.isArray(target) && fieldOverlaps) {\n const overlapMode = getOverlapModeForPath(currentPath, fieldOverlaps);\n return mergeArrays(target, source, overlapMode);\n } else {\n // Default behavior: replace entirely\n return [...source];\n }\n }\n\n if (Array.isArray(target)) {\n return source; // Source object replaces target array\n }\n\n // Deep merge objects\n const result = { ...target };\n\n for (const key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n const fieldPath = currentPath ? `${currentPath}.${key}` : key;\n\n if (Object.prototype.hasOwnProperty.call(result, key) &&\n typeof result[key] === 'object' &&\n typeof source[key] === 'object' &&\n !Array.isArray(source[key]) &&\n !Array.isArray(result[key])) {\n // Recursively merge nested objects\n result[key] = deepMergeTwo(result[key], source[key], fieldOverlaps, fieldPath);\n } else {\n // Handle arrays and primitives with overlap consideration\n if (Array.isArray(source[key]) && Array.isArray(result[key]) && fieldOverlaps) {\n const overlapMode = getOverlapModeForPath(fieldPath, fieldOverlaps);\n result[key] = mergeArrays(result[key], source[key], overlapMode);\n } else {\n // Replace with source value (higher precedence)\n result[key] = source[key];\n }\n }\n }\n }\n\n return result;\n}\n\n/**\n * Determines the overlap mode for a given field path.\n * \n * @param fieldPath The current field path (dot notation)\n * @param fieldOverlaps Configuration mapping field paths to overlap modes\n * @returns The overlap mode to use for this field path\n */\nfunction getOverlapModeForPath(fieldPath: string, fieldOverlaps: FieldOverlapOptions): ArrayOverlapMode {\n // Check for exact match first\n if (fieldPath in fieldOverlaps) {\n return fieldOverlaps[fieldPath];\n }\n\n // Check for any parent path matches (for nested configurations)\n const pathParts = fieldPath.split('.');\n for (let i = pathParts.length - 1; i > 0; i--) {\n const parentPath = pathParts.slice(0, i).join('.');\n if (parentPath in fieldOverlaps) {\n return fieldOverlaps[parentPath];\n }\n }\n\n // Default to override if no specific configuration found\n return 'override';\n}\n\n/**\n * Merges two arrays based on the specified overlap mode.\n * \n * @param targetArray The lower precedence array\n * @param sourceArray The higher precedence array\n * @param mode The overlap mode to use\n * @returns The merged array\n */\nfunction mergeArrays(targetArray: any[], sourceArray: any[], mode: ArrayOverlapMode): any[] {\n switch (mode) {\n case 'append':\n return [...targetArray, ...sourceArray];\n case 'prepend':\n return [...sourceArray, ...targetArray];\n case 'override':\n default:\n return [...sourceArray];\n }\n}\n\n/**\n * Loads configurations from multiple directories and merges them with proper precedence.\n * \n * This is the main function for hierarchical configuration loading. It:\n * 1. Discovers configuration directories up the directory tree\n * 2. Loads configuration files from each discovered directory\n * 3. Merges them with proper precedence (closer directories win)\n * 4. Returns the merged configuration with metadata\n * \n * @param options Configuration options for hierarchical loading\n * @returns Promise resolving to hierarchical configuration result\n * \n * @example\n * ```typescript\n * const result = await loadHierarchicalConfig({\n * configDirName: '.kodrdriv',\n * configFileName: 'config.yaml',\n * startingDir: '/project/subdir',\n * maxLevels: 5,\n * fieldOverlaps: {\n * 'features': 'append',\n * 'excludePatterns': 'prepend'\n * }\n * });\n * \n * // result.config contains merged configuration with custom array merging\n * // result.discoveredDirs shows where configs were found\n * // result.errors contains any non-fatal errors\n * ```\n */\nexport async function loadHierarchicalConfig(\n options: HierarchicalDiscoveryOptions\n): Promise<HierarchicalConfigResult> {\n const { configFileName, encoding = 'utf8', logger, pathFields, resolvePathArray, fieldOverlaps } = options;\n\n logger?.verbose('Starting hierarchical configuration loading');\n\n // Discover all configuration directories\n const discoveredDirs = await discoverConfigDirectories(options);\n\n if (discoveredDirs.length === 0) {\n logger?.verbose('No configuration directories found');\n return {\n config: {},\n discoveredDirs: [],\n resolvedConfigDirs: [],\n errors: []\n };\n }\n\n // Load configurations from each directory\n const configs: object[] = [];\n const resolvedConfigDirs: DiscoveredConfigDir[] = [];\n const errors: string[] = [];\n\n // Sort by level (highest level first = lowest precedence first)\n const sortedDirs = [...discoveredDirs].sort((a, b) => b.level - a.level);\n\n for (const dir of sortedDirs) {\n try {\n const config = await loadConfigFromDirectory(\n dir.path,\n configFileName,\n encoding,\n logger,\n pathFields,\n resolvePathArray\n );\n\n if (config !== null) {\n configs.push(config);\n resolvedConfigDirs.push(dir);\n logger?.debug(`Loaded config from level ${dir.level}: ${dir.path}`);\n } else {\n logger?.debug(`No valid config found at level ${dir.level}: ${dir.path}`);\n }\n } catch (error: any) {\n const errorMsg = `Failed to load config from ${dir.path}: ${error.message}`;\n errors.push(errorMsg);\n logger?.debug(errorMsg);\n }\n }\n\n // Merge all configurations with proper precedence and configurable array overlap\n const mergedConfig = deepMergeConfigs(configs, fieldOverlaps);\n\n logger?.verbose(`Hierarchical loading complete. Merged ${configs.length} configurations`);\n\n return {\n config: mergedConfig,\n discoveredDirs,\n resolvedConfigDirs,\n errors\n };\n} ","import * as yaml from 'js-yaml';\nimport * as path from 'node:path';\nimport { z, ZodObject } from 'zod';\nimport { Args, ConfigSchema, Options } from './types';\nimport * as Storage from './util/storage';\nimport { loadHierarchicalConfig, DiscoveredConfigDir } from './util/hierarchical';\n\n/**\n * Removes undefined values from an object to create a clean configuration.\n * This is used to merge configuration sources while avoiding undefined pollution.\n * \n * @param obj - The object to clean\n * @returns A new object with undefined values filtered out\n */\nfunction clean(obj: any) {\n return Object.fromEntries(\n Object.entries(obj).filter(([_, v]) => v !== undefined)\n );\n}\n\n/**\n * Resolves relative paths in configuration values relative to the configuration file's directory.\n * \n * @param config - The configuration object to process\n * @param configDir - The directory containing the configuration file\n * @param pathFields - Array of field names (using dot notation) that contain paths to be resolved\n * @param resolvePathArray - Array of field names whose array elements should all be resolved as paths\n * @returns The configuration object with resolved paths\n */\nfunction resolveConfigPaths(\n config: any,\n configDir: string,\n pathFields: string[] = [],\n resolvePathArray: string[] = []\n): any {\n if (!config || typeof config !== 'object' || pathFields.length === 0) {\n return config;\n }\n\n const resolvedConfig = { ...config };\n\n for (const fieldPath of pathFields) {\n const value = getNestedValue(resolvedConfig, fieldPath);\n if (value !== undefined) {\n const shouldResolveArrayElements = resolvePathArray.includes(fieldPath);\n const resolvedValue = resolvePathValue(value, configDir, shouldResolveArrayElements);\n setNestedValue(resolvedConfig, fieldPath, resolvedValue);\n }\n }\n\n return resolvedConfig;\n}\n\n/**\n * Gets a nested value from an object using dot notation.\n */\nfunction getNestedValue(obj: any, path: string): any {\n return path.split('.').reduce((current, key) => current?.[key], obj);\n}\n\n/**\n * Checks if a key is unsafe for prototype pollution prevention.\n */\nfunction isUnsafeKey(key: string): boolean {\n return key === '__proto__' || key === 'constructor' || key === 'prototype';\n}\n\n/**\n * Sets a nested value in an object using dot notation.\n * Prevents prototype pollution by rejecting dangerous property names.\n */\nfunction setNestedValue(obj: any, path: string, value: any): void {\n const keys = path.split('.');\n const lastKey = keys.pop()!;\n\n // Prevent prototype pollution via special property names\n if (isUnsafeKey(lastKey) || keys.some(isUnsafeKey)) {\n return;\n }\n\n const target = keys.reduce((current, key) => {\n // Skip if this is an unsafe key (already checked above, but defensive)\n if (isUnsafeKey(key)) {\n return current;\n }\n if (!(key in current)) {\n current[key] = {};\n }\n return current[key];\n }, obj);\n target[lastKey] = value;\n}\n\n/**\n * Resolves a path value (string or array of strings) relative to the config directory.\n */\nfunction resolvePathValue(value: any, configDir: string, resolveArrayElements: boolean): any {\n if (typeof value === 'string') {\n return resolveSinglePath(value, configDir);\n }\n\n if (Array.isArray(value) && resolveArrayElements) {\n return value.map(item =>\n typeof item === 'string' ? resolveSinglePath(item, configDir) : item\n );\n }\n\n return value;\n}\n\n/**\n * Resolves a single path string relative to the config directory if it's a relative path.\n */\nfunction resolveSinglePath(pathStr: string, configDir: string): string {\n if (!pathStr || path.isAbsolute(pathStr)) {\n return pathStr;\n }\n\n return path.resolve(configDir, pathStr);\n}\n\n/**\n * Validates and secures a user-provided path to prevent path traversal attacks.\n * \n * Security checks include:\n * - Path traversal prevention (blocks '..')\n * - Absolute path detection\n * - Path separator validation\n * \n * @param userPath - The user-provided path component\n * @param basePath - The base directory to join the path with\n * @returns The safely joined and normalized path\n * @throws {Error} When path traversal or absolute paths are detected\n */\nfunction validatePath(userPath: string, basePath: string): string {\n if (!userPath || !basePath) {\n throw new Error('Invalid path parameters');\n }\n\n const normalized = path.normalize(userPath);\n\n // Prevent path traversal attacks\n if (normalized.includes('..') || path.isAbsolute(normalized)) {\n throw new Error('Invalid path: path traversal detected');\n }\n\n // Ensure the path doesn't start with a path separator\n if (normalized.startsWith('/') || normalized.startsWith('\\\\')) {\n throw new Error('Invalid path: absolute path detected');\n }\n\n return path.join(basePath, normalized);\n}\n\n/**\n * Validates a configuration directory path for security and basic formatting.\n * \n * Performs validation to prevent:\n * - Null byte injection attacks\n * - Extremely long paths that could cause DoS\n * - Empty or invalid directory specifications\n * \n * @param configDir - The configuration directory path to validate\n * @returns The normalized configuration directory path\n * @throws {Error} When the directory path is invalid or potentially dangerous\n */\nfunction validateConfigDirectory(configDir: string): string {\n if (!configDir) {\n throw new Error('Configuration directory is required');\n }\n\n // Check for null bytes which could be used for path injection\n if (configDir.includes('\\0')) {\n throw new Error('Invalid path: null byte detected');\n }\n\n const normalized = path.normalize(configDir);\n\n // Basic validation - could be expanded based on requirements\n if (normalized.length > 1000) {\n throw new Error('Configuration directory path too long');\n }\n\n return normalized;\n}\n\n/**\n * Reads configuration from files and merges it with CLI arguments.\n * \n * This function implements the core configuration loading logic:\n * 1. Validates and resolves the configuration directory path\n * 2. Attempts to read the YAML configuration file\n * 3. Safely parses the YAML content with security protections\n * 4. Merges file configuration with runtime arguments\n * 5. Returns a typed configuration object\n * \n * The function handles missing files gracefully and provides detailed\n * logging for troubleshooting configuration issues.\n * \n * @template T - The Zod schema shape type for configuration validation\n * @param args - Parsed command-line arguments containing potential config overrides\n * @param options - Cardigantime options with defaults, schema, and logger\n * @returns Promise resolving to the merged and typed configuration object\n * @throws {Error} When configuration directory is invalid or required files cannot be read\n * \n * @example\n * ```typescript\n * const config = await read(cliArgs, {\n * defaults: { configDirectory: './config', configFile: 'app.yaml' },\n * configShape: MySchema.shape,\n * logger: console,\n * features: ['config']\n * });\n * // config is fully typed based on your schema\n * ```\n */\nexport const read = async <T extends z.ZodRawShape>(args: Args, options: Options<T>): Promise<z.infer<ZodObject<T & typeof ConfigSchema.shape>>> => {\n const logger = options.logger;\n\n const rawConfigDir = args.configDirectory || options.defaults?.configDirectory;\n if (!rawConfigDir) {\n throw new Error('Configuration directory must be specified');\n }\n\n const resolvedConfigDir = validateConfigDirectory(rawConfigDir);\n logger.verbose('Resolved config directory');\n\n let rawFileConfig: object = {};\n let discoveredConfigDirs: string[] = [];\n let resolvedConfigDirs: string[] = [];\n\n // Check if hierarchical configuration discovery is enabled\n // Use optional chaining for safety although options.features is defaulted\n if (options.features && options.features.includes('hierarchical')) {\n logger.verbose('Hierarchical configuration discovery enabled');\n\n try {\n // Extract the config directory name from the path for hierarchical discovery\n const configDirName = path.basename(resolvedConfigDir);\n const startingDir = path.dirname(resolvedConfigDir);\n\n logger.debug(`Using hierarchical discovery: configDirName=${configDirName}, startingDir=${startingDir}`);\n\n const hierarchicalResult = await loadHierarchicalConfig({\n configDirName,\n configFileName: options.defaults.configFile,\n startingDir,\n encoding: options.defaults.encoding,\n logger,\n pathFields: options.defaults.pathResolution?.pathFields,\n resolvePathArray: options.defaults.pathResolution?.resolvePathArray,\n fieldOverlaps: options.defaults.fieldOverlaps\n });\n\n rawFileConfig = hierarchicalResult.config;\n discoveredConfigDirs = hierarchicalResult.discoveredDirs.map(dir => dir.path);\n resolvedConfigDirs = hierarchicalResult.resolvedConfigDirs.map(dir => dir.path);\n\n if (hierarchicalResult.discoveredDirs.length > 0) {\n logger.verbose(`Hierarchical discovery found ${hierarchicalResult.discoveredDirs.length} configuration directories`);\n hierarchicalResult.discoveredDirs.forEach(dir => {\n logger.debug(` Level ${dir.level}: ${dir.path}`);\n });\n } else {\n logger.verbose('No configuration directories found in hierarchy');\n }\n\n if (hierarchicalResult.resolvedConfigDirs.length > 0) {\n logger.verbose(`Found ${hierarchicalResult.resolvedConfigDirs.length} directories with actual configuration files`);\n hierarchicalResult.resolvedConfigDirs.forEach(dir => {\n logger.debug(` Config dir level ${dir.level}: ${dir.path}`);\n });\n }\n\n if (hierarchicalResult.errors.length > 0) {\n hierarchicalResult.errors.forEach(error => logger.warn(`Hierarchical config warning: ${error}`));\n }\n\n } catch (error: any) {\n logger.error('Hierarchical configuration loading failed: ' + (error.message || 'Unknown error'));\n // Fall back to single directory mode\n logger.verbose('Falling back to single directory configuration loading');\n rawFileConfig = await loadSingleDirectoryConfig(resolvedConfigDir, options, logger);\n\n // Include the directory in both arrays (discovered but check if it had config)\n discoveredConfigDirs = [resolvedConfigDir];\n if (rawFileConfig && Object.keys(rawFileConfig).length > 0) {\n resolvedConfigDirs = [resolvedConfigDir];\n } else {\n resolvedConfigDirs = [];\n }\n }\n } else {\n // Use traditional single directory configuration loading\n logger.verbose('Using single directory configuration loading');\n rawFileConfig = await loadSingleDirectoryConfig(resolvedConfigDir, options, logger);\n\n // Include the directory in discovered, and in resolved only if it had config\n discoveredConfigDirs = [resolvedConfigDir];\n if (rawFileConfig && Object.keys(rawFileConfig).length > 0) {\n resolvedConfigDirs = [resolvedConfigDir];\n } else {\n resolvedConfigDirs = [];\n }\n }\n\n // Apply path resolution if configured\n let processedConfig = rawFileConfig;\n if (options.defaults.pathResolution?.pathFields) {\n processedConfig = resolveConfigPaths(\n rawFileConfig,\n resolvedConfigDir,\n options.defaults.pathResolution.pathFields,\n options.defaults.pathResolution.resolvePathArray || []\n );\n }\n\n const config: z.infer<ZodObject<T & typeof ConfigSchema.shape>> = clean({\n ...processedConfig,\n ...{\n configDirectory: resolvedConfigDir,\n discoveredConfigDirs,\n resolvedConfigDirs,\n }\n }) as z.infer<ZodObject<T & typeof ConfigSchema.shape>>;\n\n return config;\n}\n\n/**\n * Tries to find a config file with alternative extensions (.yaml or .yml).\n * \n * @param storage Storage instance to use for file operations\n * @param configDir The directory containing the config file\n * @param configFileName The base config file name (may have .yaml or .yml extension)\n * @param logger Logger for debugging\n * @returns Promise resolving to the found config file path or null if not found\n */\nasync function findConfigFileWithExtension(\n storage: any,\n configDir: string,\n configFileName: string,\n logger: any\n): Promise<string | null> {\n // Validate the config file name to prevent path traversal\n const configFilePath = validatePath(configFileName, configDir);\n \n // First try the exact filename as specified\n const exists = await storage.exists(configFilePath);\n if (exists) {\n const isReadable = await storage.isFileReadable(configFilePath);\n if (isReadable) {\n return configFilePath;\n }\n }\n \n // If the exact filename doesn't exist or isn't readable, try alternative extensions\n // Only do this if the filename has a .yaml or .yml extension\n const ext = path.extname(configFileName);\n if (ext === '.yaml' || ext === '.yml') {\n const baseName = path.basename(configFileName, ext);\n const alternativeExt = ext === '.yaml' ? '.yml' : '.yaml';\n const alternativeFileName = baseName + alternativeExt;\n const alternativePath = validatePath(alternativeFileName, configDir);\n \n logger.debug(`Config file not found at ${configFilePath}, trying alternative: ${alternativePath}`);\n \n const altExists = await storage.exists(alternativePath);\n if (altExists) {\n const altIsReadable = await storage.isFileReadable(alternativePath);\n if (altIsReadable) {\n logger.debug(`Found config file with alternative extension: ${alternativePath}`);\n return alternativePath;\n }\n }\n }\n \n return null;\n}\n\n/**\n * Loads configuration from a single directory (traditional mode).\n * \n * @param resolvedConfigDir - The resolved configuration directory path\n * @param options - Cardigantime options\n * @param logger - Logger instance\n * @returns Promise resolving to the configuration object\n */\nasync function loadSingleDirectoryConfig<T extends z.ZodRawShape>(\n resolvedConfigDir: string,\n options: Options<T>,\n logger: any\n): Promise<object> {\n const storage = Storage.create({ log: logger.debug });\n logger.verbose('Attempting to load config file for cardigantime');\n\n let rawFileConfig: object = {};\n\n try {\n // Try to find the config file with alternative extensions\n const configFilePath = await findConfigFileWithExtension(\n storage,\n resolvedConfigDir,\n options.defaults.configFile,\n logger\n );\n \n if (!configFilePath) {\n logger.verbose('Configuration file not found. Using empty configuration.');\n return rawFileConfig;\n }\n\n const yamlContent = await storage.readFile(configFilePath, options.defaults.encoding);\n\n // SECURITY FIX: Use safer parsing options to prevent code execution vulnerabilities\n const parsedYaml = yaml.load(yamlContent);\n\n if (parsedYaml !== null && typeof parsedYaml === 'object') {\n rawFileConfig = parsedYaml;\n logger.verbose('Loaded configuration file successfully');\n } else if (parsedYaml !== null) {\n logger.warn('Ignoring invalid configuration format. Expected an object, got ' + typeof parsedYaml);\n }\n } catch (error: any) {\n // Re-throw security-related errors (path validation failures)\n if (error.message && /Invalid path|path traversal|absolute path/i.test(error.message)) {\n throw error;\n }\n \n if (error.code === 'ENOENT' || /not found|no such file/i.test(error.message)) {\n logger.verbose('Configuration file not found. Using empty configuration.');\n } else {\n // SECURITY FIX: Don't expose internal paths or detailed error information\n logger.error('Failed to load or parse configuration file: ' + (error.message || 'Unknown error'));\n }\n }\n\n return rawFileConfig;\n}\n\n/**\n * Represents a configuration value with its source information.\n */\ninterface ConfigSourceInfo {\n /** The configuration value */\n value: any;\n /** Path to the configuration file that provided this value */\n sourcePath: string;\n /** Hierarchical level (0 = closest/highest precedence) */\n level: number;\n /** Short description of the source for display */\n sourceLabel: string;\n}\n\n/**\n * Tracks configuration values to their sources during hierarchical loading.\n */\ninterface ConfigSourceTracker {\n [key: string]: ConfigSourceInfo;\n}\n\n/**\n * Recursively tracks the source of configuration values from hierarchical loading.\n * \n * @param config - The configuration object to track\n * @param sourcePath - Path to the configuration file\n * @param level - Hierarchical level\n * @param prefix - Current object path prefix for nested values\n * @param tracker - The tracker object to populate\n */\nfunction trackConfigSources(\n config: any,\n sourcePath: string,\n level: number,\n prefix: string = '',\n tracker: ConfigSourceTracker = {}\n): ConfigSourceTracker {\n if (!config || typeof config !== 'object' || Array.isArray(config)) {\n // For primitives and arrays, track the entire value\n tracker[prefix] = {\n value: config,\n sourcePath,\n level,\n sourceLabel: `Level ${level}: ${path.basename(path.dirname(sourcePath))}`\n };\n return tracker;\n }\n\n // For objects, recursively track each property\n for (const [key, value] of Object.entries(config)) {\n const fieldPath = prefix ? `${prefix}.${key}` : key;\n trackConfigSources(value, sourcePath, level, fieldPath, tracker);\n }\n\n return tracker;\n}\n\n/**\n * Merges multiple configuration source trackers with proper precedence.\n * Lower level numbers have higher precedence.\n * \n * @param trackers - Array of trackers from different config sources\n * @returns Merged tracker with proper precedence\n */\nfunction mergeConfigTrackers(trackers: ConfigSourceTracker[]): ConfigSourceTracker {\n const merged: ConfigSourceTracker = {};\n\n for (const tracker of trackers) {\n for (const [key, info] of Object.entries(tracker)) {\n // Only update if we don't have this key yet, or if this source has higher precedence (lower level)\n if (!merged[key] || info.level < merged[key].level) {\n merged[key] = info;\n }\n }\n }\n\n return merged;\n}\n\n/**\n * Formats a configuration value for display, handling different types appropriately.\n * \n * @param value - The configuration value to format\n * @returns Formatted string representation\n */\nfunction formatConfigValue(value: any): string {\n if (value === null) return 'null';\n if (value === undefined) return 'undefined';\n if (typeof value === 'string') return `\"${value}\"`;\n if (typeof value === 'boolean') return value.toString();\n if (typeof value === 'number') return value.toString();\n if (Array.isArray(value)) {\n if (value.length === 0) return '[]';\n if (value.length <= 3) {\n return `[${value.map(formatConfigValue).join(', ')}]`;\n }\n return `[${value.slice(0, 2).map(formatConfigValue).join(', ')}, ... (${value.length} items)]`;\n }\n if (typeof value === 'object') {\n const keys = Object.keys(value);\n if (keys.length === 0) return '{}';\n if (keys.length <= 2) {\n return `{${keys.slice(0, 2).join(', ')}}`;\n }\n return `{${keys.slice(0, 2).join(', ')}, ... (${keys.length} keys)}`;\n }\n return String(value);\n}\n\n/**\n * Displays configuration with source tracking in a git blame-like format.\n * \n * @param config - The resolved configuration object\n * @param tracker - Configuration source tracker\n * @param discoveredDirs - Array of discovered configuration directories\n * @param logger - Logger instance for output\n */\nfunction displayConfigWithSources(\n config: any,\n tracker: ConfigSourceTracker,\n discoveredDirs: DiscoveredConfigDir[],\n logger: any\n): void {\n logger.info('\\n' + '='.repeat(80));\n logger.info('CONFIGURATION SOURCE ANALYSIS');\n logger.info('='.repeat(80));\n\n // Display discovered configuration hierarchy\n logger.info('\\nDISCOVERED CONFIGURATION HIERARCHY:');\n if (discoveredDirs.length === 0) {\n logger.info(' No configuration directories found in hierarchy');\n } else {\n discoveredDirs\n .sort((a, b) => a.level - b.level) // Sort by precedence (lower level = higher precedence)\n .forEach(dir => {\n const precedence = dir.level === 0 ? '(highest precedence)' :\n dir.level === Math.max(...discoveredDirs.map(d => d.level)) ? '(lowest precedence)' :\n '';\n logger.info(` Level ${dir.level}: ${dir.path} ${precedence}`);\n });\n }\n\n // Display resolved configuration with sources\n logger.info('\\nRESOLVED CONFIGURATION WITH SOURCES:');\n logger.info('Format: [Source] key: value\\n');\n\n const sortedKeys = Object.keys(tracker).sort();\n const maxKeyLength = Math.max(...sortedKeys.map(k => k.length), 20);\n const maxSourceLength = Math.max(...Object.values(tracker).map(info => info.sourceLabel.length), 25);\n\n for (const key of sortedKeys) {\n const info = tracker[key];\n const paddedKey = key.padEnd(maxKeyLength);\n const paddedSource = info.sourceLabel.padEnd(maxSourceLength);\n const formattedValue = formatConfigValue(info.value);\n\n logger.info(`[${paddedSource}] ${paddedKey}: ${formattedValue}`);\n }\n\n // Display summary\n logger.info('\\n' + '-'.repeat(80));\n logger.info('SUMMARY:');\n logger.info(` Total configuration keys: ${Object.keys(tracker).length}`);\n logger.info(` Configuration sources: ${discoveredDirs.length}`);\n\n // Count values by source\n const sourceCount: { [source: string]: number } = {};\n for (const info of Object.values(tracker)) {\n sourceCount[info.sourceLabel] = (sourceCount[info.sourceLabel] || 0) + 1;\n }\n\n logger.info(' Values by source:');\n for (const [source, count] of Object.entries(sourceCount)) {\n logger.info(` ${source}: ${count} value(s)`);\n }\n\n logger.info('='.repeat(80));\n}\n\n/**\n * Checks and displays the resolved configuration with detailed source tracking.\n * \n * This function provides a git blame-like view of configuration resolution,\n * showing which file and hierarchical level contributed each configuration value.\n * \n * @template T - The Zod schema shape type for configuration validation\n * @param args - Parsed command-line arguments\n * @param options - Cardigantime options with defaults, schema, and logger\n * @returns Promise that resolves when the configuration check is complete\n * \n * @example\n * ```typescript\n * await checkConfig(cliArgs, {\n * defaults: { configDirectory: './config', configFile: 'app.yaml' },\n * configShape: MySchema.shape,\n * logger: console,\n * features: ['config', 'hierarchical']\n * });\n * // Outputs detailed configuration source analysis\n * ```\n */\nexport const checkConfig = async <T extends z.ZodRawShape>(\n args: Args,\n options: Options<T>\n): Promise<void> => {\n const logger = options.logger;\n\n logger.info('Starting configuration check...');\n\n const rawConfigDir = args.configDirectory || options.defaults?.configDirectory;\n if (!rawConfigDir) {\n throw new Error('Configuration directory must be specified');\n }\n\n const resolvedConfigDir = validateConfigDirectory(rawConfigDir);\n logger.verbose(`Resolved config directory: ${resolvedConfigDir}`);\n\n let rawFileConfig: object = {};\n let discoveredDirs: DiscoveredConfigDir[] = [];\n let resolvedConfigDirs: DiscoveredConfigDir[] = [];\n let tracker: ConfigSourceTracker = {};\n\n // Check if hierarchical configuration discovery is enabled\n // Use optional chaining for safety although options.features is defaulted\n if (options.features && options.features.includes('hierarchical')) {\n logger.verbose('Using hierarchical configuration discovery for source tracking');\n\n try {\n // Extract the config directory name from the path for hierarchical discovery\n const configDirName = path.basename(resolvedConfigDir);\n const startingDir = path.dirname(resolvedConfigDir);\n\n logger.debug(`Using hierarchical discovery: configDirName=${configDirName}, startingDir=${startingDir}`);\n\n const hierarchicalResult = await loadHierarchicalConfig({\n configDirName,\n configFileName: options.defaults.configFile,\n startingDir,\n encoding: options.defaults.encoding,\n logger,\n pathFields: options.defaults.pathResolution?.pathFields,\n resolvePathArray: options.defaults.pathResolution?.resolvePathArray,\n fieldOverlaps: options.defaults.fieldOverlaps\n });\n\n rawFileConfig = hierarchicalResult.config;\n discoveredDirs = hierarchicalResult.discoveredDirs;\n resolvedConfigDirs = hierarchicalResult.resolvedConfigDirs;\n\n // Build detailed source tracking by re-loading each config individually\n const trackers: ConfigSourceTracker[] = [];\n\n // Sort by level (highest level first = lowest precedence first) to match merge order\n const sortedDirs = [...resolvedConfigDirs].sort((a, b) => b.level - a.level);\n\n for (const dir of sortedDirs) {\n const storage = Storage.create({ log: logger.debug });\n const configFilePath = path.join(dir.path, options.defaults.configFile);\n\n try {\n const exists = await storage.exists(configFilePath);\n if (!exists) continue;\n\n const isReadable = await storage.isFileReadable(configFilePath);\n if (!isReadable) continue;\n\n const yamlContent = await storage.readFile(configFilePath, options.defaults.encoding);\n const parsedYaml = yaml.load(yamlContent);\n\n if (parsedYaml !== null && typeof parsedYaml === 'object') {\n const levelTracker = trackConfigSources(parsedYaml, configFilePath, dir.level);\n trackers.push(levelTracker);\n }\n } catch (error: any) {\n logger.debug(`Error loading config for source tracking from ${configFilePath}: ${error.message}`);\n }\n }\n\n // Merge trackers with proper precedence\n tracker = mergeConfigTrackers(trackers);\n\n if (hierarchicalResult.errors.length > 0) {\n logger.warn('Configuration loading warnings:');\n hierarchicalResult.errors.forEach(error => logger.warn(` ${error}`));\n }\n\n } catch (error: any) {\n logger.error('Hierarchical configuration loading failed: ' + (error.message || 'Unknown error'));\n logger.verbose('Falling back to single directory configuration loading');\n\n // Fall back to single directory mode for source tracking\n rawFileConfig = await loadSingleDirectoryConfig(resolvedConfigDir, options, logger);\n const configFilePath = path.join(resolvedConfigDir, options.defaults.configFile);\n tracker = trackConfigSources(rawFileConfig, configFilePath, 0);\n\n // Include the directory in discovered, and in resolved only if it had config\n discoveredDirs = [{\n path: resolvedConfigDir,\n level: 0\n }];\n if (rawFileConfig && Object.keys(rawFileConfig).length > 0) {\n resolvedConfigDirs = [{\n path: resolvedConfigDir,\n level: 0\n }];\n } else {\n resolvedConfigDirs = [];\n }\n }\n } else {\n // Use traditional single directory configuration loading\n logger.verbose('Using single directory configuration loading for source tracking');\n rawFileConfig = await loadSingleDirectoryConfig(resolvedConfigDir, options, logger);\n const configFilePath = path.join(resolvedConfigDir, options.defaults.configFile);\n tracker = trackConfigSources(rawFileConfig, configFilePath, 0);\n\n // Include the directory in discovered, and in resolved only if it had config\n discoveredDirs = [{\n path: resolvedConfigDir,\n level: 0\n }];\n if (rawFileConfig && Object.keys(rawFileConfig).length > 0) {\n resolvedConfigDirs = [{\n path: resolvedConfigDir,\n level: 0\n }];\n } else {\n resolvedConfigDirs = [];\n }\n }\n\n // Apply path resolution if configured (this doesn't change source tracking)\n let processedConfig = rawFileConfig;\n if (options.defaults.pathResolution?.pathFields) {\n processedConfig = resolveConfigPaths(\n rawFileConfig,\n resolvedConfigDir,\n options.defaults.pathResolution.pathFields,\n options.defaults.pathResolution.resolvePathArray || []\n );\n }\n\n // Build final configuration including built-in values\n const finalConfig = clean({\n ...processedConfig,\n configDirectory: resolvedConfigDir,\n discoveredConfigDirs: discoveredDirs.map(dir => dir.path),\n resolvedConfigDirs: resolvedConfigDirs.map(dir => dir.path),\n });\n\n // Add built-in configuration to tracker\n tracker['configDirectory'] = {\n value: resolvedConfigDir,\n sourcePath: 'built-in',\n level: -1,\n sourceLabel: 'Built-in (runtime)'\n };\n\n tracker['discoveredConfigDirs'] = {\n value: discoveredDirs.map(dir => dir.path),\n sourcePath: 'built-in',\n level: -1,\n sourceLabel: 'Built-in (runtime)'\n };\n\n tracker['resolvedConfigDirs'] = {\n value: resolvedConfigDirs.map(dir => dir.path),\n sourcePath: 'built-in',\n level: -1,\n sourceLabel: 'Built-in (runtime)'\n };\n\n // Display the configuration with source information\n displayConfigWithSources(finalConfig, tracker, discoveredDirs, logger);\n};","/**\n * Error thrown when configuration validation fails\n */\nexport class ConfigurationError extends Error {\n public readonly errorType: 'validation' | 'schema' | 'extra_keys';\n public readonly details?: any;\n public readonly configPath?: string;\n\n constructor(\n errorType: 'validation' | 'schema' | 'extra_keys',\n message: string,\n details?: any,\n configPath?: string\n ) {\n super(message);\n this.name = 'ConfigurationError';\n this.errorType = errorType;\n this.details = details;\n this.configPath = configPath;\n }\n\n /**\n * Creates a validation error for when config doesn't match the schema\n */\n static validation(message: string, zodError?: any, configPath?: string): ConfigurationError {\n return new ConfigurationError('validation', message, zodError, configPath);\n }\n\n /**\n * Creates an error for when extra/unknown keys are found\n */\n static extraKeys(extraKeys: string[], allowedKeys: string[], configPath?: string): ConfigurationError {\n const message = `Unknown configuration keys found: ${extraKeys.join(', ')}. Allowed keys are: ${allowedKeys.join(', ')}`;\n return new ConfigurationError('extra_keys', message, { extraKeys, allowedKeys }, configPath);\n }\n\n /**\n * Creates a schema error for when the configuration schema itself is invalid\n */\n static schema(message: string, details?: any): ConfigurationError {\n return new ConfigurationError('schema', message, details);\n }\n} ","import { Command } from \"commander\";\nimport { ZodObject } from \"zod\";\n\nimport { z } from \"zod\";\nimport { SecurityValidationConfig } from \"./security/types\";\n\n// Re-export MCP types for convenience\nexport type {\n MCPConfigSource,\n FileConfigSource,\n ConfigSource,\n ResolvedConfig,\n MCPInvocationContext,\n} from \"./mcp/types\";\n\n/**\n * Available features that can be enabled in Cardigantime.\n * Currently supports:\n * - 'config': Configuration file reading and validation\n * - 'hierarchical': Hierarchical configuration discovery and layering\n */\nexport type Feature = 'config' | 'hierarchical';\n\n/**\n * Supported configuration file formats.\n * \n * - 'yaml': YAML format (.yaml, .yml)\n * - 'json': JSON format (.json)\n * - 'javascript': JavaScript module (.js, .mjs, .cjs)\n * - 'typescript': TypeScript module (.ts, .mts, .cts)\n */\nexport enum ConfigFormat {\n YAML = 'yaml',\n JSON = 'json',\n JavaScript = 'javascript',\n TypeScript = 'typescript'\n}\n\n/**\n * Interface for format-specific configuration parsers.\n * Each parser is responsible for loading and parsing configuration from a specific format.\n * \n * @template T - The type of the parsed configuration object\n */\nexport interface ConfigParser<T = unknown> {\n /** The format this parser handles */\n format: ConfigFormat;\n /** File extensions this parser supports (e.g., ['.yaml', '.yml']) */\n extensions: string[];\n /** \n * Parses configuration content from a file.\n * \n * @param content - The raw file content as a string\n * @param filePath - The absolute path to the configuration file\n * @returns Promise resolving to the parsed configuration object\n * @throws {Error} When parsing fails or content is invalid\n */\n parse(content: string, filePath: string): Promise<T>;\n}\n\n/**\n * Metadata about where a configuration value came from.\n * Used for tracking configuration sources and debugging.\n * \n * @deprecated Use FileConfigSource from ./mcp/types instead.\n * This type is kept for backward compatibility and will be removed in a future version.\n */\nexport interface LegacyConfigSource {\n /** The format of the configuration file */\n format: ConfigFormat;\n /** Absolute path to the configuration file */\n filePath: string;\n /** The parsed configuration content */\n content: unknown;\n /** Timestamp when the configuration was loaded */\n loadedAt: Date;\n}\n\n/**\n * Defines how array fields should be merged in hierarchical configurations.\n * \n * - 'override': Higher precedence arrays completely replace lower precedence arrays (default)\n * - 'append': Higher precedence array elements are appended to lower precedence arrays\n * - 'prepend': Higher precedence array elements are prepended to lower precedence arrays\n */\nexport type ArrayOverlapMode = 'override' | 'append' | 'prepend';\n\n/**\n * Configuration for how fields should be merged in hierarchical configurations.\n * Maps field names (using dot notation) to their overlap behavior.\n * \n * @example\n * ```typescript\n * const fieldOverlaps: FieldOverlapOptions = {\n * 'features': 'append', // features arrays will be combined by appending\n * 'api.endpoints': 'prepend', // nested endpoint arrays will be combined by prepending\n * 'excludePatterns': 'override' // excludePatterns arrays will replace each other (default behavior)\n * };\n * ```\n */\nexport interface FieldOverlapOptions {\n [fieldPath: string]: ArrayOverlapMode;\n}\n\n/**\n * Configuration for resolving relative paths in configuration values.\n * Paths specified in these fields will be resolved relative to the configuration file's directory.\n */\nexport interface PathResolutionOptions {\n /** Array of field names (using dot notation) that contain paths to be resolved */\n pathFields?: string[];\n /** Array of field names whose array elements should all be resolved as paths */\n resolvePathArray?: string[];\n}\n\n/**\n * Default configuration options for Cardigantime.\n * These define the basic behavior of configuration loading.\n */\nexport interface DefaultOptions {\n /** Directory path where configuration files are located */\n configDirectory: string;\n /** Name of the configuration file (e.g., 'config.yaml', 'app.yml') */\n configFile: string;\n /** Whether the configuration directory must exist. If true, throws error if directory doesn't exist */\n isRequired: boolean;\n /** File encoding for reading configuration files (e.g., 'utf8', 'ascii') */\n encoding: string;\n /** Configuration for resolving relative paths in configuration values */\n pathResolution?: PathResolutionOptions;\n /** \n * Configuration for how array fields should be merged in hierarchical mode.\n * Only applies when the 'hierarchical' feature is enabled.\n * If not specified, all arrays use 'override' behavior (default).\n */\n fieldOverlaps?: FieldOverlapOptions;\n /** \n * Security validation configuration (optional, uses development profile by default).\n * Enable security features to validate CLI arguments and config file values.\n */\n security?: Partial<SecurityValidationConfig>;\n /**\n * Optional source metadata for tracking where configuration came from.\n * Populated automatically when configuration is loaded.\n * \n * @deprecated Use the new ConfigSource union type from ./mcp/types instead.\n */\n source?: LegacyConfigSource;\n /**\n * Allow executable configuration files (JavaScript/TypeScript).\n * \n * **SECURITY WARNING**: Executable configs run with full Node.js permissions\n * in the same process as your application. Only enable this if you trust\n * the configuration files being loaded.\n * \n * When disabled (default), JavaScript and TypeScript config files will be\n * ignored with a warning message.\n * \n * @default false\n */\n allowExecutableConfig?: boolean;\n}\n\n/**\n * Complete options object passed to Cardigantime functions.\n * Combines defaults, features, schema shape, and logger.\n * \n * @template T - The Zod schema shape type for configuration validation\n */\nexport interface Options<T extends z.ZodRawShape> {\n /** Default configuration options */\n defaults: DefaultOptions,\n /** Array of enabled features */\n features: Feature[],\n /** Zod schema shape for validating user configuration */\n configShape: T;\n /** Logger instance for debugging and error reporting */\n logger: Logger;\n}\n\n/**\n * Logger interface for Cardigantime's internal logging.\n * Compatible with popular logging libraries like Winston, Bunyan, etc.\n */\nexport interface Logger {\n /** Debug-level logging for detailed troubleshooting information */\n debug: (message: string, ...args: any[]) => void;\n /** Info-level logging for general information */\n info: (message: string, ...args: any[]) => void;\n /** Warning-level logging for non-critical issues */\n warn: (message: string, ...args: any[]) => void;\n /** Error-level logging for critical problems */\n error: (message: string, ...args: any[]) => void;\n /** Verbose-level logging for extensive detail */\n verbose: (message: string, ...args: any[]) => void;\n /** Silly-level logging for maximum detail */\n silly: (message: string, ...args: any[]) => void;\n}\n\n/**\n * Main Cardigantime interface providing configuration management functionality.\n * \n * @template T - The Zod schema shape type for configuration validation\n */\nexport interface Cardigantime<T extends z.ZodRawShape> {\n /** \n * Adds Cardigantime's CLI options to a Commander.js command.\n * This includes options like --config-directory for runtime config path overrides.\n */\n configure: (command: Command) => Promise<Command>;\n /** Sets a custom logger for debugging and error reporting */\n setLogger: (logger: Logger) => void;\n /** \n * Reads configuration from files and merges with CLI arguments.\n * Returns a fully typed configuration object.\n */\n read: (args: Args) => Promise<z.infer<ZodObject<T & typeof ConfigSchema.shape>>>;\n /** \n * Validates the merged configuration against the Zod schema.\n * Throws ConfigurationError if validation fails.\n */\n validate: (config: z.infer<ZodObject<T & typeof ConfigSchema.shape>>) => Promise<void>;\n /** \n * Generates a configuration file with default values in the specified directory.\n * Creates the directory if it doesn't exist and writes a config file with all default values populated.\n */\n generateConfig: (configDirectory?: string) => Promise<void>;\n /** \n * Checks and displays the resolved configuration with detailed source tracking.\n * Shows which file and hierarchical level contributed each configuration value in a git blame-like format.\n */\n checkConfig: (args: Args) => Promise<void>;\n}\n\n/**\n * Parsed command-line arguments object, typically from Commander.js opts().\n * Keys correspond to CLI option names with values from user input.\n */\nexport interface Args {\n [key: string]: any;\n}\n\n/**\n * Base Zod schema for core Cardigantime configuration.\n * Contains the minimum required configuration fields.\n */\nexport const ConfigSchema = z.object({\n /** The resolved configuration directory path */\n configDirectory: z.string(),\n /** Array of all directory paths that were discovered during hierarchical search */\n discoveredConfigDirs: z.array(z.string()),\n /** Array of directory paths that actually contained valid configuration files */\n resolvedConfigDirs: z.array(z.string()),\n});\n\n/**\n * Base configuration type derived from the core schema.\n */\nexport type Config = z.infer<typeof ConfigSchema>;\n\n// ============================================================================\n// Configuration Discovery Types\n// ============================================================================\n\n/**\n * Defines a configuration file naming pattern.\n * Used to discover configuration files in various standard locations.\n * \n * Patterns support placeholders:\n * - `{app}` - The application name (e.g., 'protokoll', 'myapp')\n * - `{ext}` - The file extension (e.g., 'yaml', 'json', 'ts')\n * \n * @example\n * ```typescript\n * // Pattern: \"{app}.config.{ext}\" with app=\"myapp\" and ext=\"yaml\"\n * // Results in: \"myapp.config.yaml\"\n * \n * const pattern: ConfigNamingPattern = {\n * pattern: '{app}.config.{ext}',\n * priority: 1,\n * hidden: false\n * };\n * ```\n */\nexport interface ConfigNamingPattern {\n /**\n * Pattern template with `{app}` and `{ext}` placeholders.\n * \n * Examples:\n * - `\"{app}.config.{ext}\"` → `\"protokoll.config.yaml\"`\n * - `\".{app}/config.{ext}\"` → `\".protokoll/config.yaml\"`\n * - `\".{app}rc.{ext}\"` → `\".protokollrc.json\"`\n * - `\".{app}rc\"` → `\".protokollrc\"` (no extension)\n */\n pattern: string;\n\n /**\n * Search priority (lower number = checked first).\n * When multiple config files exist, lower priority patterns take precedence.\n */\n priority: number;\n\n /**\n * Whether this pattern results in a hidden file or directory.\n * Hidden patterns start with a dot (e.g., `.myapp/`, `.myapprc`).\n */\n hidden: boolean;\n}\n\n/**\n * Options for configuring how configuration files are discovered.\n * \n * @example\n * ```typescript\n * const options: ConfigDiscoveryOptions = {\n * appName: 'myapp',\n * extensions: ['yaml', 'yml', 'json'],\n * searchHidden: true,\n * // Use custom patterns instead of defaults\n * patterns: [\n * { pattern: '{app}.config.{ext}', priority: 1, hidden: false }\n * ]\n * };\n * ```\n */\nexport interface ConfigDiscoveryOptions {\n /**\n * The application name used in pattern expansion.\n * This value replaces `{app}` placeholders in naming patterns.\n */\n appName: string;\n\n /**\n * Custom naming patterns to use for discovery.\n * If not provided, uses the standard patterns defined in STANDARD_PATTERNS.\n */\n patterns?: ConfigNamingPattern[];\n\n /**\n * File extensions to search for.\n * These replace the `{ext}` placeholder in patterns.\n * If not provided, defaults to supported format extensions.\n * \n * @example ['yaml', 'yml', 'json', 'js', 'ts']\n */\n extensions?: string[];\n\n /**\n * Whether to search for hidden files and directories.\n * When false, patterns with `hidden: true` are skipped.\n * \n * @default true\n */\n searchHidden?: boolean;\n\n /**\n * Whether to check for multiple config files and emit a warning.\n * When enabled, discovery continues after finding the first match\n * to detect and warn about additional config files that would be ignored.\n * \n * @default true\n */\n warnOnMultipleConfigs?: boolean;\n}\n\n/**\n * Result of discovering a configuration file.\n * Contains the file path and the pattern that matched.\n */\nexport interface DiscoveredConfig {\n /**\n * The resolved file path to the configuration file.\n * Can be a file path (e.g., 'app.config.yaml') or include\n * a directory (e.g., '.app/config.yaml').\n */\n path: string;\n\n /**\n * The absolute path to the configuration file.\n */\n absolutePath: string;\n\n /**\n * The pattern that matched this configuration file.\n */\n pattern: ConfigNamingPattern;\n}\n\n/**\n * Warning information when multiple config files are found.\n * This helps users identify and remove unused config files.\n */\nexport interface MultipleConfigWarning {\n /**\n * The configuration that will be used (highest priority).\n */\n used: DiscoveredConfig;\n\n /**\n * Configurations that were found but will be ignored.\n */\n ignored: DiscoveredConfig[];\n}\n\n/**\n * Full result of configuration discovery, including warnings.\n */\nexport interface DiscoveryResult {\n /**\n * The discovered configuration file, or null if none found.\n */\n config: DiscoveredConfig | null;\n\n /**\n * Warning about multiple config files, if any were found.\n */\n multipleConfigWarning?: MultipleConfigWarning;\n}\n\n// ============================================================================\n// Hierarchical Configuration Types\n// ============================================================================\n\n/**\n * Controls how hierarchical configuration lookup behaves.\n * \n * - `'enabled'` - Walk up the directory tree and merge configs (default behavior).\n * Configurations from parent directories are merged with child configurations,\n * with child values taking precedence.\n * \n * - `'disabled'` - Use only the config found in the starting directory.\n * No parent directory traversal occurs. Useful for isolated projects or\n * MCP configurations that should be self-contained.\n * \n * - `'root-only'` - Walk up to find the first config, but don't merge with others.\n * This mode finds the \"closest\" config file without merging parent configs.\n * Useful when you want automatic config discovery but not inheritance.\n * \n * - `'explicit'` - Only merge configs that are explicitly referenced.\n * The base config can specify which parent configs to extend via an\n * `extends` field. No automatic directory traversal.\n * \n * @example\n * ```typescript\n * // In a child config that wants to be isolated:\n * // protokoll.config.yaml\n * hierarchical:\n * mode: disabled\n * \n * // This config will NOT inherit from parent directories\n * ```\n */\nexport type HierarchicalMode = 'enabled' | 'disabled' | 'root-only' | 'explicit';\n\n/**\n * Files or directories that indicate a project root.\n * When encountered during directory traversal, hierarchical lookup stops.\n * \n * @example\n * ```typescript\n * const markers: RootMarker[] = [\n * { type: 'file', name: 'package.json' },\n * { type: 'directory', name: '.git' },\n * { type: 'file', name: 'pnpm-workspace.yaml' },\n * ];\n * ```\n */\nexport interface RootMarker {\n /** Type of the marker */\n type: 'file' | 'directory';\n /** Name of the file or directory that indicates a root */\n name: string;\n}\n\n/**\n * Default root markers used when none are specified.\n * These indicate common project root boundaries.\n */\nexport const DEFAULT_ROOT_MARKERS: RootMarker[] = [\n { type: 'file', name: 'package.json' },\n { type: 'directory', name: '.git' },\n { type: 'file', name: 'pnpm-workspace.yaml' },\n { type: 'file', name: 'lerna.json' },\n { type: 'file', name: 'nx.json' },\n { type: 'file', name: 'rush.json' },\n];\n\n/**\n * Configuration options for hierarchical config behavior.\n * Can be set in the configuration file or programmatically.\n * \n * @example\n * ```typescript\n * // Configuration file (protokoll.config.yaml):\n * hierarchical:\n * mode: enabled\n * maxDepth: 5\n * stopAt:\n * - node_modules\n * - vendor\n * rootMarkers:\n * - type: file\n * name: package.json\n * ```\n * \n * @example\n * ```typescript\n * // Programmatic configuration:\n * const options: HierarchicalOptions = {\n * mode: 'disabled', // No parent config merging\n * };\n * \n * // For MCP servers:\n * const mcpOptions: HierarchicalOptions = {\n * mode: 'root-only',\n * rootMarkers: [{ type: 'file', name: 'mcp.json' }],\n * };\n * ```\n */\nexport interface HierarchicalOptions {\n /**\n * The hierarchical lookup mode.\n * Controls whether and how parent directories are searched.\n * \n * @default 'enabled'\n */\n mode?: HierarchicalMode;\n\n /**\n * Maximum number of parent directories to traverse.\n * Prevents unbounded traversal in deep directory structures.\n * \n * @default 10\n */\n maxDepth?: number;\n\n /**\n * Directory names where traversal should stop.\n * When a directory with one of these names is encountered as a parent,\n * traversal stops even if no config was found.\n * \n * @example ['node_modules', 'vendor', '.cache']\n */\n stopAt?: string[];\n\n /**\n * Files or directories that indicate a project root.\n * When a directory contains one of these markers, it's treated as a root\n * and traversal stops after processing that directory.\n * \n * If not specified, uses DEFAULT_ROOT_MARKERS.\n * Set to empty array to disable root marker detection.\n */\n rootMarkers?: RootMarker[];\n\n /**\n * Whether to stop at the first root marker found.\n * When true, traversal stops immediately when a root marker is found.\n * When false, the directory with the root marker is included but no further.\n * \n * @default true\n */\n stopAtRoot?: boolean;\n}\n\n// ============================================================================\n// Directory Traversal Security Types\n// ============================================================================\n\n/**\n * Defines security boundaries for directory traversal.\n * Used to prevent configuration lookup from accessing sensitive directories.\n * \n * @example\n * ```typescript\n * const boundaries: TraversalBoundary = {\n * forbidden: ['/etc', '/usr', '/var'],\n * boundaries: [process.env.HOME ?? '/home'],\n * maxAbsoluteDepth: 20,\n * maxRelativeDepth: 10,\n * };\n * ```\n */\nexport interface TraversalBoundary {\n /**\n * Directories that are never allowed to be accessed.\n * Traversal is blocked if the path is at or within these directories.\n * Paths can include environment variable placeholders like `$HOME`.\n * \n * @example ['/etc', '/usr', '/var', '/sys', '/proc', '$HOME/.ssh']\n */\n forbidden: string[];\n\n /**\n * Soft boundary directories - traversal stops at these unless explicitly allowed.\n * These represent natural project boundaries.\n * Paths can include environment variable placeholders like `$HOME`.\n * \n * @example ['$HOME', '/tmp', '/private/tmp']\n */\n boundaries: string[];\n\n /**\n * Maximum absolute depth from the filesystem root.\n * Prevents extremely deep traversal regardless of starting point.\n * Depth is counted as the number of path segments from root.\n * \n * @example 20 means paths like /a/b/c/.../t (20 levels deep) are allowed\n * @default 20\n */\n maxAbsoluteDepth: number;\n\n /**\n * Maximum relative depth from the starting directory.\n * Limits how far up the directory tree traversal can go.\n * \n * @example 10 means traversal can go up 10 directories from the start\n * @default 10\n */\n maxRelativeDepth: number;\n}\n\n/**\n * Result of a traversal boundary check.\n */\nexport interface TraversalCheckResult {\n /** Whether the path is allowed */\n allowed: boolean;\n \n /** Reason for blocking (if not allowed) */\n reason?: string;\n \n /** The boundary that was violated (if any) */\n violatedBoundary?: string;\n}\n\n/**\n * Options for configuring traversal security behavior.\n */\nexport interface TraversalSecurityOptions {\n /**\n * Custom traversal boundaries to use instead of defaults.\n */\n boundaries?: Partial<TraversalBoundary>;\n\n /**\n * Allow traversal beyond safe boundaries.\n * \n * **SECURITY WARNING**: Setting this to true bypasses security checks\n * and allows traversal into sensitive directories. Only use this in\n * trusted scenarios where you control all configuration files.\n * \n * @default false\n */\n allowUnsafeTraversal?: boolean;\n\n /**\n * Whether to log warnings when boundaries are overridden.\n * \n * @default true\n */\n warnOnOverride?: boolean;\n}\n","import { z, ZodObject } from \"zod\";\nimport { ArgumentError } from \"./error/ArgumentError\";\nimport { ConfigurationError } from \"./error/ConfigurationError\";\nimport { FileSystemError } from \"./error/FileSystemError\";\nimport { ConfigSchema, Logger, Options } from \"./types\";\nimport * as Storage from \"./util/storage\";\nexport { ArgumentError, ConfigurationError, FileSystemError };\n\n/**\n * Recursively extracts all keys from a Zod schema in dot notation.\n *\n * This function traverses a Zod schema structure and builds a flat list\n * of all possible keys, using dot notation for nested objects. It handles\n * optional/nullable types by unwrapping them and supports arrays by\n * introspecting their element type.\n *\n * Special handling for:\n * - ZodOptional/ZodNullable: Unwraps to get the underlying type\n * - ZodAny/ZodRecord: Accepts any keys, returns the prefix or empty array\n * - ZodArray: Introspects the element type\n * - ZodObject: Recursively processes all shape properties\n *\n * @param schema - The Zod schema to introspect\n * @param prefix - Internal parameter for building nested key paths\n * @returns Array of strings representing all possible keys in dot notation\n *\n * @example\n * ```typescript\n * const schema = z.object({\n * user: z.object({\n * name: z.string(),\n * settings: z.object({ theme: z.string() })\n * }),\n * debug: z.boolean()\n * });\n *\n * const keys = listZodKeys(schema);\n * // Returns: ['user.name', 'user.settings.theme', 'debug']\n * ```\n */\nexport const listZodKeys = (schema: z.ZodTypeAny, prefix = ''): string[] => {\n // Handle ZodOptional and ZodNullable - unwrap to get the underlying type\n if (schema instanceof z.ZodOptional || schema instanceof z.ZodNullable) {\n return listZodKeys(schema.unwrap() as z.ZodTypeAny, prefix);\n }\n\n // Handle ZodAny and ZodRecord - these accept any keys, so don't introspect\n if (schema instanceof z.ZodAny || schema instanceof z.ZodRecord) {\n return prefix ? [prefix] : [];\n }\n\n if (schema instanceof z.ZodArray) {\n return listZodKeys(schema.element as z.ZodTypeAny, prefix);\n }\n\n if (schema instanceof z.ZodObject) {\n return Object.entries(schema.shape).flatMap(([key, subschema]) => {\n const fullKey = prefix ? `${prefix}.${key}` : key;\n const nested = listZodKeys(subschema as z.ZodTypeAny, fullKey);\n return nested.length ? nested : fullKey;\n });\n }\n return [];\n}\n\n/**\n * Type guard to check if a value is a plain object (not array, null, or other types).\n *\n * @param value - The value to check\n * @returns True if the value is a plain object\n */\nconst isPlainObject = (value: unknown): value is Record<string, unknown> => {\n // Check if it's an object, not null, and not an array.\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n};\n\n/**\n * Generates a list of all keys within a JavaScript object, using dot notation for nested keys.\n * Mimics the behavior of listZodKeys but operates on plain objects.\n * For arrays, it inspects the first element that is a plain object to determine nested keys.\n * If an array contains no plain objects, or is empty, the key for the array itself is listed.\n *\n * @param obj The object to introspect.\n * @param prefix Internal use for recursion: the prefix for the current nesting level.\n * @returns An array of strings representing all keys in dot notation.\n */\nexport const listObjectKeys = (obj: Record<string, unknown>, prefix = ''): string[] => {\n const keys = new Set<string>(); // Use Set to automatically handle duplicates from array recursion\n\n for (const key in obj) {\n // Ensure it's an own property, not from the prototype chain\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n const value = obj[key];\n const fullKey = prefix ? `${prefix}.${key}` : key;\n\n if (Array.isArray(value)) {\n // Find the first element that is a plain object to determine structure\n const firstObjectElement = value.find(isPlainObject);\n if (firstObjectElement) {\n // Recurse into the structure of the first object element found\n const nestedKeys = listObjectKeys(firstObjectElement, fullKey);\n nestedKeys.forEach(k => keys.add(k));\n } else {\n // Array is empty or contains no plain objects, list the array key itself\n keys.add(fullKey);\n }\n } else if (isPlainObject(value)) {\n // Recurse into nested plain objects\n const nestedKeys = listObjectKeys(value, fullKey);\n nestedKeys.forEach(k => keys.add(k));\n } else {\n // It's a primitive, null, or other non-plain object/array type\n keys.add(fullKey);\n }\n }\n }\n return Array.from(keys); // Convert Set back to Array\n};\n\n/**\n * Validates that the configuration object contains only keys allowed by the schema.\n *\n * This function prevents configuration errors by detecting typos or extra keys\n * that aren't defined in the Zod schema. It intelligently handles:\n * - ZodRecord types that accept arbitrary keys\n * - Nested objects and their key structures\n * - Arrays and their element key structures\n *\n * The function throws a ConfigurationError if extra keys are found, providing\n * helpful information about what keys are allowed vs. what was found.\n *\n * @param mergedSources - The merged configuration object to validate\n * @param fullSchema - The complete Zod schema including base and user schemas\n * @param logger - Logger for error reporting\n * @throws {ConfigurationError} When extra keys are found that aren't in the schema\n *\n * @example\n * ```typescript\n * const schema = z.object({ name: z.string(), age: z.number() });\n * const config = { name: 'John', age: 30, typo: 'invalid' };\n *\n * checkForExtraKeys(config, schema, console);\n * // Throws: ConfigurationError with details about 'typo' being an extra key\n * ```\n */\nexport const checkForExtraKeys = (mergedSources: object, fullSchema: ZodObject<any>, logger: Logger | typeof console): void => {\n const allowedKeys = new Set(listZodKeys(fullSchema));\n const actualKeys = listObjectKeys(mergedSources as Record<string, unknown>);\n\n // Filter out keys that are under a record type (ZodRecord accepts any keys)\n const recordPrefixes = new Set<string>();\n\n // Find all prefixes that are ZodRecord types\n const findRecordPrefixes = (schema: z.ZodTypeAny, prefix = ''): void => {\n if (schema instanceof z.ZodOptional || schema instanceof z.ZodNullable) {\n findRecordPrefixes(schema.unwrap() as z.ZodTypeAny, prefix);\n return;\n }\n\n if (schema instanceof z.ZodAny || schema instanceof z.ZodRecord) {\n if (prefix) recordPrefixes.add(prefix);\n return;\n }\n\n if (schema instanceof z.ZodObject) {\n Object.entries(schema.shape).forEach(([key, subschema]) => {\n const fullKey = prefix ? `${prefix}.${key}` : key;\n findRecordPrefixes(subschema as z.ZodTypeAny, fullKey);\n });\n }\n };\n\n findRecordPrefixes(fullSchema);\n\n // Filter out keys that are under record prefixes\n const extraKeys = actualKeys.filter(key => {\n if (allowedKeys.has(key)) return false;\n\n // Check if this key is under a record prefix\n for (const recordPrefix of recordPrefixes) {\n if (key.startsWith(recordPrefix + '.')) {\n return false; // This key is allowed under a record\n }\n }\n\n return true; // This is an extra key\n });\n\n if (extraKeys.length > 0) {\n const allowedKeysArray = Array.from(allowedKeys);\n const error = ConfigurationError.extraKeys(extraKeys, allowedKeysArray);\n logger.error(error.message);\n throw error;\n }\n}\n\n/**\n * Validates that a configuration directory exists and is accessible.\n *\n * This function performs file system checks to ensure the configuration\n * directory can be used. It handles the isRequired flag to determine\n * whether a missing directory should cause an error or be silently ignored.\n *\n * @param configDirectory - Path to the configuration directory\n * @param isRequired - Whether the directory must exist\n * @param logger - Optional logger for debug information\n * @throws {FileSystemError} When the directory is required but missing or unreadable\n */\nconst validateConfigDirectory = async (configDirectory: string, isRequired: boolean, logger?: Logger): Promise<void> => {\n const storage = Storage.create({ log: logger?.debug || (() => { }) });\n const exists = await storage.exists(configDirectory);\n if (!exists) {\n if (isRequired) {\n throw FileSystemError.directoryNotFound(configDirectory, true);\n }\n } else if (exists) {\n const isReadable = await storage.isDirectoryReadable(configDirectory);\n if (!isReadable) {\n throw FileSystemError.directoryNotReadable(configDirectory);\n }\n }\n}\n\n/**\n * Validates a configuration object against the combined Zod schema.\n *\n * This is the main validation function that:\n * 1. Validates the configuration directory (if config feature enabled)\n * 2. Combines the base ConfigSchema with user-provided schema shape\n * 3. Checks for extra keys not defined in the schema\n * 4. Validates all values against their schema definitions\n * 5. Provides detailed error reporting for validation failures\n *\n * The validation is comprehensive and catches common configuration errors\n * including typos, missing required fields, wrong types, and invalid values.\n *\n * @template T - The Zod schema shape type for configuration validation\n * @param config - The merged configuration object to validate\n * @param options - Cardigantime options containing schema, defaults, and logger\n * @throws {ConfigurationError} When configuration validation fails\n * @throws {FileSystemError} When configuration directory validation fails\n *\n * @example\n * ```typescript\n * const schema = z.object({\n * apiKey: z.string().min(1),\n * timeout: z.number().positive(),\n * });\n *\n * await validate(config, {\n * configShape: schema.shape,\n * defaults: { configDirectory: './config', isRequired: true },\n * logger: console,\n * features: ['config']\n * });\n * // Throws detailed errors if validation fails\n * ```\n */\nexport const validate = async <T extends z.ZodRawShape>(config: z.infer<ZodObject<T & typeof ConfigSchema.shape>>, options: Options<T>): Promise<void> => {\n const logger = options.logger;\n\n if (options.features.includes('config') && (config as any).configDirectory) {\n await validateConfigDirectory((config as any).configDirectory, options.defaults.isRequired, logger);\n }\n\n // Combine the base schema with the user-provided shape\n const fullSchema = z.object({\n ...ConfigSchema.shape,\n ...options.configShape,\n });\n\n // Validate the merged sources against the full schema\n const validationResult = fullSchema.safeParse(config);\n\n // Check for extraneous keys\n checkForExtraKeys(config, fullSchema, logger);\n\n if (!validationResult.success) {\n const formattedError = JSON.stringify(validationResult.error.format(), null, 2);\n logger.error('Configuration validation failed. Check logs for details.');\n logger.silly('Configuration validation failed: %s', formattedError);\n throw ConfigurationError.validation('Configuration validation failed. Check logs for details.', validationResult.error);\n }\n\n return;\n}\n\n","import { z } from 'zod';\n\n/**\n * Extracts default values from a Zod schema recursively using Zod v4's parsing mechanisms.\n *\n * This function leverages Zod's own parsing behavior to extract defaults rather than\n * accessing internal properties. It works by:\n * 1. For ZodDefault types: parsing undefined to trigger the default\n * 2. For ZodObject types: creating a minimal object and parsing to get all defaults\n * 3. For wrapped types: unwrapping and recursing\n *\n * @param schema - The Zod schema to extract defaults from\n * @returns An object containing all default values from the schema\n *\n * @example\n * ```typescript\n * const schema = z.object({\n * name: z.string().default('app'),\n * port: z.number().default(3000),\n * debug: z.boolean().default(false),\n * database: z.object({\n * host: z.string().default('localhost'),\n * port: z.number().default(5432)\n * })\n * });\n *\n * const defaults = extractSchemaDefaults(schema);\n * // Returns: { name: 'app', port: 3000, debug: false, database: { host: 'localhost', port: 5432 } }\n * ```\n */\nexport const extractSchemaDefaults = (schema: z.ZodTypeAny): any => {\n // Handle ZodDefault - parse undefined to get the default value\n if (schema instanceof z.ZodDefault) {\n try {\n return schema.parse(undefined);\n } catch {\n // If parsing undefined fails, return undefined\n return undefined;\n }\n }\n\n // Handle ZodOptional and ZodNullable by unwrapping\n if (schema instanceof z.ZodOptional || schema instanceof z.ZodNullable) {\n return extractSchemaDefaults(schema.unwrap() as any);\n }\n\n // Handle ZodObject - create an object with defaults by parsing an empty object\n if (schema instanceof z.ZodObject) {\n const defaults: any = {};\n const shape = schema.shape;\n\n // First, try to extract defaults from individual fields\n for (const [key, subschema] of Object.entries(shape)) {\n const defaultValue = extractSchemaDefaults(subschema as any);\n if (defaultValue !== undefined) {\n defaults[key] = defaultValue;\n }\n }\n\n // Then parse an empty object to trigger any schema-level defaults\n const result = schema.safeParse({});\n if (result.success) {\n // Merge the parsed result with our extracted defaults\n return { ...defaults, ...result.data };\n }\n\n return Object.keys(defaults).length > 0 ? defaults : undefined;\n }\n\n // Handle ZodArray - return empty array as a reasonable default\n if (schema instanceof z.ZodArray) {\n const elementDefaults = extractSchemaDefaults(schema.element as any);\n return elementDefaults !== undefined ? [elementDefaults] : [];\n }\n\n // Handle ZodRecord - return empty object as default\n if (schema instanceof z.ZodRecord) {\n return {};\n }\n\n // No default available for other schema types\n return undefined;\n};\n\n/**\n * Extracts default values that should be included in generated config files.\n *\n * This function is similar to extractSchemaDefaults but filters out certain types\n * of defaults that shouldn't appear in generated configuration files, such as\n * computed defaults or system-specific values.\n *\n * @param schema - The Zod schema to extract config file defaults from\n * @returns An object containing default values suitable for config files\n *\n * @example\n * ```typescript\n * const schema = z.object({\n * appName: z.string().default('my-app'),\n * timestamp: z.number().default(() => Date.now()), // Excluded from config files\n * port: z.number().default(3000)\n * });\n *\n * const configDefaults = extractConfigFileDefaults(schema);\n * // Returns: { appName: 'my-app', port: 3000 }\n * // Note: timestamp is excluded because it's a function-based default\n * ```\n */\nexport const extractConfigFileDefaults = (schema: z.ZodTypeAny): any => {\n // Handle ZodDefault - parse undefined to get the default value\n if (schema instanceof z.ZodDefault) {\n try {\n const defaultValue = schema.parse(undefined);\n // Exclude function-generated defaults from config files\n // These are typically runtime-computed values\n if (typeof defaultValue === 'function') {\n return undefined;\n }\n return defaultValue;\n } catch {\n return undefined;\n }\n }\n\n // Handle ZodOptional and ZodNullable by unwrapping\n if (schema instanceof z.ZodOptional || schema instanceof z.ZodNullable) {\n return extractConfigFileDefaults(schema.unwrap() as any);\n }\n\n // Handle ZodObject - extract defaults suitable for config files\n if (schema instanceof z.ZodObject) {\n const defaults: any = {};\n const shape = schema.shape;\n\n for (const [key, subschema] of Object.entries(shape)) {\n const defaultValue = extractConfigFileDefaults(subschema as any);\n if (defaultValue !== undefined) {\n defaults[key] = defaultValue;\n }\n }\n\n // Parse an empty object to get any schema-level defaults\n const result = schema.safeParse({});\n if (result.success) {\n // Filter out any function-based or computed values\n const filteredData: any = {};\n for (const [key, value] of Object.entries(result.data)) {\n if (typeof value !== 'function' && value !== null) {\n filteredData[key] = value;\n }\n }\n return { ...defaults, ...filteredData };\n }\n\n return Object.keys(defaults).length > 0 ? defaults : undefined;\n }\n\n // Handle ZodArray - typically don't include array defaults in config files\n if (schema instanceof z.ZodArray) {\n // For config files, we usually don't want to pre-populate arrays\n return undefined;\n }\n\n // Handle ZodRecord - return empty object as default for config files\n if (schema instanceof z.ZodRecord) {\n return {};\n }\n\n // No default available for other schema types\n return undefined;\n};\n\n/**\n * Generates a complete configuration object with all default values populated.\n *\n * This function combines the base ConfigSchema with a user-provided schema shape\n * and extracts all available default values to create a complete configuration\n * example that can be serialized to YAML.\n *\n * @template T - The Zod schema shape type\n * @param configShape - The user's configuration schema shape\n * @param configDirectory - The configuration directory to include in the defaults\n * @returns An object containing all default values suitable for YAML serialization\n *\n * @example\n * ```typescript\n * const shape = z.object({\n * apiKey: z.string().describe('Your API key'),\n * timeout: z.number().default(5000).describe('Request timeout in milliseconds'),\n * features: z.array(z.string()).default(['auth', 'logging'])\n * }).shape;\n *\n * const config = generateDefaultConfig(shape, './config');\n * // Returns: { timeout: 5000, features: ['auth', 'logging'] }\n * // Note: apiKey is not included since it has no default\n * ```\n */\nexport const generateDefaultConfig = <T extends z.ZodRawShape>(\n configShape: T,\n _configDirectory: string\n): Record<string, any> => {\n // Create the full schema by combining base and user schema\n const fullSchema = z.object({\n ...configShape,\n });\n\n // Extract defaults from the full schema using only explicit defaults\n const defaults = extractSchemaDefaults(fullSchema);\n\n // Don't include configDirectory in the generated file since it's runtime-specific\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { configDirectory: _, ...configDefaults } = defaults || {};\n\n return configDefaults || {};\n};\n\n","import { Command } from 'commander';\nimport { Args, DefaultOptions, Feature, Cardigantime, Logger, Options } from 'types';\nimport { z, ZodObject } from 'zod';\nimport { configure } from './configure';\nimport { DEFAULT_FEATURES, DEFAULT_LOGGER, DEFAULT_OPTIONS } from './constants';\nimport { read, checkConfig } from './read';\nimport { ConfigSchema } from 'types';\nimport { validate } from './validate';\nimport * as yaml from 'js-yaml';\nimport * as path from 'node:path';\nimport { generateDefaultConfig } from './util/schema-defaults';\nimport * as Storage from './util/storage';\nimport { FileSystemError } from './error/FileSystemError';\n\nexport * from './types';\nexport { ArgumentError, ConfigurationError, FileSystemError } from './validate';\nexport { VERSION, PROGRAM_NAME } from './constants';\n\n/**\n * Creates a new Cardigantime instance for configuration management.\n * \n * Cardigantime handles the complete configuration lifecycle including:\n * - Reading configuration from YAML files\n * - Validating configuration against Zod schemas\n * - Merging CLI arguments with file configuration and defaults\n * - Providing type-safe configuration objects\n * \n * @template T - The Zod schema shape type for your configuration\n * @param pOptions - Configuration options for the Cardigantime instance\n * @param pOptions.defaults - Default configuration settings\n * @param pOptions.defaults.configDirectory - Directory to search for configuration files (required)\n * @param pOptions.defaults.configFile - Name of the configuration file (optional, defaults to 'config.yaml')\n * @param pOptions.defaults.isRequired - Whether the config directory must exist (optional, defaults to false)\n * @param pOptions.defaults.encoding - File encoding for reading config files (optional, defaults to 'utf8')\n * @param pOptions.defaults.pathResolution - Configuration for resolving relative paths in config values relative to the config file's directory (optional)\n * @param pOptions.features - Array of features to enable (optional, defaults to ['config'])\n * @param pOptions.configShape - Zod schema shape defining your configuration structure (required)\n * @param pOptions.logger - Custom logger implementation (optional, defaults to console logger)\n * @returns A Cardigantime instance with methods for configure, read, validate, and setLogger\n * \n * @example\n * ```typescript\n * import { create } from '@utilarium/cardigantime';\n * import { z } from 'zod';\n * \n * const MyConfigSchema = z.object({\n * apiKey: z.string().min(1),\n * timeout: z.number().default(5000),\n * debug: z.boolean().default(false),\n * contextDirectories: z.array(z.string()).optional(),\n * });\n * \n * const cardigantime = create({\n * defaults: {\n * configDirectory: './config',\n * configFile: 'myapp.yaml',\n * // Resolve relative paths in contextDirectories relative to config file location\n * pathResolution: {\n * pathFields: ['contextDirectories'],\n * resolvePathArray: ['contextDirectories']\n * },\n * // Configure how array fields are merged in hierarchical mode\n * fieldOverlaps: {\n * 'features': 'append', // Accumulate features from all levels\n * 'excludePatterns': 'prepend' // Higher precedence patterns come first\n * }\n * },\n * configShape: MyConfigSchema.shape,\n * features: ['config', 'hierarchical'], // Enable hierarchical discovery\n * });\n * \n * // If config file is at ../config/myapp.yaml and contains:\n * // contextDirectories: ['./context', './data']\n * // These paths will be resolved relative to ../config/ directory\n * ```\n */\nexport const create = <T extends z.ZodRawShape>(pOptions: {\n defaults: Pick<DefaultOptions, 'configDirectory'> & Partial<Omit<DefaultOptions, 'configDirectory'>>,\n features?: Feature[],\n configShape: T, // Make configShape mandatory\n logger?: Logger,\n}): Cardigantime<T> => {\n\n // Validate that configDirectory is a string\n if (!pOptions.defaults.configDirectory || typeof pOptions.defaults.configDirectory !== 'string') {\n throw new Error(`Configuration directory must be a string, received: ${typeof pOptions.defaults.configDirectory} (${JSON.stringify(pOptions.defaults.configDirectory)})`);\n }\n\n const defaults: DefaultOptions = { ...DEFAULT_OPTIONS, ...pOptions.defaults } as DefaultOptions;\n const features = pOptions.features || DEFAULT_FEATURES;\n const configShape = pOptions.configShape;\n let logger = pOptions.logger || DEFAULT_LOGGER;\n\n const options: Options<T> = {\n defaults,\n features,\n configShape, // Store the shape\n logger,\n }\n\n const setLogger = (pLogger: Logger) => {\n logger = pLogger;\n options.logger = pLogger;\n }\n\n const generateConfig = async (configDirectory?: string): Promise<void> => {\n const targetDir = configDirectory || options.defaults.configDirectory;\n const configFile = options.defaults.configFile;\n const encoding = options.defaults.encoding;\n\n // Validate that targetDir is a string\n if (!targetDir || typeof targetDir !== 'string') {\n throw new Error(`Configuration directory must be a string, received: ${typeof targetDir} (${JSON.stringify(targetDir)})`);\n }\n\n logger.verbose(`Generating configuration file in: ${targetDir}`);\n\n // Create storage utility\n const storage = Storage.create({ log: logger.debug });\n\n // Ensure the target directory exists\n const dirExists = await storage.exists(targetDir);\n if (!dirExists) {\n logger.info(`Creating configuration directory: ${targetDir}`);\n try {\n await storage.createDirectory(targetDir);\n } catch (error: any) {\n throw FileSystemError.directoryCreationFailed(targetDir, error);\n }\n }\n\n // Check if directory is writable\n const isWritable = await storage.isDirectoryWritable(targetDir);\n if (!isWritable) {\n throw new FileSystemError('not_writable', 'Configuration directory is not writable', targetDir, 'directory_write');\n }\n\n // Build the full config file path\n const configFilePath = path.join(targetDir, configFile);\n\n // Generate default configuration\n logger.debug(`Generating defaults for schema with keys: ${Object.keys(options.configShape).join(', ')}`);\n const defaultConfig = generateDefaultConfig(options.configShape, targetDir);\n logger.debug(`Generated default config: ${JSON.stringify(defaultConfig, null, 2)}`);\n\n // Convert to YAML with nice formatting\n const yamlContent = yaml.dump(defaultConfig, {\n indent: 2,\n lineWidth: 120,\n noRefs: true,\n sortKeys: true\n });\n\n // Add header comment to the YAML file\n const header = `# Configuration file generated by Cardigantime\n# This file contains default values for your application configuration.\n# Modify the values below to customize your application's behavior.\n#\n# For more information about Cardigantime configuration:\n# https://utilarium.github.io/cardigantime/\n\n`;\n\n const finalContent = header + yamlContent;\n\n // Check if config file already exists\n const configExists = await storage.exists(configFilePath);\n if (configExists) {\n logger.warn(`Configuration file already exists: ${configFilePath}`);\n logger.warn('This file was not overwritten, but here is what the default configuration looks like if you want to copy it:');\n logger.info('\\n' + '='.repeat(60));\n logger.info(finalContent.trim());\n logger.info('='.repeat(60));\n return;\n }\n\n // Write the configuration file\n try {\n await storage.writeFile(configFilePath, finalContent, encoding);\n logger.info(`Configuration file generated successfully: ${configFilePath}`);\n } catch (error: any) {\n throw FileSystemError.operationFailed('write configuration file', configFilePath, error);\n }\n };\n\n return {\n setLogger,\n configure: (command: Command) => configure(command, options),\n validate: (config: z.infer<ZodObject<T & typeof ConfigSchema.shape>>) => validate(config, options),\n read: (args: Args) => read(args, options),\n generateConfig,\n checkConfig: (args: Args) => checkConfig(args, options),\n }\n}\n\n/**\n * Type-safe helper for defining configuration in TypeScript/JavaScript files.\n * \n * This is a simple identity function that provides type checking and\n * autocomplete for configuration objects when using TypeScript config files.\n * \n * @template T - The configuration type\n * @param config - The configuration object\n * @returns The same configuration object (identity function)\n * \n * @example\n * ```typescript\n * // config.ts\n * import { defineConfig } from '@utilarium/cardigantime';\n * \n * export default defineConfig({\n * apiKey: process.env.API_KEY || 'default-key',\n * timeout: 5000,\n * debug: process.env.NODE_ENV === 'development'\n * });\n * ```\n */\nexport function defineConfig<T>(config: T): T {\n return config;\n}\n\n"],"names":["ArgumentError","Error","argument","argumentName","message","_define_property","name","validateConfigDirectory","configDirectory","_testThrowNonArgumentError","trimmed","trim","length","includes","configure","command","options","option","defaults","validatedDefaultDir","retCommand","value","error","validFormats","normalized","toLowerCase","join","VERSION","PROGRAM_NAME","DEFAULT_ENCODING","DEFAULT_CONFIG_FILE","DEFAULT_OPTIONS","configFile","isRequired","encoding","pathResolution","undefined","DEFAULT_FEATURES","DEFAULT_LOGGER","debug","console","info","warn","verbose","silly","FileSystemError","directoryNotFound","path","directoryNotReadable","directoryCreationFailed","originalError","operationFailed","operation","fileNotFound","errorType","create","params","log","exists","fs","promises","stat","isDirectory","stats","isFile","isReadable","access","constants","R_OK","stack","isWritable","W_OK","isFileReadable","isDirectoryWritable","isDirectoryReadable","createDirectory","mkdir","recursive","mkdirError","readFile","validEncodings","maxFileSize","size","code","writeFile","data","forEachFileIn","directory","callback","pattern","files","glob","cwd","nodir","file","err","readStream","createReadStream","hashFile","crypto","createHash","update","digest","slice","listFiles","readdir","resolveConfigPaths","config","configDir","pathFields","resolvePathArray","resolvedConfig","fieldPath","getNestedValue","shouldResolveArrayElements","resolvedValue","resolvePathValue","setNestedValue","obj","split","reduce","current","key","isUnsafeKey","keys","lastKey","pop","some","target","resolveArrayElements","resolveSinglePath","Array","isArray","map","item","pathStr","isAbsolute","resolve","discoverConfigDirectories","configDirName","maxLevels","startingDir","process","logger","storage","createStorage","discoveredDirs","currentDir","level","visited","Set","realPath","has","add","configDirPath","push","parentDir","dirname","findConfigFileWithExtension","configFileName","configFilePath","ext","extname","baseName","basename","alternativeExt","alternativePath","altExists","altIsReadable","loadConfigFromDirectory","yamlContent","parsedYaml","yaml","load","deepMergeConfigs","configs","fieldOverlaps","merged","deepMergeTwo","source","currentPath","overlapMode","getOverlapModeForPath","mergeArrays","result","Object","prototype","hasOwnProperty","call","pathParts","i","parentPath","targetArray","sourceArray","mode","loadHierarchicalConfig","resolvedConfigDirs","errors","sortedDirs","sort","a","b","dir","errorMsg","mergedConfig","clean","fromEntries","entries","filter","_","v","validatePath","userPath","basePath","normalize","startsWith","read","args","rawConfigDir","resolvedConfigDir","rawFileConfig","discoveredConfigDirs","features","hierarchicalResult","forEach","loadSingleDirectoryConfig","processedConfig","alternativeFileName","Storage","test","trackConfigSources","sourcePath","prefix","tracker","sourceLabel","mergeConfigTrackers","trackers","formatConfigValue","toString","String","displayConfigWithSources","repeat","precedence","Math","max","d","sortedKeys","maxKeyLength","k","maxSourceLength","values","paddedKey","padEnd","paddedSource","formattedValue","sourceCount","count","checkConfig","levelTracker","finalConfig","ConfigurationError","validation","zodError","configPath","extraKeys","allowedKeys","schema","details","ConfigFormat","ConfigSchema","z","object","string","array","DEFAULT_ROOT_MARKERS","type","listZodKeys","ZodOptional","ZodNullable","unwrap","ZodAny","ZodRecord","ZodArray","element","ZodObject","shape","flatMap","subschema","fullKey","nested","isPlainObject","listObjectKeys","firstObjectElement","find","nestedKeys","from","checkForExtraKeys","mergedSources","fullSchema","actualKeys","recordPrefixes","findRecordPrefixes","recordPrefix","allowedKeysArray","validate","configShape","validationResult","safeParse","success","formattedError","JSON","stringify","format","extractSchemaDefaults","ZodDefault","parse","defaultValue","elementDefaults","generateDefaultConfig","_configDirectory","configDefaults","pOptions","setLogger","pLogger","generateConfig","targetDir","dirExists","defaultConfig","dump","indent","lineWidth","noRefs","sortKeys","header","finalContent","configExists","defineConfig"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;IAcO,MAAMA,aAAAA,SAAsBC,KAAAA,CAAAA;AAgB/B;;;;AAIC,QACD,IAAIC,QAAAA,GAAmB;QACnB,OAAO,IAAI,CAACC,YAAY;AAC5B,IAAA;AAnBA;;;;;AAKC,QACD,WAAA,CAAYA,YAAoB,EAAEC,OAAe,CAAE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ACvB,YAAA;AACJ,QAAA;;QAGA,IAAI;AACA,YAAA,MAAMjG,OAAAA,CAAQ5D,SAAS,CAAC4E,cAAAA,EAAgB8K,YAAAA,EAAc5S,QAAAA,CAAAA;AACtD6G,YAAAA,MAAAA,CAAOtG,IAAI,CAAC,CAAC,2CAA2C,EAAEuH,cAAAA,CAAAA,CAAgB,CAAA;AAC9E,QAAA,CAAA,CAAE,OAAO1I,KAAAA,EAAY;AACjB,YAAA,MAAMuB,eAAAA,CAAgBM,eAAe,CAAC,0BAAA,EAA4B6G,cAAAA,EAAgB1I,KAAAA,CAAAA;AACtF,QAAA;AACJ,IAAA,CAAA;IAEA,OAAO;AACH4S,QAAAA,SAAAA;QACApT,SAAAA,EAAW,CAACC,OAAAA,GAAqBD,SAAAA,CAAUC,OAAAA,EAASC,OAAAA,CAAAA;QACpDgS,QAAAA,EAAU,CAACrM,MAAAA,GAA8DqM,QAAAA,CAASrM,MAAAA,EAAQ3F,OAAAA,CAAAA;QAC1FwM,IAAAA,EAAM,CAACC,IAAAA,GAAeD,IAAAA,CAAKC,IAAAA,EAAMzM,OAAAA,CAAAA;AACjCoT,QAAAA,cAAAA;QACAnE,WAAAA,EAAa,CAACxC,IAAAA,GAAewC,WAAAA,CAAYxC,IAAAA,EAAMzM,OAAAA;AACnD,KAAA;AACJ;AAEA;;;;;;;;;;;;;;;;;;;;;IAsBO,SAASgU,YAAAA,CAAgBrO,MAAS,EAAA;IACrC,OAAOA,MAAAA;AACX;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"cardigantime.cjs","sources":["../src/error/ArgumentError.ts","../src/configure.ts","../src/constants.ts","../src/error/FileSystemError.ts","../src/util/storage.ts","../src/util/path-normalization.ts","../src/util/hierarchical.ts","../src/read.ts","../src/error/ConfigurationError.ts","../src/types.ts","../src/validate.ts","../src/util/schema-defaults.ts","../src/cardigantime.ts"],"sourcesContent":["/**\n * Error thrown when CLI arguments or function parameters are invalid.\n * \n * This error provides specific context about which argument failed validation\n * and why, making it easier for users to fix their command-line usage or\n * for developers to debug parameter issues.\n * \n * @example\n * ```typescript\n * throw new ArgumentError('config-directory', 'Path cannot be empty');\n * // Error message: \"Path cannot be empty\"\n * // error.argument: \"config-directory\"\n * ```\n */\nexport class ArgumentError extends Error {\n /** The name of the argument that caused the error */\n private argumentName: string;\n\n /**\n * Creates a new ArgumentError instance.\n * \n * @param argumentName - The name of the invalid argument\n * @param message - Description of why the argument is invalid\n */\n constructor(argumentName: string, message: string) {\n super(`${message}`);\n this.name = 'ArgumentError';\n this.argumentName = argumentName;\n }\n\n /**\n * Gets the name of the argument that caused this error.\n * \n * @returns The argument name\n */\n get argument(): string {\n return this.argumentName;\n }\n}","import { Command } from \"commander\";\nimport { z } from \"zod\";\nimport { ArgumentError } from \"./error/ArgumentError\";\nimport { Options } from \"./types\";\nexport { ArgumentError };\n\n/**\n * Validates a configuration directory path to ensure it's safe and valid.\n * \n * Performs security and safety checks including:\n * - Non-empty string validation\n * - Null byte injection prevention\n * - Path length validation\n * - Type checking\n * \n * @param configDirectory - The configuration directory path to validate\n * @param _testThrowNonArgumentError - Internal testing parameter to simulate non-ArgumentError exceptions\n * @returns The trimmed and validated configuration directory path\n * @throws {ArgumentError} When the directory path is invalid\n * \n * @example\n * ```typescript\n * const validDir = validateConfigDirectory('./config'); // Returns './config'\n * const invalidDir = validateConfigDirectory(''); // Throws ArgumentError\n * ```\n */\nexport function validateConfigDirectory(configDirectory: string, _testThrowNonArgumentError?: boolean): string {\n if (_testThrowNonArgumentError) {\n throw new Error('Test non-ArgumentError for coverage');\n }\n\n if (!configDirectory) {\n throw new ArgumentError('configDirectory', 'Configuration directory cannot be empty');\n }\n\n if (typeof configDirectory !== 'string') {\n throw new ArgumentError('configDirectory', 'Configuration directory must be a string');\n }\n\n const trimmed = configDirectory.trim();\n if (trimmed.length === 0) {\n throw new ArgumentError('configDirectory', 'Configuration directory cannot be empty or whitespace only');\n }\n\n // Check for obviously invalid paths\n if (trimmed.includes('\\0')) {\n throw new ArgumentError('configDirectory', 'Configuration directory contains invalid null character');\n }\n\n // Validate path length (reasonable limit)\n if (trimmed.length > 1000) {\n throw new ArgumentError('configDirectory', 'Configuration directory path is too long (max 1000 characters)');\n }\n\n return trimmed;\n}\n\n/**\n * Configures a Commander.js command with Cardigantime's CLI options.\n * \n * This function adds command-line options that allow users to override\n * configuration settings at runtime, such as:\n * - --config-directory: Override the default configuration directory\n * \n * The function validates both the command object and the options to ensure\n * they meet the requirements for proper integration.\n * \n * @template T - The Zod schema shape type for configuration validation\n * @param command - The Commander.js Command instance to configure\n * @param options - Cardigantime options containing defaults and schema\n * @param _testThrowNonArgumentError - Internal testing parameter\n * @returns Promise resolving to the configured Command instance\n * @throws {ArgumentError} When command or options are invalid\n * \n * @example\n * ```typescript\n * import { Command } from 'commander';\n * import { configure } from './configure';\n * \n * const program = new Command();\n * const configuredProgram = await configure(program, options);\n * \n * // Now the program accepts: --config-directory <path>\n * ```\n */\nexport const configure = async <T extends z.ZodRawShape>(\n command: Command,\n options: Options<T>,\n _testThrowNonArgumentError?: boolean\n): Promise<Command> => {\n // Validate the command object\n if (!command) {\n throw new ArgumentError('command', 'Command instance is required');\n }\n\n if (typeof command.option !== 'function') {\n throw new ArgumentError('command', 'Command must be a valid Commander.js Command instance');\n }\n\n // Validate options\n if (!options) {\n throw new ArgumentError('options', 'Options object is required');\n }\n\n if (!options.defaults) {\n throw new ArgumentError('options.defaults', 'Options must include defaults configuration');\n }\n\n if (!options.defaults.configDirectory) {\n throw new ArgumentError('options.defaults.configDirectory', 'Default config directory is required');\n }\n\n // Validate the default config directory\n const validatedDefaultDir = validateConfigDirectory(options.defaults.configDirectory, _testThrowNonArgumentError);\n\n let retCommand = command;\n\n // Add the config directory option with validation\n retCommand = retCommand.option(\n '-c, --config-directory <configDirectory>',\n 'Configuration directory path',\n (value: string) => {\n try {\n return validateConfigDirectory(value, _testThrowNonArgumentError);\n } catch (error) {\n if (error instanceof ArgumentError) {\n // Re-throw with more specific context for CLI usage\n throw new ArgumentError('config-directory', `Invalid --config-directory: ${error.message}`);\n }\n throw error;\n }\n },\n validatedDefaultDir\n );\n\n // Add the init config option\n retCommand = retCommand.option(\n '--init-config',\n 'Generate initial configuration file and exit'\n );\n\n // Add the check config option\n retCommand = retCommand.option(\n '--check-config',\n 'Display resolved configuration with source tracking and exit'\n );\n\n // Add the config format option\n retCommand = retCommand.option(\n '--config-format <format>',\n 'Force a specific configuration file format (yaml, json, javascript, typescript)',\n (value: string) => {\n const validFormats = ['yaml', 'json', 'javascript', 'typescript'];\n const normalized = value.toLowerCase();\n if (!validFormats.includes(normalized)) {\n throw new ArgumentError(\n 'config-format',\n `Invalid --config-format: must be one of ${validFormats.join(', ')}`\n );\n }\n return normalized;\n }\n );\n\n return retCommand;\n}\n\n\n\n\n","import { DefaultOptions, Feature, Logger } from \"./types\";\n\n/** Version string populated at build time with git and system information */\nexport const VERSION = '__VERSION__ (__GIT_BRANCH__/__GIT_COMMIT__ __GIT_TAGS__ __GIT_COMMIT_DATE__) __SYSTEM_INFO__';\n\n/** The program name used in CLI help and error messages */\nexport const PROGRAM_NAME = 'cardigantime';\n\n/** Default file encoding for reading configuration files */\nexport const DEFAULT_ENCODING = 'utf8';\n\n/** Default configuration file name to look for in the config directory */\nexport const DEFAULT_CONFIG_FILE = 'config.yaml';\n\n/**\n * Default configuration options applied when creating a Cardigantime instance.\n * These provide sensible defaults that work for most use cases.\n */\nexport const DEFAULT_OPTIONS: Partial<DefaultOptions> = {\n configFile: DEFAULT_CONFIG_FILE,\n isRequired: false,\n encoding: DEFAULT_ENCODING,\n pathResolution: undefined, // No path resolution by default\n}\n\n/**\n * Default features enabled when creating a Cardigantime instance.\n * Currently includes only the 'config' feature for configuration file support.\n */\nexport const DEFAULT_FEATURES: Feature[] = ['config'];\n\n/**\n * Default logger implementation using console methods.\n * Provides basic logging functionality when no custom logger is specified.\n * The verbose and silly methods are no-ops to avoid excessive output.\n */\nexport const DEFAULT_LOGGER: Logger = {\n // eslint-disable-next-line no-console\n debug: console.debug,\n // eslint-disable-next-line no-console\n info: console.info,\n // eslint-disable-next-line no-console\n warn: console.warn,\n // eslint-disable-next-line no-console\n error: console.error,\n\n verbose: () => { },\n\n silly: () => { },\n}\n","/**\n * Error thrown when file system operations fail\n */\nexport class FileSystemError extends Error {\n public readonly errorType: 'not_found' | 'not_readable' | 'not_writable' | 'creation_failed' | 'operation_failed';\n public readonly path: string;\n public readonly operation: string;\n public readonly originalError?: Error;\n\n constructor(\n errorType: 'not_found' | 'not_readable' | 'not_writable' | 'creation_failed' | 'operation_failed',\n message: string,\n path: string,\n operation: string,\n originalError?: Error\n ) {\n super(message);\n this.name = 'FileSystemError';\n this.errorType = errorType;\n this.path = path;\n this.operation = operation;\n this.originalError = originalError;\n }\n\n /**\n * Creates an error for when a required directory doesn't exist\n */\n static directoryNotFound(path: string, isRequired: boolean = false): FileSystemError {\n const message = isRequired\n ? 'Configuration directory does not exist and is required'\n : 'Configuration directory not found';\n return new FileSystemError('not_found', message, path, 'directory_access');\n }\n\n /**\n * Creates an error for when a directory exists but isn't readable\n */\n static directoryNotReadable(path: string): FileSystemError {\n const message = 'Configuration directory exists but is not readable';\n return new FileSystemError('not_readable', message, path, 'directory_read');\n }\n\n /**\n * Creates an error for directory creation failures\n */\n static directoryCreationFailed(path: string, originalError: Error): FileSystemError {\n const message = 'Failed to create directory: ' + (originalError.message || 'Unknown error');\n return new FileSystemError('creation_failed', message, path, 'directory_create', originalError);\n }\n\n /**\n * Creates an error for file operation failures (glob, etc.)\n */\n static operationFailed(operation: string, path: string, originalError: Error): FileSystemError {\n const message = `Failed to ${operation}: ${originalError.message || 'Unknown error'}`;\n return new FileSystemError('operation_failed', message, path, operation, originalError);\n }\n\n /**\n * Creates an error for when a file is not found\n */\n static fileNotFound(path: string): FileSystemError {\n const message = 'Configuration file not found';\n return new FileSystemError('not_found', message, path, 'file_read');\n }\n} ","import * as fs from 'node:fs';\nimport { glob } from 'glob';\nimport * as path from 'node:path';\nimport * as crypto from 'node:crypto';\nimport { FileSystemError } from '../error/FileSystemError';\n/**\n * This module exists to isolate filesystem operations from the rest of the codebase.\n * This makes testing easier by avoiding direct fs mocking in jest configuration.\n * \n * Additionally, abstracting storage operations allows for future flexibility - \n * this export utility may need to work with storage systems other than the local filesystem\n * (e.g. S3, Google Cloud Storage, etc).\n */\n\nexport interface Utility {\n exists: (path: string) => Promise<boolean>;\n isDirectory: (path: string) => Promise<boolean>;\n isFile: (path: string) => Promise<boolean>;\n isReadable: (path: string) => Promise<boolean>;\n isWritable: (path: string) => Promise<boolean>;\n isFileReadable: (path: string) => Promise<boolean>;\n isDirectoryWritable: (path: string) => Promise<boolean>;\n isDirectoryReadable: (path: string) => Promise<boolean>;\n createDirectory: (path: string) => Promise<void>;\n readFile: (path: string, encoding: string) => Promise<string>;\n readStream: (path: string) => Promise<fs.ReadStream>;\n writeFile: (path: string, data: string | Buffer, encoding: string) => Promise<void>;\n forEachFileIn: (directory: string, callback: (path: string) => Promise<void>, options?: { pattern: string }) => Promise<void>;\n hashFile: (path: string, length: number) => Promise<string>;\n listFiles: (directory: string) => Promise<string[]>;\n}\n\nexport const create = (params: { log?: (message: string, ...args: any[]) => void }): Utility => {\n\n // eslint-disable-next-line no-console\n const log = params.log || console.log;\n\n const exists = async (path: string): Promise<boolean> => {\n try {\n await fs.promises.stat(path);\n return true;\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (error: any) {\n return false;\n }\n }\n\n const isDirectory = async (path: string): Promise<boolean> => {\n const stats = await fs.promises.stat(path);\n if (!stats.isDirectory()) {\n log(`${path} is not a directory`);\n return false;\n }\n return true;\n }\n\n const isFile = async (path: string): Promise<boolean> => {\n const stats = await fs.promises.stat(path);\n if (!stats.isFile()) {\n log(`${path} is not a file`);\n return false;\n }\n return true;\n }\n\n const isReadable = async (path: string): Promise<boolean> => {\n try {\n await fs.promises.access(path, fs.constants.R_OK);\n } catch (error: any) {\n log(`${path} is not readable: %s %s`, error.message, error.stack);\n return false;\n }\n return true;\n }\n\n const isWritable = async (path: string): Promise<boolean> => {\n try {\n await fs.promises.access(path, fs.constants.W_OK);\n } catch (error: any) {\n log(`${path} is not writable: %s %s`, error.message, error.stack);\n return false;\n }\n return true;\n }\n\n const isFileReadable = async (path: string): Promise<boolean> => {\n return await exists(path) && await isFile(path) && await isReadable(path);\n }\n\n const isDirectoryWritable = async (path: string): Promise<boolean> => {\n return await exists(path) && await isDirectory(path) && await isWritable(path);\n }\n\n const isDirectoryReadable = async (path: string): Promise<boolean> => {\n return await exists(path) && await isDirectory(path) && await isReadable(path);\n }\n\n const createDirectory = async (path: string): Promise<void> => {\n try {\n await fs.promises.mkdir(path, { recursive: true });\n } catch (mkdirError: any) {\n throw FileSystemError.directoryCreationFailed(path, mkdirError);\n }\n }\n\n const readFile = async (path: string, encoding: string): Promise<string> => {\n // Validate encoding parameter\n const validEncodings = ['utf8', 'utf-8', 'ascii', 'latin1', 'base64', 'hex', 'utf16le', 'ucs2', 'ucs-2'];\n if (!validEncodings.includes(encoding.toLowerCase())) {\n throw new Error('Invalid encoding specified');\n }\n\n // Check file size before reading to prevent DoS\n try {\n const stats = await fs.promises.stat(path);\n const maxFileSize = 10 * 1024 * 1024; // 10MB limit\n if (stats.size > maxFileSize) {\n throw new Error('File too large to process');\n }\n } catch (error: any) {\n if (error.code === 'ENOENT') {\n throw FileSystemError.fileNotFound(path);\n }\n throw error;\n }\n\n return await fs.promises.readFile(path, { encoding: encoding as BufferEncoding });\n }\n\n const writeFile = async (path: string, data: string | Buffer, encoding: string): Promise<void> => {\n await fs.promises.writeFile(path, data, { encoding: encoding as BufferEncoding });\n }\n\n const forEachFileIn = async (directory: string, callback: (file: string) => Promise<void>, options: { pattern: string | string[] } = { pattern: '*.*' }): Promise<void> => {\n try {\n const files = await glob(options.pattern, { cwd: directory, nodir: true });\n for (const file of files) {\n await callback(path.join(directory, file));\n }\n } catch (err: any) {\n throw FileSystemError.operationFailed(`glob pattern ${options.pattern}`, directory, err);\n }\n }\n\n const readStream = async (path: string): Promise<fs.ReadStream> => {\n return fs.createReadStream(path);\n }\n\n const hashFile = async (path: string, length: number): Promise<string> => {\n const file = await readFile(path, 'utf8');\n return crypto.createHash('sha256').update(file).digest('hex').slice(0, length);\n }\n\n const listFiles = async (directory: string): Promise<string[]> => {\n return await fs.promises.readdir(directory);\n }\n\n return {\n exists,\n isDirectory,\n isFile,\n isReadable,\n isWritable,\n isFileReadable,\n isDirectoryWritable,\n isDirectoryReadable,\n createDirectory,\n readFile,\n readStream,\n writeFile,\n forEachFileIn,\n hashFile,\n listFiles,\n };\n}","/**\n * Path normalization utilities for handling file:// URLs and rejecting non-file URLs\n */\n\n/**\n * Normalizes path input by converting file:// URLs to paths and rejecting non-file URLs\n * @param value - The value to normalize (string, array, object, or other)\n * @returns Normalized value with file:// URLs converted to paths\n * @throws Error if value contains http://, https://, or other non-file URLs\n */\nexport function normalizePathInput(value: any): any {\n if (typeof value === 'string') {\n return normalizePathString(value);\n }\n\n if (Array.isArray(value)) {\n return value.map(item =>\n typeof item === 'string' ? normalizePathString(item) : item\n );\n }\n\n if (value && typeof value === 'object') {\n const normalized: any = {};\n for (const [key, val] of Object.entries(value)) {\n normalized[key] = normalizePathInput(val); // Recursive for nested objects\n }\n return normalized;\n }\n\n return value;\n}\n\n/**\n * Normalizes a single path string by converting file:// URLs and rejecting non-file URLs\n * @param str - The string to normalize\n * @returns Normalized path string\n * @throws Error if string contains non-file URLs\n */\nfunction normalizePathString(str: string): string {\n // Check for non-file URLs and reject them\n if (/^https?:\\/\\//i.test(str)) {\n throw new Error(`Non-file URLs are not supported in path fields: ${str}`);\n }\n\n // Convert file:// URLs to regular paths\n if (/^file:\\/\\//i.test(str)) {\n try {\n const url = new URL(str);\n // Decode URL-encoded characters (like %20 for spaces)\n return decodeURIComponent(url.pathname);\n } catch {\n throw new Error(`Invalid file:// URL: ${str}`);\n }\n }\n\n // Return regular paths unchanged\n return str;\n}\n","import * as path from 'node:path';\nimport * as yaml from 'js-yaml';\nimport { create as createStorage } from './storage';\nimport { Logger, FieldOverlapOptions, ArrayOverlapMode } from '../types';\nimport { normalizePathInput } from './path-normalization';\n\n/**\n * Resolves relative paths in configuration values relative to the configuration file's directory.\n */\nfunction resolveConfigPaths(\n config: any,\n configDir: string,\n pathFields: string[] = [],\n resolvePathArray: string[] = []\n): any {\n if (!config || typeof config !== 'object' || pathFields.length === 0) {\n return config;\n }\n\n const resolvedConfig = { ...config };\n\n for (const fieldPath of pathFields) {\n const value = getNestedValue(resolvedConfig, fieldPath);\n if (value !== undefined) {\n // Step 1: Normalize input (convert file:// URLs, reject http/https)\n const normalizedValue = normalizePathInput(value);\n \n // Step 2: Resolve paths relative to config directory\n const shouldResolveArrayElements = resolvePathArray.includes(fieldPath);\n const resolvedValue = resolvePathValue(normalizedValue, configDir, shouldResolveArrayElements);\n setNestedValue(resolvedConfig, fieldPath, resolvedValue);\n }\n }\n\n return resolvedConfig;\n}\n\n/**\n * Gets a nested value from an object using dot notation.\n */\nfunction getNestedValue(obj: any, path: string): any {\n return path.split('.').reduce((current, key) => current?.[key], obj);\n}\n\n/**\n * Sets a nested value in an object using dot notation.\n */\nfunction isUnsafeKey(key: string): boolean {\n return key === '__proto__' || key === 'constructor' || key === 'prototype';\n}\n\nfunction setNestedValue(obj: any, path: string, value: any): void {\n const keys = path.split('.');\n const lastKey = keys.pop()!;\n\n // Prevent prototype pollution via special property names\n if (isUnsafeKey(lastKey) || keys.some(isUnsafeKey)) {\n return;\n }\n\n const target = keys.reduce((current, key) => {\n // Skip if this is an unsafe key (already checked above, but defensive)\n if (isUnsafeKey(key)) {\n return current;\n }\n if (!(key in current)) {\n current[key] = {};\n }\n return current[key];\n }, obj);\n target[lastKey] = value;\n}\n\n/**\n * Resolves a path value (string, array, or object) relative to the config directory.\n * \n * Handles:\n * - Strings: Resolved relative to configDir\n * - Arrays: Elements resolved if resolveArrayElements is true\n * - Objects: All string values and array elements resolved recursively\n * - Other types: Returned unchanged\n */\nfunction resolvePathValue(value: any, configDir: string, resolveArrayElements: boolean): any {\n if (typeof value === 'string') {\n return resolveSinglePath(value, configDir);\n }\n\n if (Array.isArray(value) && resolveArrayElements) {\n return value.map(item =>\n typeof item === 'string' ? resolveSinglePath(item, configDir) : item\n );\n }\n\n // NEW: Handle objects with string values\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n const resolved: any = {};\n for (const [key, val] of Object.entries(value)) {\n if (typeof val === 'string') {\n resolved[key] = resolveSinglePath(val, configDir);\n } else if (Array.isArray(val)) {\n // Also handle arrays within objects\n resolved[key] = val.map(item =>\n typeof item === 'string' ? resolveSinglePath(item, configDir) : item\n );\n } else {\n // Keep other types unchanged\n resolved[key] = val;\n }\n }\n return resolved;\n }\n\n return value;\n}\n\n/**\n * Resolves a single path string relative to the config directory if it's a relative path.\n */\nfunction resolveSinglePath(pathStr: string, configDir: string): string {\n if (!pathStr || path.isAbsolute(pathStr)) {\n return pathStr;\n }\n\n return path.resolve(configDir, pathStr);\n}\n\n/**\n * Represents a discovered configuration directory with its path and precedence level.\n */\nexport interface DiscoveredConfigDir {\n /** Absolute path to the configuration directory */\n path: string;\n /** Distance from the starting directory (0 = closest/highest precedence) */\n level: number;\n}\n\n/**\n * Options for hierarchical configuration discovery.\n */\nexport interface HierarchicalDiscoveryOptions {\n /** Name of the configuration directory to look for (e.g., '.kodrdriv') */\n configDirName: string;\n /** Name of the configuration file within each directory */\n configFileName: string;\n /** Maximum number of parent directories to traverse (default: 10) */\n maxLevels?: number;\n /** Starting directory for discovery (default: process.cwd()) */\n startingDir?: string;\n /** File encoding for reading configuration files */\n encoding?: string;\n /** Logger for debugging */\n logger?: Logger;\n /** Array of field names that contain paths to be resolved */\n pathFields?: string[];\n /** Array of field names whose array elements should all be resolved as paths */\n resolvePathArray?: string[];\n /** Configuration for how array fields should be merged in hierarchical mode */\n fieldOverlaps?: FieldOverlapOptions;\n}\n\n/**\n * Result of loading configurations from multiple directories.\n */\nexport interface HierarchicalConfigResult {\n /** Merged configuration object with proper precedence */\n config: object;\n /** Array of directories where configuration was found */\n discoveredDirs: DiscoveredConfigDir[];\n /** Array of directories that actually contained valid configuration files */\n resolvedConfigDirs: DiscoveredConfigDir[];\n /** Array of any errors encountered during loading (non-fatal) */\n errors: string[];\n}\n\n/**\n * Discovers configuration directories by traversing up the directory tree.\n * \n * Starting from the specified directory (or current working directory),\n * this function searches for directories with the given name, continuing\n * up the directory tree until it reaches the filesystem root or the\n * maximum number of levels.\n * \n * @param options Configuration options for discovery\n * @returns Promise resolving to array of discovered configuration directories\n * \n * @example\n * ```typescript\n * const dirs = await discoverConfigDirectories({\n * configDirName: '.kodrdriv',\n * configFileName: 'config.yaml',\n * maxLevels: 5\n * });\n * // Returns: [\n * // { path: '/project/.kodrdriv', level: 0 },\n * // { path: '/project/parent/.kodrdriv', level: 1 }\n * // ]\n * ```\n */\nexport async function discoverConfigDirectories(\n options: HierarchicalDiscoveryOptions\n): Promise<DiscoveredConfigDir[]> {\n const {\n configDirName,\n maxLevels = 10,\n startingDir = process.cwd(),\n logger\n } = options;\n\n const storage = createStorage({ log: logger?.debug || (() => { }) });\n const discoveredDirs: DiscoveredConfigDir[] = [];\n\n let currentDir = path.resolve(startingDir);\n let level = 0;\n const visited = new Set<string>(); // Prevent infinite loops with symlinks\n\n logger?.debug(`Starting hierarchical discovery from: ${currentDir}`);\n\n while (level < maxLevels) {\n // Prevent infinite loops with symlinks\n const realPath = path.resolve(currentDir);\n if (visited.has(realPath)) {\n logger?.debug(`Already visited ${realPath}, stopping discovery`);\n break;\n }\n visited.add(realPath);\n\n const configDirPath = path.join(currentDir, configDirName);\n logger?.debug(`Checking for config directory: ${configDirPath}`);\n\n try {\n const exists = await storage.exists(configDirPath);\n const isReadable = exists && await storage.isDirectoryReadable(configDirPath);\n\n if (exists && isReadable) {\n discoveredDirs.push({\n path: configDirPath,\n level\n });\n logger?.debug(`Found config directory at level ${level}: ${configDirPath}`);\n } else if (exists && !isReadable) {\n logger?.debug(`Config directory exists but is not readable: ${configDirPath}`);\n }\n } catch (error: any) {\n logger?.debug(`Error checking config directory ${configDirPath}: ${error.message}`);\n }\n\n // Move up one directory level\n const parentDir = path.dirname(currentDir);\n\n // Check if we've reached the root directory\n if (parentDir === currentDir) {\n logger?.debug('Reached filesystem root, stopping discovery');\n break;\n }\n\n currentDir = parentDir;\n level++;\n }\n\n logger?.verbose(`Discovery complete. Found ${discoveredDirs.length} config directories`);\n return discoveredDirs;\n}\n\n/**\n * Tries to find a config file with alternative extensions (.yaml or .yml).\n * \n * @param storage Storage instance to use for file operations\n * @param configDir The directory containing the config file\n * @param configFileName The base config file name (may have .yaml or .yml extension)\n * @param logger Optional logger for debugging\n * @returns Promise resolving to the found config file path or null if not found\n */\nasync function findConfigFileWithExtension(\n storage: any,\n configDir: string,\n configFileName: string,\n logger?: Logger\n): Promise<string | null> {\n const configFilePath = path.join(configDir, configFileName);\n \n // First try the exact filename as specified\n const exists = await storage.exists(configFilePath);\n if (exists) {\n const isReadable = await storage.isFileReadable(configFilePath);\n if (isReadable) {\n return configFilePath;\n }\n }\n \n // If the exact filename doesn't exist or isn't readable, try alternative extensions\n // Only do this if the filename has a .yaml or .yml extension\n const ext = path.extname(configFileName);\n if (ext === '.yaml' || ext === '.yml') {\n const baseName = path.basename(configFileName, ext);\n const alternativeExt = ext === '.yaml' ? '.yml' : '.yaml';\n const alternativePath = path.join(configDir, baseName + alternativeExt);\n \n logger?.debug(`Config file not found at ${configFilePath}, trying alternative: ${alternativePath}`);\n \n const altExists = await storage.exists(alternativePath);\n if (altExists) {\n const altIsReadable = await storage.isFileReadable(alternativePath);\n if (altIsReadable) {\n logger?.debug(`Found config file with alternative extension: ${alternativePath}`);\n return alternativePath;\n }\n }\n }\n \n return null;\n}\n\n/**\n * Loads and parses a configuration file from a directory.\n * \n * @param configDir Path to the configuration directory\n * @param configFileName Name of the configuration file\n * @param encoding File encoding\n * @param logger Optional logger\n * @param pathFields Optional array of field names that contain paths to be resolved\n * @param resolvePathArray Optional array of field names whose array elements should all be resolved as paths\n * @returns Promise resolving to parsed configuration object or null if not found\n */\nexport async function loadConfigFromDirectory(\n configDir: string,\n configFileName: string,\n encoding: string = 'utf8',\n logger?: Logger,\n pathFields?: string[],\n resolvePathArray?: string[]\n): Promise<object | null> {\n const storage = createStorage({ log: logger?.debug || (() => { }) });\n \n try {\n logger?.verbose(`Attempting to load config file: ${path.join(configDir, configFileName)}`);\n\n // Try to find the config file with alternative extensions\n const configFilePath = await findConfigFileWithExtension(storage, configDir, configFileName, logger);\n \n if (!configFilePath) {\n logger?.debug(`Config file does not exist: ${path.join(configDir, configFileName)}`);\n return null;\n }\n\n const yamlContent = await storage.readFile(configFilePath, encoding);\n const parsedYaml = yaml.load(yamlContent);\n\n if (parsedYaml !== null && typeof parsedYaml === 'object') {\n let config = parsedYaml as object;\n\n // Apply path resolution if configured\n if (pathFields && pathFields.length > 0) {\n config = resolveConfigPaths(config, configDir, pathFields, resolvePathArray || []);\n }\n\n logger?.verbose(`Successfully loaded config from: ${configFilePath}`);\n return config;\n } else {\n logger?.debug(`Config file contains invalid format: ${configFilePath}`);\n return null;\n }\n } catch (error: any) {\n logger?.debug(`Error loading config from ${path.join(configDir, configFileName)}: ${error.message}`);\n return null;\n }\n}\n\n/**\n * Deep merges multiple configuration objects with proper precedence and configurable array overlap behavior.\n * \n * Objects are merged from lowest precedence to highest precedence,\n * meaning that properties in later objects override properties in earlier objects.\n * Arrays can be merged using different strategies based on the fieldOverlaps configuration.\n * \n * @param configs Array of configuration objects, ordered from lowest to highest precedence\n * @param fieldOverlaps Configuration for how array fields should be merged (optional)\n * @returns Merged configuration object\n * \n * @example\n * ```typescript\n * const merged = deepMergeConfigs([\n * { api: { timeout: 5000 }, features: ['auth'] }, // Lower precedence\n * { api: { retries: 3 }, features: ['analytics'] }, // Higher precedence\n * ], {\n * 'features': 'append' // Results in features: ['auth', 'analytics']\n * });\n * ```\n */\nexport function deepMergeConfigs(configs: object[], fieldOverlaps?: FieldOverlapOptions): object {\n if (configs.length === 0) {\n return {};\n }\n\n if (configs.length === 1) {\n return { ...configs[0] };\n }\n\n return configs.reduce((merged, current) => {\n return deepMergeTwo(merged, current, fieldOverlaps);\n }, {});\n}\n\n/**\n * Deep merges two objects with proper precedence and configurable array overlap behavior.\n * \n * @param target Target object (lower precedence)\n * @param source Source object (higher precedence)\n * @param fieldOverlaps Configuration for how array fields should be merged (optional)\n * @param currentPath Current field path for nested merging (used internally)\n * @returns Merged object\n */\nfunction deepMergeTwo(target: any, source: any, fieldOverlaps?: FieldOverlapOptions, currentPath: string = ''): any {\n // Handle null/undefined\n if (source == null) return target;\n if (target == null) return source;\n\n // Handle non-objects (primitives, arrays, functions, etc.)\n if (typeof source !== 'object' || typeof target !== 'object') {\n return source; // Source takes precedence\n }\n\n // Handle arrays with configurable overlap behavior\n if (Array.isArray(source)) {\n if (Array.isArray(target) && fieldOverlaps) {\n const overlapMode = getOverlapModeForPath(currentPath, fieldOverlaps);\n return mergeArrays(target, source, overlapMode);\n } else {\n // Default behavior: replace entirely\n return [...source];\n }\n }\n\n if (Array.isArray(target)) {\n return source; // Source object replaces target array\n }\n\n // Deep merge objects\n const result = { ...target };\n\n for (const key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n const fieldPath = currentPath ? `${currentPath}.${key}` : key;\n\n if (Object.prototype.hasOwnProperty.call(result, key) &&\n typeof result[key] === 'object' &&\n typeof source[key] === 'object' &&\n !Array.isArray(source[key]) &&\n !Array.isArray(result[key])) {\n // Recursively merge nested objects\n result[key] = deepMergeTwo(result[key], source[key], fieldOverlaps, fieldPath);\n } else {\n // Handle arrays and primitives with overlap consideration\n if (Array.isArray(source[key]) && Array.isArray(result[key]) && fieldOverlaps) {\n const overlapMode = getOverlapModeForPath(fieldPath, fieldOverlaps);\n result[key] = mergeArrays(result[key], source[key], overlapMode);\n } else {\n // Replace with source value (higher precedence)\n result[key] = source[key];\n }\n }\n }\n }\n\n return result;\n}\n\n/**\n * Determines the overlap mode for a given field path.\n * \n * @param fieldPath The current field path (dot notation)\n * @param fieldOverlaps Configuration mapping field paths to overlap modes\n * @returns The overlap mode to use for this field path\n */\nfunction getOverlapModeForPath(fieldPath: string, fieldOverlaps: FieldOverlapOptions): ArrayOverlapMode {\n // Check for exact match first\n if (fieldPath in fieldOverlaps) {\n return fieldOverlaps[fieldPath];\n }\n\n // Check for any parent path matches (for nested configurations)\n const pathParts = fieldPath.split('.');\n for (let i = pathParts.length - 1; i > 0; i--) {\n const parentPath = pathParts.slice(0, i).join('.');\n if (parentPath in fieldOverlaps) {\n return fieldOverlaps[parentPath];\n }\n }\n\n // Default to override if no specific configuration found\n return 'override';\n}\n\n/**\n * Merges two arrays based on the specified overlap mode.\n * \n * @param targetArray The lower precedence array\n * @param sourceArray The higher precedence array\n * @param mode The overlap mode to use\n * @returns The merged array\n */\nfunction mergeArrays(targetArray: any[], sourceArray: any[], mode: ArrayOverlapMode): any[] {\n switch (mode) {\n case 'append':\n return [...targetArray, ...sourceArray];\n case 'prepend':\n return [...sourceArray, ...targetArray];\n case 'override':\n default:\n return [...sourceArray];\n }\n}\n\n/**\n * Loads configurations from multiple directories and merges them with proper precedence.\n * \n * This is the main function for hierarchical configuration loading. It:\n * 1. Discovers configuration directories up the directory tree\n * 2. Loads configuration files from each discovered directory\n * 3. Merges them with proper precedence (closer directories win)\n * 4. Returns the merged configuration with metadata\n * \n * @param options Configuration options for hierarchical loading\n * @returns Promise resolving to hierarchical configuration result\n * \n * @example\n * ```typescript\n * const result = await loadHierarchicalConfig({\n * configDirName: '.kodrdriv',\n * configFileName: 'config.yaml',\n * startingDir: '/project/subdir',\n * maxLevels: 5,\n * fieldOverlaps: {\n * 'features': 'append',\n * 'excludePatterns': 'prepend'\n * }\n * });\n * \n * // result.config contains merged configuration with custom array merging\n * // result.discoveredDirs shows where configs were found\n * // result.errors contains any non-fatal errors\n * ```\n */\nexport async function loadHierarchicalConfig(\n options: HierarchicalDiscoveryOptions\n): Promise<HierarchicalConfigResult> {\n const { configFileName, encoding = 'utf8', logger, pathFields, resolvePathArray, fieldOverlaps } = options;\n\n logger?.verbose('Starting hierarchical configuration loading');\n\n // Discover all configuration directories\n const discoveredDirs = await discoverConfigDirectories(options);\n\n if (discoveredDirs.length === 0) {\n logger?.verbose('No configuration directories found');\n return {\n config: {},\n discoveredDirs: [],\n resolvedConfigDirs: [],\n errors: []\n };\n }\n\n // Load configurations from each directory\n const configs: object[] = [];\n const resolvedConfigDirs: DiscoveredConfigDir[] = [];\n const errors: string[] = [];\n\n // Sort by level (highest level first = lowest precedence first)\n const sortedDirs = [...discoveredDirs].sort((a, b) => b.level - a.level);\n\n for (const dir of sortedDirs) {\n try {\n const config = await loadConfigFromDirectory(\n dir.path,\n configFileName,\n encoding,\n logger,\n pathFields,\n resolvePathArray\n );\n\n if (config !== null) {\n configs.push(config);\n resolvedConfigDirs.push(dir);\n logger?.debug(`Loaded config from level ${dir.level}: ${dir.path}`);\n } else {\n logger?.debug(`No valid config found at level ${dir.level}: ${dir.path}`);\n }\n } catch (error: any) {\n const errorMsg = `Failed to load config from ${dir.path}: ${error.message}`;\n errors.push(errorMsg);\n logger?.debug(errorMsg);\n }\n }\n\n // Merge all configurations with proper precedence and configurable array overlap\n const mergedConfig = deepMergeConfigs(configs, fieldOverlaps);\n\n logger?.verbose(`Hierarchical loading complete. Merged ${configs.length} configurations`);\n\n return {\n config: mergedConfig,\n discoveredDirs,\n resolvedConfigDirs,\n errors\n };\n} ","import * as yaml from 'js-yaml';\nimport * as path from 'node:path';\nimport { z, ZodObject } from 'zod';\nimport { Args, ConfigSchema, Options } from './types';\nimport * as Storage from './util/storage';\nimport { loadHierarchicalConfig, DiscoveredConfigDir } from './util/hierarchical';\nimport { normalizePathInput } from './util/path-normalization';\n\n/**\n * Removes undefined values from an object to create a clean configuration.\n * This is used to merge configuration sources while avoiding undefined pollution.\n * \n * @param obj - The object to clean\n * @returns A new object with undefined values filtered out\n */\nfunction clean(obj: any) {\n return Object.fromEntries(\n Object.entries(obj).filter(([_, v]) => v !== undefined)\n );\n}\n\n/**\n * Resolves relative paths in configuration values relative to the configuration file's directory.\n * \n * @param config - The configuration object to process\n * @param configDir - The directory containing the configuration file\n * @param pathFields - Array of field names (using dot notation) that contain paths to be resolved\n * @param resolvePathArray - Array of field names whose array elements should all be resolved as paths\n * @returns The configuration object with resolved paths\n */\nfunction resolveConfigPaths(\n config: any,\n configDir: string,\n pathFields: string[] = [],\n resolvePathArray: string[] = []\n): any {\n if (!config || typeof config !== 'object' || pathFields.length === 0) {\n return config;\n }\n\n const resolvedConfig = { ...config };\n\n for (const fieldPath of pathFields) {\n const value = getNestedValue(resolvedConfig, fieldPath);\n if (value !== undefined) {\n // Step 1: Normalize input (convert file:// URLs, reject http/https)\n const normalizedValue = normalizePathInput(value);\n \n // Step 2: Resolve paths relative to config directory\n const shouldResolveArrayElements = resolvePathArray.includes(fieldPath);\n const resolvedValue = resolvePathValue(normalizedValue, configDir, shouldResolveArrayElements);\n setNestedValue(resolvedConfig, fieldPath, resolvedValue);\n }\n }\n\n return resolvedConfig;\n}\n\n/**\n * Gets a nested value from an object using dot notation.\n */\nfunction getNestedValue(obj: any, path: string): any {\n return path.split('.').reduce((current, key) => current?.[key], obj);\n}\n\n/**\n * Checks if a key is unsafe for prototype pollution prevention.\n */\nfunction isUnsafeKey(key: string): boolean {\n return key === '__proto__' || key === 'constructor' || key === 'prototype';\n}\n\n/**\n * Sets a nested value in an object using dot notation.\n * Prevents prototype pollution by rejecting dangerous property names.\n */\nfunction setNestedValue(obj: any, path: string, value: any): void {\n const keys = path.split('.');\n const lastKey = keys.pop()!;\n\n // Prevent prototype pollution via special property names\n if (isUnsafeKey(lastKey) || keys.some(isUnsafeKey)) {\n return;\n }\n\n const target = keys.reduce((current, key) => {\n // Skip if this is an unsafe key (already checked above, but defensive)\n if (isUnsafeKey(key)) {\n return current;\n }\n if (!(key in current)) {\n current[key] = {};\n }\n return current[key];\n }, obj);\n target[lastKey] = value;\n}\n\n/**\n * Resolves a path value (string, array, or object) relative to the config directory.\n * \n * Handles:\n * - Strings: Resolved relative to configDir\n * - Arrays: Elements resolved if resolveArrayElements is true\n * - Objects: All string values and array elements resolved recursively\n * - Other types: Returned unchanged\n */\nfunction resolvePathValue(value: any, configDir: string, resolveArrayElements: boolean): any {\n if (typeof value === 'string') {\n return resolveSinglePath(value, configDir);\n }\n\n if (Array.isArray(value) && resolveArrayElements) {\n return value.map(item =>\n typeof item === 'string' ? resolveSinglePath(item, configDir) : item\n );\n }\n\n // NEW: Handle objects with string values\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n const resolved: any = {};\n for (const [key, val] of Object.entries(value)) {\n if (typeof val === 'string') {\n resolved[key] = resolveSinglePath(val, configDir);\n } else if (Array.isArray(val)) {\n // Also handle arrays within objects\n resolved[key] = val.map(item =>\n typeof item === 'string' ? resolveSinglePath(item, configDir) : item\n );\n } else {\n // Keep other types unchanged\n resolved[key] = val;\n }\n }\n return resolved;\n }\n\n return value;\n}\n\n/**\n * Resolves a single path string relative to the config directory if it's a relative path.\n */\nfunction resolveSinglePath(pathStr: string, configDir: string): string {\n if (!pathStr || path.isAbsolute(pathStr)) {\n return pathStr;\n }\n\n return path.resolve(configDir, pathStr);\n}\n\n/**\n * Validates and secures a user-provided path to prevent path traversal attacks.\n * \n * Security checks include:\n * - Path traversal prevention (blocks '..')\n * - Absolute path detection\n * - Path separator validation\n * \n * @param userPath - The user-provided path component\n * @param basePath - The base directory to join the path with\n * @returns The safely joined and normalized path\n * @throws {Error} When path traversal or absolute paths are detected\n */\nfunction validatePath(userPath: string, basePath: string): string {\n if (!userPath || !basePath) {\n throw new Error('Invalid path parameters');\n }\n\n const normalized = path.normalize(userPath);\n\n // Prevent path traversal attacks\n if (normalized.includes('..') || path.isAbsolute(normalized)) {\n throw new Error('Invalid path: path traversal detected');\n }\n\n // Ensure the path doesn't start with a path separator\n if (normalized.startsWith('/') || normalized.startsWith('\\\\')) {\n throw new Error('Invalid path: absolute path detected');\n }\n\n return path.join(basePath, normalized);\n}\n\n/**\n * Validates a configuration directory path for security and basic formatting.\n * \n * Performs validation to prevent:\n * - Null byte injection attacks\n * - Extremely long paths that could cause DoS\n * - Empty or invalid directory specifications\n * \n * @param configDir - The configuration directory path to validate\n * @returns The normalized configuration directory path\n * @throws {Error} When the directory path is invalid or potentially dangerous\n */\nfunction validateConfigDirectory(configDir: string): string {\n if (!configDir) {\n throw new Error('Configuration directory is required');\n }\n\n // Check for null bytes which could be used for path injection\n if (configDir.includes('\\0')) {\n throw new Error('Invalid path: null byte detected');\n }\n\n const normalized = path.normalize(configDir);\n\n // Basic validation - could be expanded based on requirements\n if (normalized.length > 1000) {\n throw new Error('Configuration directory path too long');\n }\n\n return normalized;\n}\n\n/**\n * Reads configuration from files and merges it with CLI arguments.\n * \n * This function implements the core configuration loading logic:\n * 1. Validates and resolves the configuration directory path\n * 2. Attempts to read the YAML configuration file\n * 3. Safely parses the YAML content with security protections\n * 4. Merges file configuration with runtime arguments\n * 5. Returns a typed configuration object\n * \n * The function handles missing files gracefully and provides detailed\n * logging for troubleshooting configuration issues.\n * \n * @template T - The Zod schema shape type for configuration validation\n * @param args - Parsed command-line arguments containing potential config overrides\n * @param options - Cardigantime options with defaults, schema, and logger\n * @returns Promise resolving to the merged and typed configuration object\n * @throws {Error} When configuration directory is invalid or required files cannot be read\n * \n * @example\n * ```typescript\n * const config = await read(cliArgs, {\n * defaults: { configDirectory: './config', configFile: 'app.yaml' },\n * configShape: MySchema.shape,\n * logger: console,\n * features: ['config']\n * });\n * // config is fully typed based on your schema\n * ```\n */\nexport const read = async <T extends z.ZodRawShape>(args: Args, options: Options<T>): Promise<z.infer<ZodObject<T & typeof ConfigSchema.shape>>> => {\n const logger = options.logger;\n\n const rawConfigDir = args.configDirectory || options.defaults?.configDirectory;\n if (!rawConfigDir) {\n throw new Error('Configuration directory must be specified');\n }\n\n const resolvedConfigDir = validateConfigDirectory(rawConfigDir);\n logger.verbose('Resolved config directory');\n\n let rawFileConfig: object = {};\n let discoveredConfigDirs: string[] = [];\n let resolvedConfigDirs: string[] = [];\n\n // Check if hierarchical configuration discovery is enabled\n // Use optional chaining for safety although options.features is defaulted\n if (options.features && options.features.includes('hierarchical')) {\n logger.verbose('Hierarchical configuration discovery enabled');\n\n try {\n // Extract the config directory name from the path for hierarchical discovery\n const configDirName = path.basename(resolvedConfigDir);\n const startingDir = path.dirname(resolvedConfigDir);\n\n logger.debug(`Using hierarchical discovery: configDirName=${configDirName}, startingDir=${startingDir}`);\n\n const hierarchicalResult = await loadHierarchicalConfig({\n configDirName,\n configFileName: options.defaults.configFile,\n startingDir,\n encoding: options.defaults.encoding,\n logger,\n pathFields: options.defaults.pathResolution?.pathFields,\n resolvePathArray: options.defaults.pathResolution?.resolvePathArray,\n fieldOverlaps: options.defaults.fieldOverlaps\n });\n\n rawFileConfig = hierarchicalResult.config;\n discoveredConfigDirs = hierarchicalResult.discoveredDirs.map(dir => dir.path);\n resolvedConfigDirs = hierarchicalResult.resolvedConfigDirs.map(dir => dir.path);\n\n if (hierarchicalResult.discoveredDirs.length > 0) {\n logger.verbose(`Hierarchical discovery found ${hierarchicalResult.discoveredDirs.length} configuration directories`);\n hierarchicalResult.discoveredDirs.forEach(dir => {\n logger.debug(` Level ${dir.level}: ${dir.path}`);\n });\n } else {\n logger.verbose('No configuration directories found in hierarchy');\n }\n\n if (hierarchicalResult.resolvedConfigDirs.length > 0) {\n logger.verbose(`Found ${hierarchicalResult.resolvedConfigDirs.length} directories with actual configuration files`);\n hierarchicalResult.resolvedConfigDirs.forEach(dir => {\n logger.debug(` Config dir level ${dir.level}: ${dir.path}`);\n });\n }\n\n if (hierarchicalResult.errors.length > 0) {\n hierarchicalResult.errors.forEach(error => logger.warn(`Hierarchical config warning: ${error}`));\n }\n\n } catch (error: any) {\n logger.error('Hierarchical configuration loading failed: ' + (error.message || 'Unknown error'));\n // Fall back to single directory mode\n logger.verbose('Falling back to single directory configuration loading');\n rawFileConfig = await loadSingleDirectoryConfig(resolvedConfigDir, options, logger);\n\n // Include the directory in both arrays (discovered but check if it had config)\n discoveredConfigDirs = [resolvedConfigDir];\n if (rawFileConfig && Object.keys(rawFileConfig).length > 0) {\n resolvedConfigDirs = [resolvedConfigDir];\n } else {\n resolvedConfigDirs = [];\n }\n }\n } else {\n // Use traditional single directory configuration loading\n logger.verbose('Using single directory configuration loading');\n rawFileConfig = await loadSingleDirectoryConfig(resolvedConfigDir, options, logger);\n\n // Include the directory in discovered, and in resolved only if it had config\n discoveredConfigDirs = [resolvedConfigDir];\n if (rawFileConfig && Object.keys(rawFileConfig).length > 0) {\n resolvedConfigDirs = [resolvedConfigDir];\n } else {\n resolvedConfigDirs = [];\n }\n }\n\n // Apply path resolution if configured\n let processedConfig = rawFileConfig;\n if (options.defaults.pathResolution?.pathFields) {\n processedConfig = resolveConfigPaths(\n rawFileConfig,\n resolvedConfigDir,\n options.defaults.pathResolution.pathFields,\n options.defaults.pathResolution.resolvePathArray || []\n );\n }\n\n const config: z.infer<ZodObject<T & typeof ConfigSchema.shape>> = clean({\n ...processedConfig,\n ...{\n configDirectory: resolvedConfigDir,\n discoveredConfigDirs,\n resolvedConfigDirs,\n }\n }) as z.infer<ZodObject<T & typeof ConfigSchema.shape>>;\n\n return config;\n}\n\n/**\n * Tries to find a config file with alternative extensions (.yaml or .yml).\n * \n * @param storage Storage instance to use for file operations\n * @param configDir The directory containing the config file\n * @param configFileName The base config file name (may have .yaml or .yml extension)\n * @param logger Logger for debugging\n * @returns Promise resolving to the found config file path or null if not found\n */\nasync function findConfigFileWithExtension(\n storage: any,\n configDir: string,\n configFileName: string,\n logger: any\n): Promise<string | null> {\n // Validate the config file name to prevent path traversal\n const configFilePath = validatePath(configFileName, configDir);\n \n // First try the exact filename as specified\n const exists = await storage.exists(configFilePath);\n if (exists) {\n const isReadable = await storage.isFileReadable(configFilePath);\n if (isReadable) {\n return configFilePath;\n }\n }\n \n // If the exact filename doesn't exist or isn't readable, try alternative extensions\n // Only do this if the filename has a .yaml or .yml extension\n const ext = path.extname(configFileName);\n if (ext === '.yaml' || ext === '.yml') {\n const baseName = path.basename(configFileName, ext);\n const alternativeExt = ext === '.yaml' ? '.yml' : '.yaml';\n const alternativeFileName = baseName + alternativeExt;\n const alternativePath = validatePath(alternativeFileName, configDir);\n \n logger.debug(`Config file not found at ${configFilePath}, trying alternative: ${alternativePath}`);\n \n const altExists = await storage.exists(alternativePath);\n if (altExists) {\n const altIsReadable = await storage.isFileReadable(alternativePath);\n if (altIsReadable) {\n logger.debug(`Found config file with alternative extension: ${alternativePath}`);\n return alternativePath;\n }\n }\n }\n \n return null;\n}\n\n/**\n * Loads configuration from a single directory (traditional mode).\n * \n * @param resolvedConfigDir - The resolved configuration directory path\n * @param options - Cardigantime options\n * @param logger - Logger instance\n * @returns Promise resolving to the configuration object\n */\nasync function loadSingleDirectoryConfig<T extends z.ZodRawShape>(\n resolvedConfigDir: string,\n options: Options<T>,\n logger: any\n): Promise<object> {\n const storage = Storage.create({ log: logger.debug });\n logger.verbose('Attempting to load config file for cardigantime');\n\n let rawFileConfig: object = {};\n\n try {\n // Try to find the config file with alternative extensions\n const configFilePath = await findConfigFileWithExtension(\n storage,\n resolvedConfigDir,\n options.defaults.configFile,\n logger\n );\n \n if (!configFilePath) {\n logger.verbose('Configuration file not found. Using empty configuration.');\n return rawFileConfig;\n }\n\n const yamlContent = await storage.readFile(configFilePath, options.defaults.encoding);\n\n // SECURITY FIX: Use safer parsing options to prevent code execution vulnerabilities\n const parsedYaml = yaml.load(yamlContent);\n\n if (parsedYaml !== null && typeof parsedYaml === 'object') {\n rawFileConfig = parsedYaml;\n logger.verbose('Loaded configuration file successfully');\n } else if (parsedYaml !== null) {\n logger.warn('Ignoring invalid configuration format. Expected an object, got ' + typeof parsedYaml);\n }\n } catch (error: any) {\n // Re-throw security-related errors (path validation failures)\n if (error.message && /Invalid path|path traversal|absolute path/i.test(error.message)) {\n throw error;\n }\n \n if (error.code === 'ENOENT' || /not found|no such file/i.test(error.message)) {\n logger.verbose('Configuration file not found. Using empty configuration.');\n } else {\n // SECURITY FIX: Don't expose internal paths or detailed error information\n logger.error('Failed to load or parse configuration file: ' + (error.message || 'Unknown error'));\n }\n }\n\n return rawFileConfig;\n}\n\n/**\n * Represents a configuration value with its source information.\n */\ninterface ConfigSourceInfo {\n /** The configuration value */\n value: any;\n /** Path to the configuration file that provided this value */\n sourcePath: string;\n /** Hierarchical level (0 = closest/highest precedence) */\n level: number;\n /** Short description of the source for display */\n sourceLabel: string;\n}\n\n/**\n * Tracks configuration values to their sources during hierarchical loading.\n */\ninterface ConfigSourceTracker {\n [key: string]: ConfigSourceInfo;\n}\n\n/**\n * Recursively tracks the source of configuration values from hierarchical loading.\n * \n * @param config - The configuration object to track\n * @param sourcePath - Path to the configuration file\n * @param level - Hierarchical level\n * @param prefix - Current object path prefix for nested values\n * @param tracker - The tracker object to populate\n */\nfunction trackConfigSources(\n config: any,\n sourcePath: string,\n level: number,\n prefix: string = '',\n tracker: ConfigSourceTracker = {}\n): ConfigSourceTracker {\n if (!config || typeof config !== 'object' || Array.isArray(config)) {\n // For primitives and arrays, track the entire value\n tracker[prefix] = {\n value: config,\n sourcePath,\n level,\n sourceLabel: `Level ${level}: ${path.basename(path.dirname(sourcePath))}`\n };\n return tracker;\n }\n\n // For objects, recursively track each property\n for (const [key, value] of Object.entries(config)) {\n const fieldPath = prefix ? `${prefix}.${key}` : key;\n trackConfigSources(value, sourcePath, level, fieldPath, tracker);\n }\n\n return tracker;\n}\n\n/**\n * Merges multiple configuration source trackers with proper precedence.\n * Lower level numbers have higher precedence.\n * \n * @param trackers - Array of trackers from different config sources\n * @returns Merged tracker with proper precedence\n */\nfunction mergeConfigTrackers(trackers: ConfigSourceTracker[]): ConfigSourceTracker {\n const merged: ConfigSourceTracker = {};\n\n for (const tracker of trackers) {\n for (const [key, info] of Object.entries(tracker)) {\n // Only update if we don't have this key yet, or if this source has higher precedence (lower level)\n if (!merged[key] || info.level < merged[key].level) {\n merged[key] = info;\n }\n }\n }\n\n return merged;\n}\n\n/**\n * Formats a configuration value for display, handling different types appropriately.\n * \n * @param value - The configuration value to format\n * @returns Formatted string representation\n */\nfunction formatConfigValue(value: any): string {\n if (value === null) return 'null';\n if (value === undefined) return 'undefined';\n if (typeof value === 'string') return `\"${value}\"`;\n if (typeof value === 'boolean') return value.toString();\n if (typeof value === 'number') return value.toString();\n if (Array.isArray(value)) {\n if (value.length === 0) return '[]';\n if (value.length <= 3) {\n return `[${value.map(formatConfigValue).join(', ')}]`;\n }\n return `[${value.slice(0, 2).map(formatConfigValue).join(', ')}, ... (${value.length} items)]`;\n }\n if (typeof value === 'object') {\n const keys = Object.keys(value);\n if (keys.length === 0) return '{}';\n if (keys.length <= 2) {\n return `{${keys.slice(0, 2).join(', ')}}`;\n }\n return `{${keys.slice(0, 2).join(', ')}, ... (${keys.length} keys)}`;\n }\n return String(value);\n}\n\n/**\n * Displays configuration with source tracking in a git blame-like format.\n * \n * @param config - The resolved configuration object\n * @param tracker - Configuration source tracker\n * @param discoveredDirs - Array of discovered configuration directories\n * @param logger - Logger instance for output\n */\nfunction displayConfigWithSources(\n config: any,\n tracker: ConfigSourceTracker,\n discoveredDirs: DiscoveredConfigDir[],\n logger: any\n): void {\n logger.info('\\n' + '='.repeat(80));\n logger.info('CONFIGURATION SOURCE ANALYSIS');\n logger.info('='.repeat(80));\n\n // Display discovered configuration hierarchy\n logger.info('\\nDISCOVERED CONFIGURATION HIERARCHY:');\n if (discoveredDirs.length === 0) {\n logger.info(' No configuration directories found in hierarchy');\n } else {\n discoveredDirs\n .sort((a, b) => a.level - b.level) // Sort by precedence (lower level = higher precedence)\n .forEach(dir => {\n const precedence = dir.level === 0 ? '(highest precedence)' :\n dir.level === Math.max(...discoveredDirs.map(d => d.level)) ? '(lowest precedence)' :\n '';\n logger.info(` Level ${dir.level}: ${dir.path} ${precedence}`);\n });\n }\n\n // Display resolved configuration with sources\n logger.info('\\nRESOLVED CONFIGURATION WITH SOURCES:');\n logger.info('Format: [Source] key: value\\n');\n\n const sortedKeys = Object.keys(tracker).sort();\n const maxKeyLength = Math.max(...sortedKeys.map(k => k.length), 20);\n const maxSourceLength = Math.max(...Object.values(tracker).map(info => info.sourceLabel.length), 25);\n\n for (const key of sortedKeys) {\n const info = tracker[key];\n const paddedKey = key.padEnd(maxKeyLength);\n const paddedSource = info.sourceLabel.padEnd(maxSourceLength);\n const formattedValue = formatConfigValue(info.value);\n\n logger.info(`[${paddedSource}] ${paddedKey}: ${formattedValue}`);\n }\n\n // Display summary\n logger.info('\\n' + '-'.repeat(80));\n logger.info('SUMMARY:');\n logger.info(` Total configuration keys: ${Object.keys(tracker).length}`);\n logger.info(` Configuration sources: ${discoveredDirs.length}`);\n\n // Count values by source\n const sourceCount: { [source: string]: number } = {};\n for (const info of Object.values(tracker)) {\n sourceCount[info.sourceLabel] = (sourceCount[info.sourceLabel] || 0) + 1;\n }\n\n logger.info(' Values by source:');\n for (const [source, count] of Object.entries(sourceCount)) {\n logger.info(` ${source}: ${count} value(s)`);\n }\n\n logger.info('='.repeat(80));\n}\n\n/**\n * Checks and displays the resolved configuration with detailed source tracking.\n * \n * This function provides a git blame-like view of configuration resolution,\n * showing which file and hierarchical level contributed each configuration value.\n * \n * @template T - The Zod schema shape type for configuration validation\n * @param args - Parsed command-line arguments\n * @param options - Cardigantime options with defaults, schema, and logger\n * @returns Promise that resolves when the configuration check is complete\n * \n * @example\n * ```typescript\n * await checkConfig(cliArgs, {\n * defaults: { configDirectory: './config', configFile: 'app.yaml' },\n * configShape: MySchema.shape,\n * logger: console,\n * features: ['config', 'hierarchical']\n * });\n * // Outputs detailed configuration source analysis\n * ```\n */\nexport const checkConfig = async <T extends z.ZodRawShape>(\n args: Args,\n options: Options<T>\n): Promise<void> => {\n const logger = options.logger;\n\n logger.info('Starting configuration check...');\n\n const rawConfigDir = args.configDirectory || options.defaults?.configDirectory;\n if (!rawConfigDir) {\n throw new Error('Configuration directory must be specified');\n }\n\n const resolvedConfigDir = validateConfigDirectory(rawConfigDir);\n logger.verbose(`Resolved config directory: ${resolvedConfigDir}`);\n\n let rawFileConfig: object = {};\n let discoveredDirs: DiscoveredConfigDir[] = [];\n let resolvedConfigDirs: DiscoveredConfigDir[] = [];\n let tracker: ConfigSourceTracker = {};\n\n // Check if hierarchical configuration discovery is enabled\n // Use optional chaining for safety although options.features is defaulted\n if (options.features && options.features.includes('hierarchical')) {\n logger.verbose('Using hierarchical configuration discovery for source tracking');\n\n try {\n // Extract the config directory name from the path for hierarchical discovery\n const configDirName = path.basename(resolvedConfigDir);\n const startingDir = path.dirname(resolvedConfigDir);\n\n logger.debug(`Using hierarchical discovery: configDirName=${configDirName}, startingDir=${startingDir}`);\n\n const hierarchicalResult = await loadHierarchicalConfig({\n configDirName,\n configFileName: options.defaults.configFile,\n startingDir,\n encoding: options.defaults.encoding,\n logger,\n pathFields: options.defaults.pathResolution?.pathFields,\n resolvePathArray: options.defaults.pathResolution?.resolvePathArray,\n fieldOverlaps: options.defaults.fieldOverlaps\n });\n\n rawFileConfig = hierarchicalResult.config;\n discoveredDirs = hierarchicalResult.discoveredDirs;\n resolvedConfigDirs = hierarchicalResult.resolvedConfigDirs;\n\n // Build detailed source tracking by re-loading each config individually\n const trackers: ConfigSourceTracker[] = [];\n\n // Sort by level (highest level first = lowest precedence first) to match merge order\n const sortedDirs = [...resolvedConfigDirs].sort((a, b) => b.level - a.level);\n\n for (const dir of sortedDirs) {\n const storage = Storage.create({ log: logger.debug });\n const configFilePath = path.join(dir.path, options.defaults.configFile);\n\n try {\n const exists = await storage.exists(configFilePath);\n if (!exists) continue;\n\n const isReadable = await storage.isFileReadable(configFilePath);\n if (!isReadable) continue;\n\n const yamlContent = await storage.readFile(configFilePath, options.defaults.encoding);\n const parsedYaml = yaml.load(yamlContent);\n\n if (parsedYaml !== null && typeof parsedYaml === 'object') {\n const levelTracker = trackConfigSources(parsedYaml, configFilePath, dir.level);\n trackers.push(levelTracker);\n }\n } catch (error: any) {\n logger.debug(`Error loading config for source tracking from ${configFilePath}: ${error.message}`);\n }\n }\n\n // Merge trackers with proper precedence\n tracker = mergeConfigTrackers(trackers);\n\n if (hierarchicalResult.errors.length > 0) {\n logger.warn('Configuration loading warnings:');\n hierarchicalResult.errors.forEach(error => logger.warn(` ${error}`));\n }\n\n } catch (error: any) {\n logger.error('Hierarchical configuration loading failed: ' + (error.message || 'Unknown error'));\n logger.verbose('Falling back to single directory configuration loading');\n\n // Fall back to single directory mode for source tracking\n rawFileConfig = await loadSingleDirectoryConfig(resolvedConfigDir, options, logger);\n const configFilePath = path.join(resolvedConfigDir, options.defaults.configFile);\n tracker = trackConfigSources(rawFileConfig, configFilePath, 0);\n\n // Include the directory in discovered, and in resolved only if it had config\n discoveredDirs = [{\n path: resolvedConfigDir,\n level: 0\n }];\n if (rawFileConfig && Object.keys(rawFileConfig).length > 0) {\n resolvedConfigDirs = [{\n path: resolvedConfigDir,\n level: 0\n }];\n } else {\n resolvedConfigDirs = [];\n }\n }\n } else {\n // Use traditional single directory configuration loading\n logger.verbose('Using single directory configuration loading for source tracking');\n rawFileConfig = await loadSingleDirectoryConfig(resolvedConfigDir, options, logger);\n const configFilePath = path.join(resolvedConfigDir, options.defaults.configFile);\n tracker = trackConfigSources(rawFileConfig, configFilePath, 0);\n\n // Include the directory in discovered, and in resolved only if it had config\n discoveredDirs = [{\n path: resolvedConfigDir,\n level: 0\n }];\n if (rawFileConfig && Object.keys(rawFileConfig).length > 0) {\n resolvedConfigDirs = [{\n path: resolvedConfigDir,\n level: 0\n }];\n } else {\n resolvedConfigDirs = [];\n }\n }\n\n // Apply path resolution if configured (this doesn't change source tracking)\n let processedConfig = rawFileConfig;\n if (options.defaults.pathResolution?.pathFields) {\n processedConfig = resolveConfigPaths(\n rawFileConfig,\n resolvedConfigDir,\n options.defaults.pathResolution.pathFields,\n options.defaults.pathResolution.resolvePathArray || []\n );\n }\n\n // Build final configuration including built-in values\n const finalConfig = clean({\n ...processedConfig,\n configDirectory: resolvedConfigDir,\n discoveredConfigDirs: discoveredDirs.map(dir => dir.path),\n resolvedConfigDirs: resolvedConfigDirs.map(dir => dir.path),\n });\n\n // Add built-in configuration to tracker\n tracker['configDirectory'] = {\n value: resolvedConfigDir,\n sourcePath: 'built-in',\n level: -1,\n sourceLabel: 'Built-in (runtime)'\n };\n\n tracker['discoveredConfigDirs'] = {\n value: discoveredDirs.map(dir => dir.path),\n sourcePath: 'built-in',\n level: -1,\n sourceLabel: 'Built-in (runtime)'\n };\n\n tracker['resolvedConfigDirs'] = {\n value: resolvedConfigDirs.map(dir => dir.path),\n sourcePath: 'built-in',\n level: -1,\n sourceLabel: 'Built-in (runtime)'\n };\n\n // Display the configuration with source information\n displayConfigWithSources(finalConfig, tracker, discoveredDirs, logger);\n};","/**\n * Error thrown when configuration validation fails\n */\nexport class ConfigurationError extends Error {\n public readonly errorType: 'validation' | 'schema' | 'extra_keys';\n public readonly details?: any;\n public readonly configPath?: string;\n\n constructor(\n errorType: 'validation' | 'schema' | 'extra_keys',\n message: string,\n details?: any,\n configPath?: string\n ) {\n super(message);\n this.name = 'ConfigurationError';\n this.errorType = errorType;\n this.details = details;\n this.configPath = configPath;\n }\n\n /**\n * Creates a validation error for when config doesn't match the schema\n */\n static validation(message: string, zodError?: any, configPath?: string): ConfigurationError {\n return new ConfigurationError('validation', message, zodError, configPath);\n }\n\n /**\n * Creates an error for when extra/unknown keys are found\n */\n static extraKeys(extraKeys: string[], allowedKeys: string[], configPath?: string): ConfigurationError {\n const message = `Unknown configuration keys found: ${extraKeys.join(', ')}. Allowed keys are: ${allowedKeys.join(', ')}`;\n return new ConfigurationError('extra_keys', message, { extraKeys, allowedKeys }, configPath);\n }\n\n /**\n * Creates a schema error for when the configuration schema itself is invalid\n */\n static schema(message: string, details?: any): ConfigurationError {\n return new ConfigurationError('schema', message, details);\n }\n} ","import { Command } from \"commander\";\nimport { ZodObject } from \"zod\";\n\nimport { z } from \"zod\";\nimport { SecurityValidationConfig } from \"./security/types\";\n\n// Re-export MCP types for convenience\nexport type {\n MCPConfigSource,\n FileConfigSource,\n ConfigSource,\n ResolvedConfig,\n MCPInvocationContext,\n} from \"./mcp/types\";\n\n/**\n * Available features that can be enabled in Cardigantime.\n * Currently supports:\n * - 'config': Configuration file reading and validation\n * - 'hierarchical': Hierarchical configuration discovery and layering\n */\nexport type Feature = 'config' | 'hierarchical';\n\n/**\n * Supported configuration file formats.\n * \n * - 'yaml': YAML format (.yaml, .yml)\n * - 'json': JSON format (.json)\n * - 'javascript': JavaScript module (.js, .mjs, .cjs)\n * - 'typescript': TypeScript module (.ts, .mts, .cts)\n */\nexport enum ConfigFormat {\n YAML = 'yaml',\n JSON = 'json',\n JavaScript = 'javascript',\n TypeScript = 'typescript'\n}\n\n/**\n * Interface for format-specific configuration parsers.\n * Each parser is responsible for loading and parsing configuration from a specific format.\n * \n * @template T - The type of the parsed configuration object\n */\nexport interface ConfigParser<T = unknown> {\n /** The format this parser handles */\n format: ConfigFormat;\n /** File extensions this parser supports (e.g., ['.yaml', '.yml']) */\n extensions: string[];\n /** \n * Parses configuration content from a file.\n * \n * @param content - The raw file content as a string\n * @param filePath - The absolute path to the configuration file\n * @returns Promise resolving to the parsed configuration object\n * @throws {Error} When parsing fails or content is invalid\n */\n parse(content: string, filePath: string): Promise<T>;\n}\n\n/**\n * Metadata about where a configuration value came from.\n * Used for tracking configuration sources and debugging.\n * \n * @deprecated Use FileConfigSource from ./mcp/types instead.\n * This type is kept for backward compatibility and will be removed in a future version.\n */\nexport interface LegacyConfigSource {\n /** The format of the configuration file */\n format: ConfigFormat;\n /** Absolute path to the configuration file */\n filePath: string;\n /** The parsed configuration content */\n content: unknown;\n /** Timestamp when the configuration was loaded */\n loadedAt: Date;\n}\n\n/**\n * Defines how array fields should be merged in hierarchical configurations.\n * \n * - 'override': Higher precedence arrays completely replace lower precedence arrays (default)\n * - 'append': Higher precedence array elements are appended to lower precedence arrays\n * - 'prepend': Higher precedence array elements are prepended to lower precedence arrays\n */\nexport type ArrayOverlapMode = 'override' | 'append' | 'prepend';\n\n/**\n * Configuration for how fields should be merged in hierarchical configurations.\n * Maps field names (using dot notation) to their overlap behavior.\n * \n * @example\n * ```typescript\n * const fieldOverlaps: FieldOverlapOptions = {\n * 'features': 'append', // features arrays will be combined by appending\n * 'api.endpoints': 'prepend', // nested endpoint arrays will be combined by prepending\n * 'excludePatterns': 'override' // excludePatterns arrays will replace each other (default behavior)\n * };\n * ```\n */\nexport interface FieldOverlapOptions {\n [fieldPath: string]: ArrayOverlapMode;\n}\n\n/**\n * Configuration for resolving relative paths in configuration values.\n * Paths specified in these fields will be resolved relative to the configuration file's directory.\n */\nexport interface PathResolutionOptions {\n /** Array of field names (using dot notation) that contain paths to be resolved */\n pathFields?: string[];\n /** Array of field names whose array elements should all be resolved as paths */\n resolvePathArray?: string[];\n /** \n * Whether to validate that resolved paths exist on the filesystem\n * @default false\n */\n validateExists?: boolean;\n /**\n * Whether to warn about config values that look like paths but aren't in pathFields\n * Looks for values containing './' or '../' that might be unresolved paths\n * @default true\n */\n warnUnmarkedPaths?: boolean;\n}\n\n/**\n * Default configuration options for Cardigantime.\n * These define the basic behavior of configuration loading.\n */\nexport interface DefaultOptions {\n /** Directory path where configuration files are located */\n configDirectory: string;\n /** Name of the configuration file (e.g., 'config.yaml', 'app.yml') */\n configFile: string;\n /** Whether the configuration directory must exist. If true, throws error if directory doesn't exist */\n isRequired: boolean;\n /** File encoding for reading configuration files (e.g., 'utf8', 'ascii') */\n encoding: string;\n /** Configuration for resolving relative paths in configuration values */\n pathResolution?: PathResolutionOptions;\n /** \n * Configuration for how array fields should be merged in hierarchical mode.\n * Only applies when the 'hierarchical' feature is enabled.\n * If not specified, all arrays use 'override' behavior (default).\n */\n fieldOverlaps?: FieldOverlapOptions;\n /** \n * Security validation configuration (optional, uses development profile by default).\n * Enable security features to validate CLI arguments and config file values.\n */\n security?: Partial<SecurityValidationConfig>;\n /**\n * Optional source metadata for tracking where configuration came from.\n * Populated automatically when configuration is loaded.\n * \n * @deprecated Use the new ConfigSource union type from ./mcp/types instead.\n */\n source?: LegacyConfigSource;\n /**\n * Allow executable configuration files (JavaScript/TypeScript).\n * \n * **SECURITY WARNING**: Executable configs run with full Node.js permissions\n * in the same process as your application. Only enable this if you trust\n * the configuration files being loaded.\n * \n * When disabled (default), JavaScript and TypeScript config files will be\n * ignored with a warning message.\n * \n * @default false\n */\n allowExecutableConfig?: boolean;\n}\n\n/**\n * Complete options object passed to Cardigantime functions.\n * Combines defaults, features, schema shape, and logger.\n * \n * @template T - The Zod schema shape type for configuration validation\n */\nexport interface Options<T extends z.ZodRawShape> {\n /** Default configuration options */\n defaults: DefaultOptions,\n /** Array of enabled features */\n features: Feature[],\n /** Zod schema shape for validating user configuration */\n configShape: T;\n /** Logger instance for debugging and error reporting */\n logger: Logger;\n}\n\n/**\n * Logger interface for Cardigantime's internal logging.\n * Compatible with popular logging libraries like Winston, Bunyan, etc.\n */\nexport interface Logger {\n /** Debug-level logging for detailed troubleshooting information */\n debug: (message: string, ...args: any[]) => void;\n /** Info-level logging for general information */\n info: (message: string, ...args: any[]) => void;\n /** Warning-level logging for non-critical issues */\n warn: (message: string, ...args: any[]) => void;\n /** Error-level logging for critical problems */\n error: (message: string, ...args: any[]) => void;\n /** Verbose-level logging for extensive detail */\n verbose: (message: string, ...args: any[]) => void;\n /** Silly-level logging for maximum detail */\n silly: (message: string, ...args: any[]) => void;\n}\n\n/**\n * Main Cardigantime interface providing configuration management functionality.\n * \n * @template T - The Zod schema shape type for configuration validation\n */\nexport interface Cardigantime<T extends z.ZodRawShape> {\n /** \n * Adds Cardigantime's CLI options to a Commander.js command.\n * This includes options like --config-directory for runtime config path overrides.\n */\n configure: (command: Command) => Promise<Command>;\n /** Sets a custom logger for debugging and error reporting */\n setLogger: (logger: Logger) => void;\n /** \n * Reads configuration from files and merges with CLI arguments.\n * Returns a fully typed configuration object.\n */\n read: (args: Args) => Promise<z.infer<ZodObject<T & typeof ConfigSchema.shape>>>;\n /** \n * Validates the merged configuration against the Zod schema.\n * Throws ConfigurationError if validation fails.\n */\n validate: (config: z.infer<ZodObject<T & typeof ConfigSchema.shape>>) => Promise<void>;\n /** \n * Generates a configuration file with default values in the specified directory.\n * Creates the directory if it doesn't exist and writes a config file with all default values populated.\n */\n generateConfig: (configDirectory?: string) => Promise<void>;\n /** \n * Checks and displays the resolved configuration with detailed source tracking.\n * Shows which file and hierarchical level contributed each configuration value in a git blame-like format.\n */\n checkConfig: (args: Args) => Promise<void>;\n}\n\n/**\n * Parsed command-line arguments object, typically from Commander.js opts().\n * Keys correspond to CLI option names with values from user input.\n */\nexport interface Args {\n [key: string]: any;\n}\n\n/**\n * Base Zod schema for core Cardigantime configuration.\n * Contains the minimum required configuration fields.\n */\nexport const ConfigSchema = z.object({\n /** The resolved configuration directory path */\n configDirectory: z.string(),\n /** Array of all directory paths that were discovered during hierarchical search */\n discoveredConfigDirs: z.array(z.string()),\n /** Array of directory paths that actually contained valid configuration files */\n resolvedConfigDirs: z.array(z.string()),\n});\n\n/**\n * Base configuration type derived from the core schema.\n */\nexport type Config = z.infer<typeof ConfigSchema>;\n\n// ============================================================================\n// Configuration Discovery Types\n// ============================================================================\n\n/**\n * Defines a configuration file naming pattern.\n * Used to discover configuration files in various standard locations.\n * \n * Patterns support placeholders:\n * - `{app}` - The application name (e.g., 'protokoll', 'myapp')\n * - `{ext}` - The file extension (e.g., 'yaml', 'json', 'ts')\n * \n * @example\n * ```typescript\n * // Pattern: \"{app}.config.{ext}\" with app=\"myapp\" and ext=\"yaml\"\n * // Results in: \"myapp.config.yaml\"\n * \n * const pattern: ConfigNamingPattern = {\n * pattern: '{app}.config.{ext}',\n * priority: 1,\n * hidden: false\n * };\n * ```\n */\nexport interface ConfigNamingPattern {\n /**\n * Pattern template with `{app}` and `{ext}` placeholders.\n * \n * Examples:\n * - `\"{app}.config.{ext}\"` → `\"protokoll.config.yaml\"`\n * - `\".{app}/config.{ext}\"` → `\".protokoll/config.yaml\"`\n * - `\".{app}rc.{ext}\"` → `\".protokollrc.json\"`\n * - `\".{app}rc\"` → `\".protokollrc\"` (no extension)\n */\n pattern: string;\n\n /**\n * Search priority (lower number = checked first).\n * When multiple config files exist, lower priority patterns take precedence.\n */\n priority: number;\n\n /**\n * Whether this pattern results in a hidden file or directory.\n * Hidden patterns start with a dot (e.g., `.myapp/`, `.myapprc`).\n */\n hidden: boolean;\n}\n\n/**\n * Options for configuring how configuration files are discovered.\n * \n * @example\n * ```typescript\n * const options: ConfigDiscoveryOptions = {\n * appName: 'myapp',\n * extensions: ['yaml', 'yml', 'json'],\n * searchHidden: true,\n * // Use custom patterns instead of defaults\n * patterns: [\n * { pattern: '{app}.config.{ext}', priority: 1, hidden: false }\n * ]\n * };\n * ```\n */\nexport interface ConfigDiscoveryOptions {\n /**\n * The application name used in pattern expansion.\n * This value replaces `{app}` placeholders in naming patterns.\n */\n appName: string;\n\n /**\n * Custom naming patterns to use for discovery.\n * If not provided, uses the standard patterns defined in STANDARD_PATTERNS.\n */\n patterns?: ConfigNamingPattern[];\n\n /**\n * File extensions to search for.\n * These replace the `{ext}` placeholder in patterns.\n * If not provided, defaults to supported format extensions.\n * \n * @example ['yaml', 'yml', 'json', 'js', 'ts']\n */\n extensions?: string[];\n\n /**\n * Whether to search for hidden files and directories.\n * When false, patterns with `hidden: true` are skipped.\n * \n * @default true\n */\n searchHidden?: boolean;\n\n /**\n * Whether to check for multiple config files and emit a warning.\n * When enabled, discovery continues after finding the first match\n * to detect and warn about additional config files that would be ignored.\n * \n * @default true\n */\n warnOnMultipleConfigs?: boolean;\n}\n\n/**\n * Result of discovering a configuration file.\n * Contains the file path and the pattern that matched.\n */\nexport interface DiscoveredConfig {\n /**\n * The resolved file path to the configuration file.\n * Can be a file path (e.g., 'app.config.yaml') or include\n * a directory (e.g., '.app/config.yaml').\n */\n path: string;\n\n /**\n * The absolute path to the configuration file.\n */\n absolutePath: string;\n\n /**\n * The pattern that matched this configuration file.\n */\n pattern: ConfigNamingPattern;\n}\n\n/**\n * Warning information when multiple config files are found.\n * This helps users identify and remove unused config files.\n */\nexport interface MultipleConfigWarning {\n /**\n * The configuration that will be used (highest priority).\n */\n used: DiscoveredConfig;\n\n /**\n * Configurations that were found but will be ignored.\n */\n ignored: DiscoveredConfig[];\n}\n\n/**\n * Full result of configuration discovery, including warnings.\n */\nexport interface DiscoveryResult {\n /**\n * The discovered configuration file, or null if none found.\n */\n config: DiscoveredConfig | null;\n\n /**\n * Warning about multiple config files, if any were found.\n */\n multipleConfigWarning?: MultipleConfigWarning;\n}\n\n// ============================================================================\n// Hierarchical Configuration Types\n// ============================================================================\n\n/**\n * Controls how hierarchical configuration lookup behaves.\n * \n * - `'enabled'` - Walk up the directory tree and merge configs (default behavior).\n * Configurations from parent directories are merged with child configurations,\n * with child values taking precedence.\n * \n * - `'disabled'` - Use only the config found in the starting directory.\n * No parent directory traversal occurs. Useful for isolated projects or\n * MCP configurations that should be self-contained.\n * \n * - `'root-only'` - Walk up to find the first config, but don't merge with others.\n * This mode finds the \"closest\" config file without merging parent configs.\n * Useful when you want automatic config discovery but not inheritance.\n * \n * - `'explicit'` - Only merge configs that are explicitly referenced.\n * The base config can specify which parent configs to extend via an\n * `extends` field. No automatic directory traversal.\n * \n * @example\n * ```typescript\n * // In a child config that wants to be isolated:\n * // protokoll.config.yaml\n * hierarchical:\n * mode: disabled\n * \n * // This config will NOT inherit from parent directories\n * ```\n */\nexport type HierarchicalMode = 'enabled' | 'disabled' | 'root-only' | 'explicit';\n\n/**\n * Files or directories that indicate a project root.\n * When encountered during directory traversal, hierarchical lookup stops.\n * \n * @example\n * ```typescript\n * const markers: RootMarker[] = [\n * { type: 'file', name: 'package.json' },\n * { type: 'directory', name: '.git' },\n * { type: 'file', name: 'pnpm-workspace.yaml' },\n * ];\n * ```\n */\nexport interface RootMarker {\n /** Type of the marker */\n type: 'file' | 'directory';\n /** Name of the file or directory that indicates a root */\n name: string;\n}\n\n/**\n * Default root markers used when none are specified.\n * These indicate common project root boundaries.\n */\nexport const DEFAULT_ROOT_MARKERS: RootMarker[] = [\n { type: 'file', name: 'package.json' },\n { type: 'directory', name: '.git' },\n { type: 'file', name: 'pnpm-workspace.yaml' },\n { type: 'file', name: 'lerna.json' },\n { type: 'file', name: 'nx.json' },\n { type: 'file', name: 'rush.json' },\n];\n\n/**\n * Configuration options for hierarchical config behavior.\n * Can be set in the configuration file or programmatically.\n * \n * @example\n * ```typescript\n * // Configuration file (protokoll.config.yaml):\n * hierarchical:\n * mode: enabled\n * maxDepth: 5\n * stopAt:\n * - node_modules\n * - vendor\n * rootMarkers:\n * - type: file\n * name: package.json\n * ```\n * \n * @example\n * ```typescript\n * // Programmatic configuration:\n * const options: HierarchicalOptions = {\n * mode: 'disabled', // No parent config merging\n * };\n * \n * // For MCP servers:\n * const mcpOptions: HierarchicalOptions = {\n * mode: 'root-only',\n * rootMarkers: [{ type: 'file', name: 'mcp.json' }],\n * };\n * ```\n */\nexport interface HierarchicalOptions {\n /**\n * The hierarchical lookup mode.\n * Controls whether and how parent directories are searched.\n * \n * @default 'enabled'\n */\n mode?: HierarchicalMode;\n\n /**\n * Maximum number of parent directories to traverse.\n * Prevents unbounded traversal in deep directory structures.\n * \n * @default 10\n */\n maxDepth?: number;\n\n /**\n * Directory names where traversal should stop.\n * When a directory with one of these names is encountered as a parent,\n * traversal stops even if no config was found.\n * \n * @example ['node_modules', 'vendor', '.cache']\n */\n stopAt?: string[];\n\n /**\n * Files or directories that indicate a project root.\n * When a directory contains one of these markers, it's treated as a root\n * and traversal stops after processing that directory.\n * \n * If not specified, uses DEFAULT_ROOT_MARKERS.\n * Set to empty array to disable root marker detection.\n */\n rootMarkers?: RootMarker[];\n\n /**\n * Whether to stop at the first root marker found.\n * When true, traversal stops immediately when a root marker is found.\n * When false, the directory with the root marker is included but no further.\n * \n * @default true\n */\n stopAtRoot?: boolean;\n}\n\n// ============================================================================\n// Directory Traversal Security Types\n// ============================================================================\n\n/**\n * Defines security boundaries for directory traversal.\n * Used to prevent configuration lookup from accessing sensitive directories.\n * \n * @example\n * ```typescript\n * const boundaries: TraversalBoundary = {\n * forbidden: ['/etc', '/usr', '/var'],\n * boundaries: [process.env.HOME ?? '/home'],\n * maxAbsoluteDepth: 20,\n * maxRelativeDepth: 10,\n * };\n * ```\n */\nexport interface TraversalBoundary {\n /**\n * Directories that are never allowed to be accessed.\n * Traversal is blocked if the path is at or within these directories.\n * Paths can include environment variable placeholders like `$HOME`.\n * \n * @example ['/etc', '/usr', '/var', '/sys', '/proc', '$HOME/.ssh']\n */\n forbidden: string[];\n\n /**\n * Soft boundary directories - traversal stops at these unless explicitly allowed.\n * These represent natural project boundaries.\n * Paths can include environment variable placeholders like `$HOME`.\n * \n * @example ['$HOME', '/tmp', '/private/tmp']\n */\n boundaries: string[];\n\n /**\n * Maximum absolute depth from the filesystem root.\n * Prevents extremely deep traversal regardless of starting point.\n * Depth is counted as the number of path segments from root.\n * \n * @example 20 means paths like /a/b/c/.../t (20 levels deep) are allowed\n * @default 20\n */\n maxAbsoluteDepth: number;\n\n /**\n * Maximum relative depth from the starting directory.\n * Limits how far up the directory tree traversal can go.\n * \n * @example 10 means traversal can go up 10 directories from the start\n * @default 10\n */\n maxRelativeDepth: number;\n}\n\n/**\n * Result of a traversal boundary check.\n */\nexport interface TraversalCheckResult {\n /** Whether the path is allowed */\n allowed: boolean;\n \n /** Reason for blocking (if not allowed) */\n reason?: string;\n \n /** The boundary that was violated (if any) */\n violatedBoundary?: string;\n}\n\n/**\n * Options for configuring traversal security behavior.\n */\nexport interface TraversalSecurityOptions {\n /**\n * Custom traversal boundaries to use instead of defaults.\n */\n boundaries?: Partial<TraversalBoundary>;\n\n /**\n * Allow traversal beyond safe boundaries.\n * \n * **SECURITY WARNING**: Setting this to true bypasses security checks\n * and allows traversal into sensitive directories. Only use this in\n * trusted scenarios where you control all configuration files.\n * \n * @default false\n */\n allowUnsafeTraversal?: boolean;\n\n /**\n * Whether to log warnings when boundaries are overridden.\n * \n * @default true\n */\n warnOnOverride?: boolean;\n}\n","import { z, ZodObject } from \"zod\";\nimport { ArgumentError } from \"./error/ArgumentError\";\nimport { ConfigurationError } from \"./error/ConfigurationError\";\nimport { FileSystemError } from \"./error/FileSystemError\";\nimport { ConfigSchema, Logger, Options } from \"./types\";\nimport * as Storage from \"./util/storage\";\nexport { ArgumentError, ConfigurationError, FileSystemError };\n\n/**\n * Recursively extracts all keys from a Zod schema in dot notation.\n *\n * This function traverses a Zod schema structure and builds a flat list\n * of all possible keys, using dot notation for nested objects. It handles\n * optional/nullable types by unwrapping them and supports arrays by\n * introspecting their element type.\n *\n * Special handling for:\n * - ZodOptional/ZodNullable: Unwraps to get the underlying type\n * - ZodAny/ZodRecord: Accepts any keys, returns the prefix or empty array\n * - ZodArray: Introspects the element type\n * - ZodObject: Recursively processes all shape properties\n *\n * @param schema - The Zod schema to introspect\n * @param prefix - Internal parameter for building nested key paths\n * @returns Array of strings representing all possible keys in dot notation\n *\n * @example\n * ```typescript\n * const schema = z.object({\n * user: z.object({\n * name: z.string(),\n * settings: z.object({ theme: z.string() })\n * }),\n * debug: z.boolean()\n * });\n *\n * const keys = listZodKeys(schema);\n * // Returns: ['user.name', 'user.settings.theme', 'debug']\n * ```\n */\nexport const listZodKeys = (schema: z.ZodTypeAny, prefix = ''): string[] => {\n // Handle ZodOptional and ZodNullable - unwrap to get the underlying type\n if (schema instanceof z.ZodOptional || schema instanceof z.ZodNullable) {\n return listZodKeys(schema.unwrap() as z.ZodTypeAny, prefix);\n }\n\n // Handle ZodAny and ZodRecord - these accept any keys, so don't introspect\n if (schema instanceof z.ZodAny || schema instanceof z.ZodRecord) {\n return prefix ? [prefix] : [];\n }\n\n if (schema instanceof z.ZodArray) {\n return listZodKeys(schema.element as z.ZodTypeAny, prefix);\n }\n\n if (schema instanceof z.ZodObject) {\n return Object.entries(schema.shape).flatMap(([key, subschema]) => {\n const fullKey = prefix ? `${prefix}.${key}` : key;\n const nested = listZodKeys(subschema as z.ZodTypeAny, fullKey);\n return nested.length ? nested : fullKey;\n });\n }\n return [];\n}\n\n/**\n * Type guard to check if a value is a plain object (not array, null, or other types).\n *\n * @param value - The value to check\n * @returns True if the value is a plain object\n */\nconst isPlainObject = (value: unknown): value is Record<string, unknown> => {\n // Check if it's an object, not null, and not an array.\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n};\n\n/**\n * Generates a list of all keys within a JavaScript object, using dot notation for nested keys.\n * Mimics the behavior of listZodKeys but operates on plain objects.\n * For arrays, it inspects the first element that is a plain object to determine nested keys.\n * If an array contains no plain objects, or is empty, the key for the array itself is listed.\n *\n * @param obj The object to introspect.\n * @param prefix Internal use for recursion: the prefix for the current nesting level.\n * @returns An array of strings representing all keys in dot notation.\n */\nexport const listObjectKeys = (obj: Record<string, unknown>, prefix = ''): string[] => {\n const keys = new Set<string>(); // Use Set to automatically handle duplicates from array recursion\n\n for (const key in obj) {\n // Ensure it's an own property, not from the prototype chain\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n const value = obj[key];\n const fullKey = prefix ? `${prefix}.${key}` : key;\n\n if (Array.isArray(value)) {\n // Find the first element that is a plain object to determine structure\n const firstObjectElement = value.find(isPlainObject);\n if (firstObjectElement) {\n // Recurse into the structure of the first object element found\n const nestedKeys = listObjectKeys(firstObjectElement, fullKey);\n nestedKeys.forEach(k => keys.add(k));\n } else {\n // Array is empty or contains no plain objects, list the array key itself\n keys.add(fullKey);\n }\n } else if (isPlainObject(value)) {\n // Recurse into nested plain objects\n const nestedKeys = listObjectKeys(value, fullKey);\n nestedKeys.forEach(k => keys.add(k));\n } else {\n // It's a primitive, null, or other non-plain object/array type\n keys.add(fullKey);\n }\n }\n }\n return Array.from(keys); // Convert Set back to Array\n};\n\n/**\n * Validates that the configuration object contains only keys allowed by the schema.\n *\n * This function prevents configuration errors by detecting typos or extra keys\n * that aren't defined in the Zod schema. It intelligently handles:\n * - ZodRecord types that accept arbitrary keys\n * - Nested objects and their key structures\n * - Arrays and their element key structures\n *\n * The function throws a ConfigurationError if extra keys are found, providing\n * helpful information about what keys are allowed vs. what was found.\n *\n * @param mergedSources - The merged configuration object to validate\n * @param fullSchema - The complete Zod schema including base and user schemas\n * @param logger - Logger for error reporting\n * @throws {ConfigurationError} When extra keys are found that aren't in the schema\n *\n * @example\n * ```typescript\n * const schema = z.object({ name: z.string(), age: z.number() });\n * const config = { name: 'John', age: 30, typo: 'invalid' };\n *\n * checkForExtraKeys(config, schema, console);\n * // Throws: ConfigurationError with details about 'typo' being an extra key\n * ```\n */\nexport const checkForExtraKeys = (mergedSources: object, fullSchema: ZodObject<any>, logger: Logger | typeof console): void => {\n const allowedKeys = new Set(listZodKeys(fullSchema));\n const actualKeys = listObjectKeys(mergedSources as Record<string, unknown>);\n\n // Filter out keys that are under a record type (ZodRecord accepts any keys)\n const recordPrefixes = new Set<string>();\n\n // Find all prefixes that are ZodRecord types\n const findRecordPrefixes = (schema: z.ZodTypeAny, prefix = ''): void => {\n if (schema instanceof z.ZodOptional || schema instanceof z.ZodNullable) {\n findRecordPrefixes(schema.unwrap() as z.ZodTypeAny, prefix);\n return;\n }\n\n if (schema instanceof z.ZodAny || schema instanceof z.ZodRecord) {\n if (prefix) recordPrefixes.add(prefix);\n return;\n }\n\n if (schema instanceof z.ZodObject) {\n Object.entries(schema.shape).forEach(([key, subschema]) => {\n const fullKey = prefix ? `${prefix}.${key}` : key;\n findRecordPrefixes(subschema as z.ZodTypeAny, fullKey);\n });\n }\n };\n\n findRecordPrefixes(fullSchema);\n\n // Filter out keys that are under record prefixes\n const extraKeys = actualKeys.filter(key => {\n if (allowedKeys.has(key)) return false;\n\n // Check if this key is under a record prefix\n for (const recordPrefix of recordPrefixes) {\n if (key.startsWith(recordPrefix + '.')) {\n return false; // This key is allowed under a record\n }\n }\n\n return true; // This is an extra key\n });\n\n if (extraKeys.length > 0) {\n const allowedKeysArray = Array.from(allowedKeys);\n const error = ConfigurationError.extraKeys(extraKeys, allowedKeysArray);\n logger.error(error.message);\n throw error;\n }\n}\n\n/**\n * Validates that a configuration directory exists and is accessible.\n *\n * This function performs file system checks to ensure the configuration\n * directory can be used. It handles the isRequired flag to determine\n * whether a missing directory should cause an error or be silently ignored.\n *\n * @param configDirectory - Path to the configuration directory\n * @param isRequired - Whether the directory must exist\n * @param logger - Optional logger for debug information\n * @throws {FileSystemError} When the directory is required but missing or unreadable\n */\nconst validateConfigDirectory = async (configDirectory: string, isRequired: boolean, logger?: Logger): Promise<void> => {\n const storage = Storage.create({ log: logger?.debug || (() => { }) });\n const exists = await storage.exists(configDirectory);\n if (!exists) {\n if (isRequired) {\n throw FileSystemError.directoryNotFound(configDirectory, true);\n }\n } else if (exists) {\n const isReadable = await storage.isDirectoryReadable(configDirectory);\n if (!isReadable) {\n throw FileSystemError.directoryNotReadable(configDirectory);\n }\n }\n}\n\n/**\n * Validates a configuration object against the combined Zod schema.\n *\n * This is the main validation function that:\n * 1. Validates the configuration directory (if config feature enabled)\n * 2. Combines the base ConfigSchema with user-provided schema shape\n * 3. Checks for extra keys not defined in the schema\n * 4. Validates all values against their schema definitions\n * 5. Provides detailed error reporting for validation failures\n *\n * The validation is comprehensive and catches common configuration errors\n * including typos, missing required fields, wrong types, and invalid values.\n *\n * @template T - The Zod schema shape type for configuration validation\n * @param config - The merged configuration object to validate\n * @param options - Cardigantime options containing schema, defaults, and logger\n * @throws {ConfigurationError} When configuration validation fails\n * @throws {FileSystemError} When configuration directory validation fails\n *\n * @example\n * ```typescript\n * const schema = z.object({\n * apiKey: z.string().min(1),\n * timeout: z.number().positive(),\n * });\n *\n * await validate(config, {\n * configShape: schema.shape,\n * defaults: { configDirectory: './config', isRequired: true },\n * logger: console,\n * features: ['config']\n * });\n * // Throws detailed errors if validation fails\n * ```\n */\nexport const validate = async <T extends z.ZodRawShape>(config: z.infer<ZodObject<T & typeof ConfigSchema.shape>>, options: Options<T>): Promise<void> => {\n const logger = options.logger;\n\n if (options.features.includes('config') && (config as any).configDirectory) {\n await validateConfigDirectory((config as any).configDirectory, options.defaults.isRequired, logger);\n }\n\n // Combine the base schema with the user-provided shape\n const fullSchema = z.object({\n ...ConfigSchema.shape,\n ...options.configShape,\n });\n\n // Validate the merged sources against the full schema\n const validationResult = fullSchema.safeParse(config);\n\n // Check for extraneous keys\n checkForExtraKeys(config, fullSchema, logger);\n\n if (!validationResult.success) {\n const formattedError = JSON.stringify(validationResult.error.format(), null, 2);\n logger.error('Configuration validation failed. Check logs for details.');\n logger.silly('Configuration validation failed: %s', formattedError);\n throw ConfigurationError.validation('Configuration validation failed. Check logs for details.', validationResult.error);\n }\n\n return;\n}\n\n","import { z } from 'zod';\n\n/**\n * Extracts default values from a Zod schema recursively using Zod v4's parsing mechanisms.\n *\n * This function leverages Zod's own parsing behavior to extract defaults rather than\n * accessing internal properties. It works by:\n * 1. For ZodDefault types: parsing undefined to trigger the default\n * 2. For ZodObject types: creating a minimal object and parsing to get all defaults\n * 3. For wrapped types: unwrapping and recursing\n *\n * @param schema - The Zod schema to extract defaults from\n * @returns An object containing all default values from the schema\n *\n * @example\n * ```typescript\n * const schema = z.object({\n * name: z.string().default('app'),\n * port: z.number().default(3000),\n * debug: z.boolean().default(false),\n * database: z.object({\n * host: z.string().default('localhost'),\n * port: z.number().default(5432)\n * })\n * });\n *\n * const defaults = extractSchemaDefaults(schema);\n * // Returns: { name: 'app', port: 3000, debug: false, database: { host: 'localhost', port: 5432 } }\n * ```\n */\nexport const extractSchemaDefaults = (schema: z.ZodTypeAny): any => {\n // Handle ZodDefault - parse undefined to get the default value\n if (schema instanceof z.ZodDefault) {\n try {\n return schema.parse(undefined);\n } catch {\n // If parsing undefined fails, return undefined\n return undefined;\n }\n }\n\n // Handle ZodOptional and ZodNullable by unwrapping\n if (schema instanceof z.ZodOptional || schema instanceof z.ZodNullable) {\n return extractSchemaDefaults(schema.unwrap() as any);\n }\n\n // Handle ZodObject - create an object with defaults by parsing an empty object\n if (schema instanceof z.ZodObject) {\n const defaults: any = {};\n const shape = schema.shape;\n\n // First, try to extract defaults from individual fields\n for (const [key, subschema] of Object.entries(shape)) {\n const defaultValue = extractSchemaDefaults(subschema as any);\n if (defaultValue !== undefined) {\n defaults[key] = defaultValue;\n }\n }\n\n // Then parse an empty object to trigger any schema-level defaults\n const result = schema.safeParse({});\n if (result.success) {\n // Merge the parsed result with our extracted defaults\n return { ...defaults, ...result.data };\n }\n\n return Object.keys(defaults).length > 0 ? defaults : undefined;\n }\n\n // Handle ZodArray - return empty array as a reasonable default\n if (schema instanceof z.ZodArray) {\n const elementDefaults = extractSchemaDefaults(schema.element as any);\n return elementDefaults !== undefined ? [elementDefaults] : [];\n }\n\n // Handle ZodRecord - return empty object as default\n if (schema instanceof z.ZodRecord) {\n return {};\n }\n\n // No default available for other schema types\n return undefined;\n};\n\n/**\n * Extracts default values that should be included in generated config files.\n *\n * This function is similar to extractSchemaDefaults but filters out certain types\n * of defaults that shouldn't appear in generated configuration files, such as\n * computed defaults or system-specific values.\n *\n * @param schema - The Zod schema to extract config file defaults from\n * @returns An object containing default values suitable for config files\n *\n * @example\n * ```typescript\n * const schema = z.object({\n * appName: z.string().default('my-app'),\n * timestamp: z.number().default(() => Date.now()), // Excluded from config files\n * port: z.number().default(3000)\n * });\n *\n * const configDefaults = extractConfigFileDefaults(schema);\n * // Returns: { appName: 'my-app', port: 3000 }\n * // Note: timestamp is excluded because it's a function-based default\n * ```\n */\nexport const extractConfigFileDefaults = (schema: z.ZodTypeAny): any => {\n // Handle ZodDefault - parse undefined to get the default value\n if (schema instanceof z.ZodDefault) {\n try {\n const defaultValue = schema.parse(undefined);\n // Exclude function-generated defaults from config files\n // These are typically runtime-computed values\n if (typeof defaultValue === 'function') {\n return undefined;\n }\n return defaultValue;\n } catch {\n return undefined;\n }\n }\n\n // Handle ZodOptional and ZodNullable by unwrapping\n if (schema instanceof z.ZodOptional || schema instanceof z.ZodNullable) {\n return extractConfigFileDefaults(schema.unwrap() as any);\n }\n\n // Handle ZodObject - extract defaults suitable for config files\n if (schema instanceof z.ZodObject) {\n const defaults: any = {};\n const shape = schema.shape;\n\n for (const [key, subschema] of Object.entries(shape)) {\n const defaultValue = extractConfigFileDefaults(subschema as any);\n if (defaultValue !== undefined) {\n defaults[key] = defaultValue;\n }\n }\n\n // Parse an empty object to get any schema-level defaults\n const result = schema.safeParse({});\n if (result.success) {\n // Filter out any function-based or computed values\n const filteredData: any = {};\n for (const [key, value] of Object.entries(result.data)) {\n if (typeof value !== 'function' && value !== null) {\n filteredData[key] = value;\n }\n }\n return { ...defaults, ...filteredData };\n }\n\n return Object.keys(defaults).length > 0 ? defaults : undefined;\n }\n\n // Handle ZodArray - typically don't include array defaults in config files\n if (schema instanceof z.ZodArray) {\n // For config files, we usually don't want to pre-populate arrays\n return undefined;\n }\n\n // Handle ZodRecord - return empty object as default for config files\n if (schema instanceof z.ZodRecord) {\n return {};\n }\n\n // No default available for other schema types\n return undefined;\n};\n\n/**\n * Generates a complete configuration object with all default values populated.\n *\n * This function combines the base ConfigSchema with a user-provided schema shape\n * and extracts all available default values to create a complete configuration\n * example that can be serialized to YAML.\n *\n * @template T - The Zod schema shape type\n * @param configShape - The user's configuration schema shape\n * @param configDirectory - The configuration directory to include in the defaults\n * @returns An object containing all default values suitable for YAML serialization\n *\n * @example\n * ```typescript\n * const shape = z.object({\n * apiKey: z.string().describe('Your API key'),\n * timeout: z.number().default(5000).describe('Request timeout in milliseconds'),\n * features: z.array(z.string()).default(['auth', 'logging'])\n * }).shape;\n *\n * const config = generateDefaultConfig(shape, './config');\n * // Returns: { timeout: 5000, features: ['auth', 'logging'] }\n * // Note: apiKey is not included since it has no default\n * ```\n */\nexport const generateDefaultConfig = <T extends z.ZodRawShape>(\n configShape: T,\n _configDirectory: string\n): Record<string, any> => {\n // Create the full schema by combining base and user schema\n const fullSchema = z.object({\n ...configShape,\n });\n\n // Extract defaults from the full schema using only explicit defaults\n const defaults = extractSchemaDefaults(fullSchema);\n\n // Don't include configDirectory in the generated file since it's runtime-specific\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { configDirectory: _, ...configDefaults } = defaults || {};\n\n return configDefaults || {};\n};\n\n","import { Command } from 'commander';\nimport { Args, DefaultOptions, Feature, Cardigantime, Logger, Options } from 'types';\nimport { z, ZodObject } from 'zod';\nimport { configure } from './configure';\nimport { DEFAULT_FEATURES, DEFAULT_LOGGER, DEFAULT_OPTIONS } from './constants';\nimport { read, checkConfig } from './read';\nimport { ConfigSchema } from 'types';\nimport { validate } from './validate';\nimport * as yaml from 'js-yaml';\nimport * as path from 'node:path';\nimport { generateDefaultConfig } from './util/schema-defaults';\nimport * as Storage from './util/storage';\nimport { FileSystemError } from './error/FileSystemError';\n\nexport * from './types';\nexport { ArgumentError, ConfigurationError, FileSystemError } from './validate';\nexport { VERSION, PROGRAM_NAME } from './constants';\n\n/**\n * Creates a new Cardigantime instance for configuration management.\n * \n * Cardigantime handles the complete configuration lifecycle including:\n * - Reading configuration from YAML files\n * - Validating configuration against Zod schemas\n * - Merging CLI arguments with file configuration and defaults\n * - Providing type-safe configuration objects\n * \n * @template T - The Zod schema shape type for your configuration\n * @param pOptions - Configuration options for the Cardigantime instance\n * @param pOptions.defaults - Default configuration settings\n * @param pOptions.defaults.configDirectory - Directory to search for configuration files (required)\n * @param pOptions.defaults.configFile - Name of the configuration file (optional, defaults to 'config.yaml')\n * @param pOptions.defaults.isRequired - Whether the config directory must exist (optional, defaults to false)\n * @param pOptions.defaults.encoding - File encoding for reading config files (optional, defaults to 'utf8')\n * @param pOptions.defaults.pathResolution - Configuration for resolving relative paths in config values relative to the config file's directory (optional)\n * @param pOptions.features - Array of features to enable (optional, defaults to ['config'])\n * @param pOptions.configShape - Zod schema shape defining your configuration structure (required)\n * @param pOptions.logger - Custom logger implementation (optional, defaults to console logger)\n * @returns A Cardigantime instance with methods for configure, read, validate, and setLogger\n * \n * @example\n * ```typescript\n * import { create } from '@utilarium/cardigantime';\n * import { z } from 'zod';\n * \n * const MyConfigSchema = z.object({\n * apiKey: z.string().min(1),\n * timeout: z.number().default(5000),\n * debug: z.boolean().default(false),\n * contextDirectories: z.array(z.string()).optional(),\n * });\n * \n * const cardigantime = create({\n * defaults: {\n * configDirectory: './config',\n * configFile: 'myapp.yaml',\n * // Resolve relative paths in contextDirectories relative to config file location\n * pathResolution: {\n * pathFields: ['contextDirectories'],\n * resolvePathArray: ['contextDirectories']\n * },\n * // Configure how array fields are merged in hierarchical mode\n * fieldOverlaps: {\n * 'features': 'append', // Accumulate features from all levels\n * 'excludePatterns': 'prepend' // Higher precedence patterns come first\n * }\n * },\n * configShape: MyConfigSchema.shape,\n * features: ['config', 'hierarchical'], // Enable hierarchical discovery\n * });\n * \n * // If config file is at ../config/myapp.yaml and contains:\n * // contextDirectories: ['./context', './data']\n * // These paths will be resolved relative to ../config/ directory\n * ```\n */\nexport const create = <T extends z.ZodRawShape>(pOptions: {\n defaults: Pick<DefaultOptions, 'configDirectory'> & Partial<Omit<DefaultOptions, 'configDirectory'>>,\n features?: Feature[],\n configShape: T, // Make configShape mandatory\n logger?: Logger,\n}): Cardigantime<T> => {\n\n // Validate that configDirectory is a string\n if (!pOptions.defaults.configDirectory || typeof pOptions.defaults.configDirectory !== 'string') {\n throw new Error(`Configuration directory must be a string, received: ${typeof pOptions.defaults.configDirectory} (${JSON.stringify(pOptions.defaults.configDirectory)})`);\n }\n\n const defaults: DefaultOptions = { ...DEFAULT_OPTIONS, ...pOptions.defaults } as DefaultOptions;\n const features = pOptions.features || DEFAULT_FEATURES;\n const configShape = pOptions.configShape;\n let logger = pOptions.logger || DEFAULT_LOGGER;\n\n const options: Options<T> = {\n defaults,\n features,\n configShape, // Store the shape\n logger,\n }\n\n const setLogger = (pLogger: Logger) => {\n logger = pLogger;\n options.logger = pLogger;\n }\n\n const generateConfig = async (configDirectory?: string): Promise<void> => {\n const targetDir = configDirectory || options.defaults.configDirectory;\n const configFile = options.defaults.configFile;\n const encoding = options.defaults.encoding;\n\n // Validate that targetDir is a string\n if (!targetDir || typeof targetDir !== 'string') {\n throw new Error(`Configuration directory must be a string, received: ${typeof targetDir} (${JSON.stringify(targetDir)})`);\n }\n\n logger.verbose(`Generating configuration file in: ${targetDir}`);\n\n // Create storage utility\n const storage = Storage.create({ log: logger.debug });\n\n // Ensure the target directory exists\n const dirExists = await storage.exists(targetDir);\n if (!dirExists) {\n logger.info(`Creating configuration directory: ${targetDir}`);\n try {\n await storage.createDirectory(targetDir);\n } catch (error: any) {\n throw FileSystemError.directoryCreationFailed(targetDir, error);\n }\n }\n\n // Check if directory is writable\n const isWritable = await storage.isDirectoryWritable(targetDir);\n if (!isWritable) {\n throw new FileSystemError('not_writable', 'Configuration directory is not writable', targetDir, 'directory_write');\n }\n\n // Build the full config file path\n const configFilePath = path.join(targetDir, configFile);\n\n // Generate default configuration\n logger.debug(`Generating defaults for schema with keys: ${Object.keys(options.configShape).join(', ')}`);\n const defaultConfig = generateDefaultConfig(options.configShape, targetDir);\n logger.debug(`Generated default config: ${JSON.stringify(defaultConfig, null, 2)}`);\n\n // Convert to YAML with nice formatting\n const yamlContent = yaml.dump(defaultConfig, {\n indent: 2,\n lineWidth: 120,\n noRefs: true,\n sortKeys: true\n });\n\n // Add header comment to the YAML file\n const header = `# Configuration file generated by Cardigantime\n# This file contains default values for your application configuration.\n# Modify the values below to customize your application's behavior.\n#\n# For more information about Cardigantime configuration:\n# https://utilarium.github.io/cardigantime/\n\n`;\n\n const finalContent = header + yamlContent;\n\n // Check if config file already exists\n const configExists = await storage.exists(configFilePath);\n if (configExists) {\n logger.warn(`Configuration file already exists: ${configFilePath}`);\n logger.warn('This file was not overwritten, but here is what the default configuration looks like if you want to copy it:');\n logger.info('\\n' + '='.repeat(60));\n logger.info(finalContent.trim());\n logger.info('='.repeat(60));\n return;\n }\n\n // Write the configuration file\n try {\n await storage.writeFile(configFilePath, finalContent, encoding);\n logger.info(`Configuration file generated successfully: ${configFilePath}`);\n } catch (error: any) {\n throw FileSystemError.operationFailed('write configuration file', configFilePath, error);\n }\n };\n\n return {\n setLogger,\n configure: (command: Command) => configure(command, options),\n validate: (config: z.infer<ZodObject<T & typeof ConfigSchema.shape>>) => validate(config, options),\n read: (args: Args) => read(args, options),\n generateConfig,\n checkConfig: (args: Args) => checkConfig(args, options),\n }\n}\n\n/**\n * Type-safe helper for defining configuration in TypeScript/JavaScript files.\n * \n * This is a simple identity function that provides type checking and\n * autocomplete for configuration objects when using TypeScript config files.\n * \n * @template T - The configuration type\n * @param config - The configuration object\n * @returns The same configuration object (identity function)\n * \n * @example\n * ```typescript\n * // config.ts\n * import { defineConfig } from '@utilarium/cardigantime';\n * \n * export default defineConfig({\n * apiKey: process.env.API_KEY || 'default-key',\n * timeout: 5000,\n * debug: process.env.NODE_ENV === 'development'\n * });\n * ```\n */\nexport function defineConfig<T>(config: T): T {\n return config;\n}\n\n"],"names":["ArgumentError","Error","argument","argumentName","message","_define_property","name","validateConfigDirectory","configDirectory","_testThrowNonArgumentError","trimmed","trim","length","includes","configure","command","options","option","defaults","validatedDefaultDir","retCommand","value","error","validFormats","normalized","toLowerCase","join","VERSION","PROGRAM_NAME","DEFAULT_ENCODING","DEFAULT_CONFIG_FILE","DEFAULT_OPTIONS","configFile","isRequired","encoding","pathResolution","undefined","DEFAULT_FEATURES","DEFAULT_LOGGER","debug","console","info","warn","verbose","silly","FileSystemError","directoryNotFound","path","directoryNotReadable","directoryCreationFailed","originalError","operationFailed","operation","fileNotFound","errorType","create","params","log","exists","fs","promises","stat","isDirectory","stats","isFile","isReadable","access","constants","R_OK","stack","isWritable","W_OK","isFileReadable","isDirectoryWritable","isDirectoryReadable","createDirectory","mkdir","recursive","mkdirError","readFile","validEncodings","maxFileSize","size","code","writeFile","data","forEachFileIn","directory","callback","pattern","files","glob","cwd","nodir","file","err","readStream","createReadStream","hashFile","crypto","createHash","update","digest","slice","listFiles","readdir","normalizePathInput","normalizePathString","Array","isArray","map","item","key","val","Object","entries","str","test","url","URL","decodeURIComponent","pathname","resolveConfigPaths","config","configDir","pathFields","resolvePathArray","resolvedConfig","fieldPath","getNestedValue","normalizedValue","shouldResolveArrayElements","resolvedValue","resolvePathValue","setNestedValue","obj","split","reduce","current","isUnsafeKey","keys","lastKey","pop","some","target","resolveArrayElements","resolveSinglePath","resolved","pathStr","isAbsolute","resolve","discoverConfigDirectories","configDirName","maxLevels","startingDir","process","logger","storage","createStorage","discoveredDirs","currentDir","level","visited","Set","realPath","has","add","configDirPath","push","parentDir","dirname","findConfigFileWithExtension","configFileName","configFilePath","ext","extname","baseName","basename","alternativeExt","alternativePath","altExists","altIsReadable","loadConfigFromDirectory","yamlContent","parsedYaml","yaml","load","deepMergeConfigs","configs","fieldOverlaps","merged","deepMergeTwo","source","currentPath","overlapMode","getOverlapModeForPath","mergeArrays","result","prototype","hasOwnProperty","call","pathParts","i","parentPath","targetArray","sourceArray","mode","loadHierarchicalConfig","resolvedConfigDirs","errors","sortedDirs","sort","a","b","dir","errorMsg","mergedConfig","clean","fromEntries","filter","_","v","validatePath","userPath","basePath","normalize","startsWith","read","args","rawConfigDir","resolvedConfigDir","rawFileConfig","discoveredConfigDirs","features","hierarchicalResult","forEach","loadSingleDirectoryConfig","processedConfig","alternativeFileName","Storage","trackConfigSources","sourcePath","prefix","tracker","sourceLabel","mergeConfigTrackers","trackers","formatConfigValue","toString","String","displayConfigWithSources","repeat","precedence","Math","max","d","sortedKeys","maxKeyLength","k","maxSourceLength","values","paddedKey","padEnd","paddedSource","formattedValue","sourceCount","count","checkConfig","levelTracker","finalConfig","ConfigurationError","validation","zodError","configPath","extraKeys","allowedKeys","schema","details","ConfigFormat","ConfigSchema","z","object","string","array","DEFAULT_ROOT_MARKERS","type","listZodKeys","ZodOptional","ZodNullable","unwrap","ZodAny","ZodRecord","ZodArray","element","ZodObject","shape","flatMap","subschema","fullKey","nested","isPlainObject","listObjectKeys","firstObjectElement","find","nestedKeys","from","checkForExtraKeys","mergedSources","fullSchema","actualKeys","recordPrefixes","findRecordPrefixes","recordPrefix","allowedKeysArray","validate","configShape","validationResult","safeParse","success","formattedError","JSON","stringify","format","extractSchemaDefaults","ZodDefault","parse","defaultValue","elementDefaults","generateDefaultConfig","_configDirectory","configDefaults","pOptions","setLogger","pLogger","generateConfig","targetDir","dirExists","defaultConfig","dump","indent","lineWidth","noRefs","sortKeys","header","finalContent","configExists","defineConfig"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;IAcO,MAAMA,aAAAA,SAAsBC,KAAAA,CAAAA;AAgB/B;;;;AAIC,QACD,IAAIC,QAAAA,GAAmB;QACnB,OAAO,IAAI,CAACC,YAAY;AAC5B,IAAA;AAnBA;;;;;AAKC,QACD,WAAA,CAAYA,YAAoB,EAAEC,OAAe,CAAE;QAC/C,KAAK,CAAC,GAAGA,OAAAA,CAAAA,CAAS,CAAA,wDATtBC,kBAAA,CAAA,IAAA,EAAQF,gBAAR,MAAA,CAAA;QAUI,IAAI,CAACG,IAAI,GAAG,eAAA;QACZ,IAAI,CAACH,YAAY,GAAGA,YAAAA;AACxB,IAAA;AAUJ;;AChCA;;;;;;;;;;;;;;;;;;;AAmBC,IACM,SAASI,yBAAAA,CAAwBC,eAAuB,EAAEC,0BAAoC,EAAA;AAKjG,IAAA,IAAI,CAACD,eAAAA,EAAiB;QAClB,MAAM,IAAIR,cAAc,iBAAA,EAAmB,yCAAA,CAAA;AAC/C,IAAA;IAEA,IAAI,OAAOQ,oBAAoB,QAAA,EAAU;QACrC,MAAM,IAAIR,cAAc,iBAAA,EAAmB,0CAAA,CAAA;AAC/C,IAAA;IAEA,MAAMU,OAAAA,GAAUF,gBAAgBG,IAAI,EAAA;IACpC,IAAID,OAAAA,CAAQE,MAAM,KAAK,CAAA,EAAG;QACtB,MAAM,IAAIZ,cAAc,iBAAA,EAAmB,4DAAA,CAAA;AAC/C,IAAA;;IAGA,IAAIU,OAAAA,CAAQG,QAAQ,CAAC,IAAA,CAAA,EAAO;QACxB,MAAM,IAAIb,cAAc,iBAAA,EAAmB,yDAAA,CAAA;AAC/C,IAAA;;I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