rc-config-loader.ts
6.63 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
// MIT © 2017 azu
// MIT © Zoltan Kochan
// Original https://github.com/zkochan/rcfile
import path from "path";
import fs from "fs";
import requireFromString from "require-from-string";
import JSON5 from "json5";
const debug = require("debug")("rc-config-loader");
const defaultLoaderByExt = {
".cjs": loadJSConfigFile,
".js": loadJSConfigFile,
".json": loadJSONConfigFile,
".yaml": loadYAMLConfigFile,
".yml": loadYAMLConfigFile,
};
const defaultOptions = {
// does look for `package.json`
packageJSON: false,
// treat default(no ext file) as some extension
defaultExtension: [".json", ".yaml", ".yml", ".js", ".cjs"],
cwd: process.cwd(),
};
export interface rcConfigLoaderOption {
// does look for `package.json`
packageJSON?:
| boolean
| {
fieldName: string;
};
// if config file name is not same with packageName, set the name
configFileName?: string;
// treat default(no ext file) as some extension
defaultExtension?: string | string[];
// where start to load
cwd?: string;
}
type Loader = <R extends object>(fileName: string, suppress: boolean) => R;
const selectLoader = (defaultLoaderByExt: { [index: string]: Loader }, extension: string) => {
if (!defaultOptions.defaultExtension.includes(extension)) {
throw new Error(`${extension} is not supported.`);
}
return defaultLoaderByExt[extension];
};
/**
* Find and load rcfile, return { config, filePath }
* If not found any rcfile, throw an Error.
* @param {string} pkgName
* @param {rcConfigLoaderOption} [opts]
* @returns {{ config: Object, filePath:string } | undefined}
*/
export function rcFile<R extends {}>(
pkgName: string,
opts: rcConfigLoaderOption = {}
):
| {
config: R;
filePath: string;
}
| undefined {
// path/to/config or basename of config file.
const configFileName = opts.configFileName || `.${pkgName}rc`;
const defaultExtension = opts.defaultExtension || defaultOptions.defaultExtension;
const cwd = opts.cwd || defaultOptions.cwd;
const packageJSON = opts.packageJSON || defaultOptions.packageJSON;
const packageJSONFieldName = typeof packageJSON === "object" ? packageJSON.fieldName : pkgName;
const parts = splitPath(cwd);
const loadersByOrder = Array.isArray(defaultExtension)
? defaultExtension.map((extension) => selectLoader(defaultLoaderByExt, extension))
: selectLoader(defaultLoaderByExt, defaultExtension);
const loaderByExt = {
...defaultLoaderByExt,
"": loadersByOrder,
};
return findConfig<R>({
parts,
loaderByExt,
loadersByOrder,
configFileName,
packageJSON,
packageJSONFieldName,
});
}
/**
*
* @returns {{
* config: string,
* filePath: string
* }}
*/
function findConfig<R extends {}>({
parts,
loaderByExt,
loadersByOrder,
configFileName,
packageJSON,
packageJSONFieldName,
}: {
parts: string[];
loaderByExt: {
[index: string]: Loader | Loader[];
};
loadersByOrder: Loader | Loader[];
configFileName: string;
packageJSON: boolean | { fieldName: string };
packageJSONFieldName: string;
}):
| {
config: R;
filePath: string;
}
| undefined {
const extensions = Object.keys(loaderByExt);
while (extensions.length) {
const ext = extensions.shift();
// may be ext is "". if it .<product>rc
const configLocation = join(parts, configFileName + ext);
if (!fs.existsSync(configLocation)) {
continue;
}
// if ext === ""(empty string):, use ordered loaders
const loaders = ext ? loaderByExt[ext] : loadersByOrder;
if (!Array.isArray(loaders)) {
const loader = loaders;
const result = loader<R>(configLocation, false);
if (!result) {
continue;
}
return {
config: result,
filePath: configLocation,
};
}
for (let i = 0; i < loaders.length; i++) {
const loader = loaders[i];
const result = loader<R>(configLocation, true);
if (!result) {
continue;
}
return {
config: result,
filePath: configLocation,
};
}
}
if (packageJSON) {
const pkgJSONLoc = join(parts, "package.json");
if (fs.existsSync(pkgJSONLoc)) {
const pkgJSON = require(pkgJSONLoc);
if (pkgJSON[packageJSONFieldName]) {
return {
config: pkgJSON[packageJSONFieldName],
filePath: pkgJSONLoc,
};
}
}
}
if (parts.pop()) {
return findConfig({ parts, loaderByExt, loadersByOrder, configFileName, packageJSON, packageJSONFieldName });
}
return;
}
function splitPath(x: string): string[] {
return path.resolve(x || "").split(path.sep);
}
function join(parts: string[], filename: string) {
return path.resolve(parts.join(path.sep) + path.sep, filename);
}
function loadJSConfigFile(filePath: string, suppress: boolean) {
debug(`Loading JavaScript config file: ${filePath}`);
try {
const content = fs.readFileSync(filePath, "utf-8");
return requireFromString(content, filePath);
} catch (error) {
debug(`Error reading JavaScript file: ${filePath}`);
if (!suppress) {
error.message = `Cannot read config file: ${filePath}\nError: ${error.message}`;
throw error;
}
}
}
function loadJSONConfigFile(filePath: string, suppress: boolean) {
debug(`Loading JSON config file: ${filePath}`);
try {
return JSON5.parse(readFile(filePath));
} catch (error) {
debug(`Error reading JSON file: ${filePath}`);
if (!suppress) {
error.message = `Cannot read config file: ${filePath}\nError: ${error.message}`;
throw error;
}
}
}
function readFile(filePath: string) {
return fs.readFileSync(filePath, "utf8");
}
function loadYAMLConfigFile(filePath: string, suppress: boolean) {
debug(`Loading YAML config file: ${filePath}`);
// lazy load YAML to improve performance when not used
const yaml = require("js-yaml");
try {
// empty YAML file can be null, so always use
return yaml.load(readFile(filePath)) || {};
} catch (error) {
debug(`Error reading YAML file: ${filePath}`);
if (!suppress) {
error.message = `Cannot read config file: ${filePath}\nError: ${error.message}`;
throw error;
}
}
}