All files / cli ConfigLoader.ts

91.66% Statements 11/12
75% Branches 3/4
50% Functions 1/2
91.66% Lines 11/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46                                    13x                 13x 13x 13x 7x 7x 7x     1x 1x 1x     5x          
/**
 * ConfigLoader
 * Loads configuration from project config files using cosmiconfig
 */
 
import { cosmiconfigSync } from "cosmiconfig";
import IFileConfig from "./types/IFileConfig";
 
/**
 * Load configuration from project directory
 */
class ConfigLoader {
  /**
   * Load config from project directory, searching up the directory tree
   * @param startDir - Directory to start searching from
   * @returns Loaded configuration (empty object if no config found)
   */
  static load(startDir: string): IFileConfig {
    const explorer = cosmiconfigSync("cnext", {
      searchPlaces: ["cnext.config.json", ".cnext.json", ".cnextrc"],
      loaders: {
        ".cnextrc": (_filepath: string, content: string) => JSON.parse(content),
      },
      // Search up to filesystem root
      stopDir: "/",
    });
 
    try {
      const result = explorer.search(startDir);
      if (result?.config) {
        const config = result.config as IFileConfig;
        config._path = result.filepath;
        return config;
      }
    } catch (err) {
      const message = err instanceof Error ? err.message : String(err);
      console.error(`Warning: Failed to parse config: ${message}`);
      return {};
    }
 
    return {}; // No config found
  }
}
 
export default ConfigLoader;