UNPKG

@darkobits/saffron

Version:

Yargs + Cosmiconfig for robust, configurable CLIs.

104 lines (103 loc) 3.25 kB
import path from "path"; import { defaultLoaders, cosmiconfig } from "cosmiconfig"; import merge from "deepmerge"; import validators from "../../etc/validators.js"; import { esbuildStrategy } from "./strategies/esbuild.js"; import log from "../log.js"; import { getPackageInfo } from "../package.js"; function getDefaultExport(module) { let result = module; while (Reflect.has(result, "default")) result = Reflect.get(result, "default"); return result; } async function ecmaScriptLoader(filePath) { var _a; const prefix = log.chalk.green("config"); log.verbose(prefix, `Loading file: ${log.chalk.green(filePath)}`); const errors = []; try { const result = await import(filePath); log.verbose(prefix, "Used strategy:", log.chalk.bold("import()")); return getDefaultExport(result); } catch (err) { errors.push(new Error(`${prefix} Failed to load file with ${log.chalk.bold("import()")}: ${err}`)); } try { const pkgInfo = getPackageInfo({ cwd: path.dirname(filePath) }); if (!(pkgInfo == null ? void 0 : pkgInfo.root)) throw new Error(`${prefix} Unable to compute host package root directory.`); const result = await esbuildStrategy(filePath, { pkg: { root: pkgInfo.root, type: (_a = pkgInfo.json) == null ? void 0 : _a.type } }); log.verbose(prefix, "Used strategy:", log.chalk.bold("esbuild")); return getDefaultExport(result); } catch (err) { errors.push(new Error(`${prefix} Failed to load file with ${log.chalk.bold("esbuild")}: ${err}`)); } if (errors.length > 0) throw new AggregateError(errors, "All parsing strategies failed."); } function createLoader(options) { const { fileName, ...cosmicOptions } = validators.cosmiconfigOptions(options); const mergedOptions = merge({ loaders: { ...defaultLoaders, ".ts": ecmaScriptLoader, ".tsx": ecmaScriptLoader, ".mts": ecmaScriptLoader, ".cts": ecmaScriptLoader, ".js": ecmaScriptLoader, ".jsx": ecmaScriptLoader, ".mjs": ecmaScriptLoader, ".cjs": ecmaScriptLoader }, searchPlaces: [ `${fileName}.config.ts`, `${fileName}.config.tsx`, `${fileName}.config.mts`, `${fileName}.config.cts`, `${fileName}.config.js`, `${fileName}.config.jsx`, `${fileName}.config.mjs`, `${fileName}.config.cjs`, `${fileName}rc.ts`, `${fileName}rc.tsx`, `${fileName}rc.mts`, `${fileName}rc.cts`, `${fileName}rc.js`, `${fileName}rc.jsx`, `${fileName}rc.mjs`, `${fileName}rc.cjs`, `.${fileName}.json`, `.${fileName}.yaml`, `.${fileName}.yml`, `.${fileName}rc`, "package.json" ] }, cosmicOptions, { arrayMerge: (target, source) => { return [...source, ...target]; } }); const explorer = cosmiconfig(fileName, mergedOptions); return { load: async (filePath) => { const result = await explorer.load(filePath); if (result) return result; }, search: async (searchFrom) => { const result = await explorer.search(searchFrom); if (result) return result; } }; } export { createLoader as default }; //# sourceMappingURL=loader.js.map