@theunwalked/cardigantime 0.0.9 → 0.0.10

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.
package/dist/read.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"read.js","sources":["../src/read.ts"],"sourcesContent":["import * as yaml from 'js-yaml';\nimport * as path from 'path';\nimport { z, ZodObject } from 'zod';\nimport { Args, ConfigSchema, Options } from './types';\nimport * as Storage from './util/storage';\nimport { loadHierarchicalConfig } 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 * Sets a nested value in an object using dot notation.\n */\nfunction setNestedValue(obj: any, path: string, value: any): void {\n const keys = path.split('.');\n const lastKey = keys.pop()!;\n const target = keys.reduce((current, key) => {\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\n // Check if hierarchical configuration discovery is enabled\n if (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\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.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 } 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\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 }\n }) as z.infer<ZodObject<T & typeof ConfigSchema.shape>>;\n\n return config;\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 const configFile = validatePath(options.defaults.configFile, resolvedConfigDir);\n logger.verbose('Attempting to load config file for cardigantime');\n\n let rawFileConfig: object = {};\n\n try {\n const yamlContent = await storage.readFile(configFile, 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 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}"],"names":["clean","obj","Object","fromEntries","entries","filter","_","v","undefined","resolveConfigPaths","config","configDir","pathFields","resolvePathArray","length","resolvedConfig","fieldPath","value","getNestedValue","shouldResolveArrayElements","includes","resolvedValue","resolvePathValue","setNestedValue","path","split","reduce","current","key","keys","lastKey","pop","target","resolveArrayElements","resolveSinglePath","Array","isArray","map","item","pathStr","isAbsolute","resolve","validatePath","userPath","basePath","Error","normalized","normalize","startsWith","join","validateConfigDirectory","read","args","options","logger","rawConfigDir","configDirectory","defaults","resolvedConfigDir","verbose","rawFileConfig","features","configDirName","basename","startingDir","dirname","debug","hierarchicalResult","loadHierarchicalConfig","configFileName","configFile","encoding","pathResolution","fieldOverlaps","discoveredDirs","forEach","dir","level","errors","error","warn","message","loadSingleDirectoryConfig","processedConfig","storage","Storage","log","yamlContent","readFile","parsedYaml","yaml","load","code","test"],"mappings":";;;;;AAOA;;;;;;IAOA,SAASA,MAAMC,GAAQ,EAAA;AACnB,IAAA,OAAOC,MAAAA,CAAOC,WAAW,CACrBD,MAA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AOK,OAAO,CAAC,iDAAA,CAAA;AAEf,IAAA,IAAIC,gBAAwB,EAAC;IAE7B,IAAI;QACA,MAAM2B,WAAAA,GAAc,MAAMH,OAAAA,CAAQI,QAAQ,CAAClB,UAAAA,EAAYjB,OAAAA,CAAQI,QAAQ,CAACc,QAAQ,CAAA;;QAGhF,MAAMkB,UAAAA,GAAaC,IAAAA,CAAKC,IAAI,CAACJ,WAAAA,CAAAA;AAE7B,QAAA,IAAIE,UAAAA,KAAe,IAAA,IAAQ,OAAOA,UAAAA,KAAe,QAAA,EAAU;YACvD7B,aAAAA,GAAgB6B,UAAAA;AAChBnC,YAAAA,MAAAA,CAAOK,OAAO,CAAC,wCAAA,CAAA;SACnB,MAAO,IAAI8B,eAAe,IAAA,EAAM;YAC5BnC,MAAAA,CAAO0B,IAAI,CAAC,iEAAA,GAAoE,OAAOS,UAAAA,CAAAA;AAC3F;AACJ,KAAA,CAAE,OAAOV,KAAAA,EAAY;QACjB,IAAIA,KAAAA,CAAMa,IAAI,KAAK,QAAA,IAAY,0BAA0BC,IAAI,CAACd,KAAAA,CAAME,OAAO,CAAA,EAAG;AAC1E3B,YAAAA,MAAAA,CAAOK,OAAO,CAAC,0DAAA,CAAA;SACnB,MAAO;;AAEHL,YAAAA,MAAAA,CAAOyB,KAAK,CAAC,8CAAA,IAAkDA,KAAAA,CAAME,OAAO,IAAI,eAAc,CAAA,CAAA;AAClG;AACJ;IAEA,OAAOrB,aAAAA;AACX;;;;"}
1
+ {"version":3,"file":"read.js","sources":["../src/read.ts"],"sourcesContent":["import * as yaml from 'js-yaml';\nimport * as path from '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 * Sets a nested value in an object using dot notation.\n */\nfunction setNestedValue(obj: any, path: string, value: any): void {\n const keys = path.split('.');\n const lastKey = keys.pop()!;\n const target = keys.reduce((current, key) => {\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\n // Check if hierarchical configuration discovery is enabled\n if (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\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.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 } 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\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 }\n }) as z.infer<ZodObject<T & typeof ConfigSchema.shape>>;\n\n return config;\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 const configFile = validatePath(options.defaults.configFile, resolvedConfigDir);\n logger.verbose('Attempting to load config file for cardigantime');\n\n let rawFileConfig: object = {};\n\n try {\n const yamlContent = await storage.readFile(configFile, 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 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 tracker: ConfigSourceTracker = {};\n\n // Check if hierarchical configuration discovery is enabled\n if (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\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 = [...discoveredDirs].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 discoveredDirs = [{\n path: resolvedConfigDir,\n level: 0\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 discoveredDirs = [{\n path: resolvedConfigDir,\n level: 0\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 });\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 // Display the configuration with source information\n displayConfigWithSources(finalConfig, tracker, discoveredDirs, logger);\n};"],"names":["clean","obj","Object","fromEntries","entries","filter","_","v","undefined","resolveConfigPaths","config","configDir","pathFields","resolvePathArray","length","resolvedConfig","fieldPath","value","getNestedValue","shouldResolveArrayElements","includes","resolvedValue","resolvePathValue","setNestedValue","path","split","reduce","current","key","keys","lastKey","pop","target","resolveArrayElements","resolveSinglePath","Array","isArray","map","item","pathStr","isAbsolute","resolve","validatePath","userPath","basePath","Error","normalized","normalize","startsWith","join","validateConfigDirectory","read","args","options","logger","rawConfigDir","configDirectory","defaults","resolvedConfigDir","verbose","rawFileConfig","features","configDirName","basename","startingDir","dirname","debug","hierarchicalResult","loadHierarchicalConfig","configFileName","configFile","encoding","pathResolution","fieldOverlaps","discoveredDirs","forEach","dir","level","errors","error","warn","message","loadSingleDirectoryConfig","processedConfig","storage","Storage","log","yamlContent","readFile","parsedYaml","yaml","load","code","test","trackConfigSources","sourcePath","prefix","tracker","sourceLabel","mergeConfigTrackers","trackers","merged","info","formatConfigValue","toString","slice","String","displayConfigWithSources","repeat","sort","a","b","precedence","Math","max","d","sortedKeys","maxKeyLength","k","maxSourceLength","values","paddedKey","padEnd","paddedSource","formattedValue","sourceCount","source","count","checkConfig","sortedDirs","configFilePath","exists","isReadable","isFileReadable","levelTracker","push","finalConfig"],"mappings":";;;;;AAOA;;;;;;IAOA,SAASA,MAAMC,GAAQ,EAAA;AACnB,IAAA,OAAOC,MAAAA,CAAOC,WAAW,CACrBD,MAAAA,CAAOE,OAAO,CAACH,GAAAA,CAAAA,CAAKI,MAAM,CAAC,CAAC,CAACC,CAAAA,EAAGC,CAAAA,CAAE,GAAKA,CAAAA,KAAMC,SAAAA,CAAAA,CAAAA;AAErD;AAEA;;;;;;;;IASA,SAASC,kBAAAA,CACLC,MAAW,EACXC,SAAiB,EACjBC,UAAAA,GAAuB,EAAE,EACzBC,gBAAAA,GAA6B,EAAE,EAAA;IAE/B,IAAI,CAACH,UAAU,OAAOA,MAAAA,KAAW,YAAYE,UAAAA,CAAWE,MAAM,KAAK,CAAA,EAAG;QAClE,OAAOJ,MAAAA;AACX;AAEA,IAAA,MAAMK,cAAAA,GAAiB;AAAE,QAAA,GAAGL;AAAO,KAAA;IAEnC,KAAK,MAAMM,aAAaJ,UAAAA,CAAY;QAChC,MAAMK,KAAAA,GAAQC,eAAeH,cAAAA,EAAgBC,SAAAA,CAAAA;AAC7C,QAAA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N;;AAGA,IAAA,IAAIM,eAAAA,GAAkBvB,aAAAA;IACtB,IAAA,CAAIP,gCAAAA,GAAAA,QAAQI,QAAQ,CAACe,cAAc,MAAA,IAAA,IAA/BnB,gCAAAA,KAAAA,MAAAA,GAAAA,MAAAA,GAAAA,gCAAAA,CAAiCzC,UAAU,EAAE;AAC7CuE,QAAAA,eAAAA,GAAkB1E,mBACdmD,aAAAA,EACAF,iBAAAA,EACAL,OAAAA,CAAQI,QAAQ,CAACe,cAAc,CAAC5D,UAAU,EAC1CyC,QAAQI,QAAQ,CAACe,cAAc,CAAC3D,gBAAgB,IAAI,EAAE,CAAA;AAE9D;;AAGA,IAAA,MAAM2H,cAAcxI,KAAAA,CAAM;AACtB,QAAA,GAAGmF,eAAe;QAClB3B,eAAAA,EAAiBE;AACrB,KAAA,CAAA;;IAGAuC,OAAO,CAAC,kBAAkB,GAAG;QACzBhF,KAAAA,EAAOyC,iBAAAA;QACPqC,UAAAA,EAAY,UAAA;AACZlB,QAAAA,KAAAA,EAAO,EAAC;QACRqB,WAAAA,EAAa;AACjB,KAAA;;IAGAS,wBAAAA,CAAyB6B,WAAAA,EAAavC,SAASvB,cAAAA,EAAgBpB,MAAAA,CAAAA;AACnE;;;;"}
package/dist/types.d.ts CHANGED
@@ -120,6 +120,16 @@ export interface Cardigantime<T extends z.ZodRawShape> {
120
120
  * Throws ConfigurationError if validation fails.
121
121
  */
122
122
  validate: (config: z.infer<ZodObject<T & typeof ConfigSchema.shape>>) => Promise<void>;
123
+ /**
124
+ * Generates a configuration file with default values in the specified directory.
125
+ * Creates the directory if it doesn't exist and writes a config file with all default values populated.
126
+ */
127
+ generateConfig: (configDirectory?: string) => Promise<void>;
128
+ /**
129
+ * Checks and displays the resolved configuration with detailed source tracking.
130
+ * Shows which file and hierarchical level contributed each configuration value in a git blame-like format.
131
+ */
132
+ checkConfig: (args: Args) => Promise<void>;
123
133
  }
