UNPKG

6.12 kBJavaScriptView Raw
1"use strict";
2var __importDefault = (this && this.__importDefault) || function (mod) {
3 return (mod && mod.__esModule) ? mod : { "default": mod };
4};
5Object.defineProperty(exports, "__esModule", { value: true });
6exports.rcFile = void 0;
7// MIT © 2017 azu
8// MIT © Zoltan Kochan
9// Original https://github.com/zkochan/rcfile
10const path_1 = __importDefault(require("path"));
11const fs_1 = __importDefault(require("fs"));
12const require_from_string_1 = __importDefault(require("require-from-string"));
13const json5_1 = __importDefault(require("json5"));
14const debug = require("debug")("rc-config-loader");
15const defaultLoaderByExt = {
16 ".cjs": loadJSConfigFile,
17 ".js": loadJSConfigFile,
18 ".json": loadJSONConfigFile,
19 ".yaml": loadYAMLConfigFile,
20 ".yml": loadYAMLConfigFile
21};
22const defaultOptions = {
23 packageJSON: false,
24 defaultExtension: [".json", ".yaml", ".yml", ".js", ".cjs"],
25 cwd: process.cwd()
26};
27const selectLoader = (defaultLoaderByExt, extension) => {
28 if (!defaultOptions.defaultExtension.includes(extension)) {
29 throw new Error(`${extension} is not supported.`);
30 }
31 return defaultLoaderByExt[extension];
32};
33/**
34 * Find and load rcfile, return { config, filePath }
35 * If not found any rcfile, throw an Error.
36 * @param {string} pkgName
37 * @param {rcConfigLoaderOption} [opts]
38 * @returns {{ config: Object, filePath:string } | undefined}
39 */
40function rcFile(pkgName, opts = {}) {
41 // path/to/config or basename of config file.
42 const configFileName = opts.configFileName || `.${pkgName}rc`;
43 const defaultExtension = opts.defaultExtension || defaultOptions.defaultExtension;
44 const cwd = opts.cwd || defaultOptions.cwd;
45 const packageJSON = opts.packageJSON || defaultOptions.packageJSON;
46 const packageJSONFieldName = typeof packageJSON === "object" ? packageJSON.fieldName : pkgName;
47 const parts = splitPath(cwd);
48 const loadersByOrder = Array.isArray(defaultExtension)
49 ? defaultExtension.map((extension) => selectLoader(defaultLoaderByExt, extension))
50 : selectLoader(defaultLoaderByExt, defaultExtension);
51 const loaderByExt = Object.assign(Object.assign({}, defaultLoaderByExt), { "": loadersByOrder });
52 return findConfig({
53 parts,
54 loaderByExt,
55 loadersByOrder,
56 configFileName,
57 packageJSON,
58 packageJSONFieldName
59 });
60}
61exports.rcFile = rcFile;
62/**
63 *
64 * @returns {{
65 * config: string,
66 * filePath: string
67 * }}
68 */
69function findConfig({ parts, loaderByExt, loadersByOrder, configFileName, packageJSON, packageJSONFieldName }) {
70 const extensions = Object.keys(loaderByExt);
71 while (extensions.length) {
72 const ext = extensions.shift();
73 // may be ext is "". if it .<product>rc
74 const configLocation = join(parts, configFileName + ext);
75 if (!fs_1.default.existsSync(configLocation)) {
76 continue;
77 }
78 // if ext === ""(empty string):, use ordered loaders
79 const loaders = ext ? loaderByExt[ext] : loadersByOrder;
80 if (!Array.isArray(loaders)) {
81 const loader = loaders;
82 const result = loader(configLocation, false);
83 if (!result) {
84 continue;
85 }
86 return {
87 config: result,
88 filePath: configLocation
89 };
90 }
91 for (let i = 0; i < loaders.length; i++) {
92 const loader = loaders[i];
93 const result = loader(configLocation, true);
94 if (!result) {
95 continue;
96 }
97 return {
98 config: result,
99 filePath: configLocation
100 };
101 }
102 }
103 if (packageJSON) {
104 const pkgJSONLoc = join(parts, "package.json");
105 if (fs_1.default.existsSync(pkgJSONLoc)) {
106 const pkgJSON = json5_1.default.parse(readFile(pkgJSONLoc));
107 if (pkgJSON[packageJSONFieldName]) {
108 return {
109 config: pkgJSON[packageJSONFieldName],
110 filePath: pkgJSONLoc
111 };
112 }
113 }
114 }
115 if (parts.pop()) {
116 return findConfig({ parts, loaderByExt, loadersByOrder, configFileName, packageJSON, packageJSONFieldName });
117 }
118 return;
119}
120function splitPath(x) {
121 return path_1.default.resolve(x || "").split(path_1.default.sep);
122}
123function join(parts, filename) {
124 return path_1.default.resolve(parts.join(path_1.default.sep) + path_1.default.sep, filename);
125}
126function loadJSConfigFile(filePath, suppress) {
127 debug(`Loading JavaScript config file: ${filePath}`);
128 try {
129 const content = fs_1.default.readFileSync(filePath, "utf-8");
130 return (0, require_from_string_1.default)(content, filePath);
131 }
132 catch (error) {
133 debug(`Error reading JavaScript file: ${filePath}`);
134 if (!suppress) {
135 error.message = `Cannot read config file: ${filePath}\nError: ${error.message}`;
136 throw error;
137 }
138 }
139}
140function loadJSONConfigFile(filePath, suppress) {
141 debug(`Loading JSON config file: ${filePath}`);
142 try {
143 return json5_1.default.parse(readFile(filePath));
144 }
145 catch (error) {
146 debug(`Error reading JSON file: ${filePath}`);
147 if (!suppress) {
148 error.message = `Cannot read config file: ${filePath}\nError: ${error.message}`;
149 throw error;
150 }
151 }
152}
153function readFile(filePath) {
154 return fs_1.default.readFileSync(filePath, "utf8");
155}
156function loadYAMLConfigFile(filePath, suppress) {
157 debug(`Loading YAML config file: ${filePath}`);
158 // lazy load YAML to improve performance when not used
159 const yaml = require("js-yaml");
160 try {
161 // empty YAML file can be null, so always use
162 return yaml.load(readFile(filePath)) || {};
163 }
164 catch (error) {
165 debug(`Error reading YAML file: ${filePath}`);
166 if (!suppress) {
167 error.message = `Cannot read config file: ${filePath}\nError: ${error.message}`;
168 throw error;
169 }
170 }
171}
172//# sourceMappingURL=rc-config-loader.js.map
\No newline at end of file