-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathindex.js
55 lines (40 loc) · 1.55 KB
/
index.js
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
import path from 'node:path';
import {findUp, findUpSync} from 'find-up-simple';
import {loadJsonFile, loadJsonFileSync} from 'load-json-file';
const filePaths = new WeakMap();
const findNextCwd = packagePath => path.resolve(path.dirname(packagePath), '..');
const addFilePath = (object, filePath) => {
filePaths.set(object, filePath);
return object;
};
export async function packageConfig(namespace, options = {}) {
if (!namespace) {
throw new TypeError('Expected a namespace');
}
const filePath = await findUp('package.json', options.cwd ? {cwd: options.cwd} : {});
if (!filePath) {
return addFilePath({...options.defaults}, filePath);
}
const packageJson = await loadJsonFile(filePath);
if (options.skipOnFalse && packageJson[namespace] === false) {
return packageConfig(namespace, {...options, cwd: findNextCwd(filePath)});
}
return addFilePath({...options.defaults, ...packageJson[namespace]}, filePath);
}
export function packageConfigSync(namespace, options = {}) {
if (!namespace) {
throw new TypeError('Expected a namespace');
}
const filePath = findUpSync('package.json', options.cwd ? {cwd: options.cwd} : {});
if (!filePath) {
return addFilePath({...options.defaults}, filePath);
}
const packageJson = loadJsonFileSync(filePath);
if (options.skipOnFalse && packageJson[namespace] === false) {
return packageConfigSync(namespace, {...options, cwd: findNextCwd(filePath)});
}
return addFilePath({...options.defaults, ...packageJson[namespace]}, filePath);
}
export function packageJsonPath(config) {
return filePaths.get(config);
}