124
134
  /**
125
135
  * Parsed command-line arguments object, typically from Commander.js opts().
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sources":["../src/types.ts"],"sourcesContent":["import { Command } from \"commander\";\nimport { ZodObject } from \"zod\";\n\nimport { z } from \"zod\";\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 * 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\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\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});\n\n/**\n * Base configuration type derived from the core schema.\n */\nexport type Config = z.infer<typeof ConfigSchema>;\n"],"names":["ConfigSchema","z","object","configDirectory","string"],"mappings":";;AA8IA;;;AAGC,IACM,MAAMA,YAAAA,GAAeC,CAAAA,CAAEC,MAAM,CAAC;qDAEjCC,eAAAA,EAAiBF,CAAAA,CAAEG,MAAM;AAC7B,CAAA;;;;"}
1
+ {"version":3,"file":"types.js","sources":["../src/types.ts"],"sourcesContent":["import { Command } from \"commander\";\nimport { ZodObject } from \"zod\";\n\nimport { z } from \"zod\";\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 * 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\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});\n\n/**\n * Base configuration type derived from the core schema.\n */\nexport type Config = z.infer<typeof ConfigSchema>;\n"],"names":["ConfigSchema","z","object","configDirectory","string"],"mappings":";;AAwJA;;;AAGC,IACM,MAAMA,YAAAA,GAAeC,CAAAA,CAAEC,MAAM,CAAC;qDAEjCC,eAAAA,EAAiBF,CAAAA,CAAEG,MAAM;AAC7B,CAAA;;;;"}
@@ -0,0 +1,57 @@
1
+ import { z } from 'zod';
2
+ /**
3
+ * Extracts default values from a Zod schema recursively.
4
+ *
5
+ * This function traverses a Zod schema and builds an object containing
6
+ * all the default values defined in the schema. It handles:
7
+ * - ZodDefault types with explicit default values
8
+ * - ZodOptional/ZodNullable types by unwrapping them
9
+ * - ZodObject types by recursively processing their shape
10
+ * - ZodArray types by providing an empty array as default
11
+ *
12
+ * @param schema - The Zod schema to extract defaults from
13
+ * @returns An object containing all default values from the schema
14
+ *
15
+ * @example
16
+ * ```typescript
17
+ * const schema = z.object({
18
+ * name: z.string().default('app'),
19
+ * port: z.number().default(3000),
20
+ * debug: z.boolean().default(false),
21
+ * database: z.object({
22
+ * host: z.string().default('localhost'),
23
+ * port: z.number().default(5432)
24
+ * })
25
+ * });
26
+ *
27
+ * const defaults = extractSchemaDefaults(schema);
28
+ * // Returns: { name: 'app', port: 3000, debug: false, database: { host: 'localhost', port: 5432 } }
29
+ * ```
30
+ */
31
+ export declare const extractSchemaDefaults: (schema: z.ZodTypeAny) => any;
32
+ /**
33
+ * Generates a complete configuration object with all default values populated.
34
+ *
35
+ * This function combines the base ConfigSchema with a user-provided schema shape
36
+ * and extracts all available default values to create a complete configuration
37
+ * example that can be serialized to YAML.
38
+ *
39
+ * @template T - The Zod schema shape type
40
+ * @param configShape - The user's configuration schema shape
41
+ * @param configDirectory - The configuration directory to include in the defaults
42
+ * @returns An object containing all default values suitable for YAML serialization
43
+ *
44
+ * @example
45
+ * ```typescript
46
+ * const shape = z.object({
47
+ * apiKey: z.string().describe('Your API key'),
48
+ * timeout: z.number().default(5000).describe('Request timeout in milliseconds'),
49
+ * features: z.array(z.string()).default(['auth', 'logging'])
50
+ * }).shape;
51
+ *
52
+ * const config = generateDefaultConfig(shape, './config');
53
+ * // Returns: { timeout: 5000, features: ['auth', 'logging'] }
54
+ * // Note: apiKey is not included since it has no default
55
+ * ```
56
+ */
57
+ export declare const generateDefaultConfig: <T extends z.ZodRawShape>(configShape: T, configDirectory: string) => Record<string, any>;
@@ -0,0 +1,108 @@
1
+ import { z } from 'zod';
2
+
3
+ /**
4
+ * Extracts default values from a Zod schema recursively.
5
+ *
6
+ * This function traverses a Zod schema and builds an object containing
7
+ * all the default values defined in the schema. It handles:
8
+ * - ZodDefault types with explicit default values
9
+ * - ZodOptional/ZodNullable types by unwrapping them
10
+ * - ZodObject types by recursively processing their shape
11
+ * - ZodArray types by providing an empty array as default
12
+ *
13
+ * @param schema - The Zod schema to extract defaults from
14
+ * @returns An object containing all default values from the schema
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * const schema = z.object({
19
+ * name: z.string().default('app'),
20
+ * port: z.number().default(3000),
21
+ * debug: z.boolean().default(false),
22
+ * database: z.object({
23
+ * host: z.string().default('localhost'),
24
+ * port: z.number().default(5432)
25
+ * })
26
+ * });
27
+ *
28
+ * const defaults = extractSchemaDefaults(schema);
29
+ * // Returns: { name: 'app', port: 3000, debug: false, database: { host: 'localhost', port: 5432 } }
30
+ * ```
31
+ */ const extractSchemaDefaults = (schema)=>{
32
+ // Handle ZodDefault - extract the default value
33
+ if (schema._def && schema._def.typeName === 'ZodDefault') {
34
+ const defaultSchema = schema;
35
+ return defaultSchema._def.defaultValue();
36
+ }
37
+ // Handle ZodOptional and ZodNullable - unwrap and recurse
38
+ if (schema._def && (schema._def.typeName === 'ZodOptional' || schema._def.typeName === 'ZodNullable')) {
39
+ const unwrappable = schema;
40
+ return extractSchemaDefaults(unwrappable.unwrap());
41
+ }
42
+ // Handle ZodObject - recursively process shape
43
+ if (schema._def && schema._def.typeName === 'ZodObject') {
44
+ const objectSchema = schema;
45
+ const result = {};
46
+ for (const [key, subschema] of Object.entries(objectSchema.shape)){
47
+ const defaultValue = extractSchemaDefaults(subschema);
48
+ if (defaultValue !== undefined) {
49
+ result[key] = defaultValue;
50
+ }
51
+ }
52
+ return Object.keys(result).length > 0 ? result : undefined;
53
+ }
54
+ // Handle ZodArray - provide empty array as default
55
+ if (schema._def && schema._def.typeName === 'ZodArray') {
56
+ const arraySchema = schema;
57
+ const elementDefaults = extractSchemaDefaults(arraySchema.element);
58
+ // Return an empty array, or an array with one example element if it has defaults
59
+ return elementDefaults !== undefined ? [
60
+ elementDefaults
61
+ ] : [];
62
+ }
63
+ // Handle ZodRecord - provide empty object as default
64
+ if (schema._def && schema._def.typeName === 'ZodRecord') {
65
+ return {};
66
+ }
67
+ // For other types, return undefined (no default available)
68
+ return undefined;
69
+ };
70
+ /**
71
+ * Generates a complete configuration object with all default values populated.
72
+ *
73
+ * This function combines the base ConfigSchema with a user-provided schema shape
74
+ * and extracts all available default values to create a complete configuration
75
+ * example that can be serialized to YAML.
76
+ *
77
+ * @template T - The Zod schema shape type
78
+ * @param configShape - The user's configuration schema shape
79
+ * @param configDirectory - The configuration directory to include in the defaults
80
+ * @returns An object containing all default values suitable for YAML serialization
81
+ *
82
+ * @example
83
+ * ```typescript
84
+ * const shape = z.object({
85
+ * apiKey: z.string().describe('Your API key'),
86
+ * timeout: z.number().default(5000).describe('Request timeout in milliseconds'),
87
+ * features: z.array(z.string()).default(['auth', 'logging'])
88
+ * }).shape;
89
+ *
90
+ * const config = generateDefaultConfig(shape, './config');
91
+ * // Returns: { timeout: 5000, features: ['auth', 'logging'] }
92
+ * // Note: apiKey is not included since it has no default
93
+ * ```
94
+ */ const generateDefaultConfig = (configShape, configDirectory)=>{
95
+ // Create the full schema by combining base and user schema
96
+ const fullSchema = z.object({
97
+ ...configShape
98
+ });
99
+ // Extract defaults from the full schema
100
+ const defaults = extractSchemaDefaults(fullSchema);
101
+ // Don't include configDirectory in the generated file since it's runtime-specific
102
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
103
+ const { configDirectory: _, ...configDefaults } = defaults || {};
104
+ return configDefaults || {};
105
+ };
106
+
107
+ export { extractSchemaDefaults, generateDefaultConfig };
108
+ //# sourceMappingURL=schema-defaults.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema-defaults.js","sources":["../../src/util/schema-defaults.ts"],"sourcesContent":["import { z, ZodObject } from 'zod';\n\n/**\n * Extracts default values from a Zod schema recursively.\n * \n * This function traverses a Zod schema and builds an object containing\n * all the default values defined in the schema. It handles:\n * - ZodDefault types with explicit default values\n * - ZodOptional/ZodNullable types by unwrapping them\n * - ZodObject types by recursively processing their shape\n * - ZodArray types by providing an empty array as default\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 - extract the default value\n if (schema._def && schema._def.typeName === 'ZodDefault') {\n const defaultSchema = schema as z.ZodDefault<any>;\n return defaultSchema._def.defaultValue();\n }\n\n // Handle ZodOptional and ZodNullable - unwrap and recurse\n if (schema._def && (schema._def.typeName === 'ZodOptional' || schema._def.typeName === 'ZodNullable')) {\n const unwrappable = schema as z.ZodOptional<any> | z.ZodNullable<any>;\n return extractSchemaDefaults(unwrappable.unwrap());\n }\n\n // Handle ZodObject - recursively process shape\n if (schema._def && schema._def.typeName === 'ZodObject') {\n const objectSchema = schema as z.ZodObject<any>;\n const result: any = {};\n\n for (const [key, subschema] of Object.entries(objectSchema.shape)) {\n const defaultValue = extractSchemaDefaults(subschema as z.ZodTypeAny);\n if (defaultValue !== undefined) {\n result[key] = defaultValue;\n }\n }\n\n return Object.keys(result).length > 0 ? result : undefined;\n }\n\n // Handle ZodArray - provide empty array as default\n if (schema._def && schema._def.typeName === 'ZodArray') {\n const arraySchema = schema as z.ZodArray<any>;\n const elementDefaults = extractSchemaDefaults(arraySchema.element);\n // Return an empty array, or an array with one example element if it has defaults\n return elementDefaults !== undefined ? [elementDefaults] : [];\n }\n\n // Handle ZodRecord - provide empty object as default\n if (schema._def && schema._def.typeName === 'ZodRecord') {\n return {};\n }\n\n // For other types, return undefined (no default available)\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\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}; "],"names":["extractSchemaDefaults","schema","_def","typeName","defaultSchema","defaultValue","unwrappable","unwrap","objectSchema","result","key","subschema","Object","entries","shape","undefined","keys","length","arraySchema","elementDefaults","element","generateDefaultConfig","configShape","configDirectory","fullSchema","z","object","defaults","_","configDefaults"],"mappings":";;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;IA6BO,MAAMA,qBAAAA,GAAwB,CAACC,MAAAA,GAAAA;;IAElC,IAAIA,MAAAA,CAAOC,IAAI,IAAID,MAAAA,CAAOC,IAAI,CAACC,QAAQ,KAAK,YAAA,EAAc;AACtD,QAAA,MAAMC,aAAAA,GAAgBH,MAAAA;QACtB,OAAOG,aAAAA,CAAcF,IAAI,CAACG,YAAY,EAAA;AAC1C;;AAGA,IAAA,IAAIJ,OAAOC,IAAI,KAAKD,MAAAA,CAAOC,IAAI,CAACC,QAAQ,KAAK,aAAA,IAAiBF,OAAOC,IAAI,CAACC,QAAQ,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C,CAAAA,CAAEC,MAAM,CAAC;AACxB,QAAA,GAAGJ;AACP,KAAA,CAAA;;AAGA,IAAA,MAAMK,WAAW3B,qBAAAA,CAAsBwB,UAAAA,CAAAA;;;IAIvC,MAAM,EAAED,iBAAiBK,CAAC,EAAE,GAAGC,cAAAA,EAAgB,GAAGF,YAAY,EAAC;AAE/D,IAAA,OAAOE,kBAAkB,EAAC;AAC9B;;;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theunwalked/cardigantime",
3
- "version": "0.0.9",
3
+ "version": "0.0.10",
4
4
  "description": "cardigantime is a tool to help you time your cardigans.",
5
5
  "type": "module",
6
6
  "main": "./dist/cardigantime.cjs",