-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathindex.mjs
More file actions
59 lines (49 loc) · 1.83 KB
/
index.mjs
File metadata and controls
59 lines (49 loc) · 1.83 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
const { fromEntries } = Object;
/** @type {(contentsStr: string) => string[]} */
function parseRawOptions(contentsStr) {
return contentsStr
.split('\n')
.map((x) => x.replace(/#.*$/, '').trim())
.filter(Boolean);
}
/** @type {(rawOptions: string[]) => [string, string][]} */
function parseOptionsEntries(rawOptions) {
return rawOptions.map((x) => ((/[=]/).test(x)
? x.split('=').map((y) => y.trim())
: /** @type {const} */ (['node', x])
));
}
/** @type {(rawOptions: string[], optionsEntries: [string, string][], map: Map<string, string>) => boolean} */
export function isValidNVMRC(rawOptions, optionsEntries, map) {
return !(
map.size !== optionsEntries.length
|| !map.has('node')
|| rawOptions.filter((x) => !x.includes('=')).length !== 1
|| (/^\s*[~^><=]/).test(map.get('node').trim())
);
}
/** @typedef {{ success: true, options: Record<string, string> }} ParseResult */
/** @typedef {{ success: false, errorMessage: string, rawOptions: string[] }} ParseError */
const ERROR_MESSAGE = `invalid .nvmrc!
all non-commented content (anything after # is a comment) must be either:
- a single bare nvm-recognized version-ish
- or, multiple distinct key-value pairs, each key/value separated by a single equals sign (=)
additionally, a single bare nvm-recognized version-ish must be present (after stripping comments).
Note that nvm does not understand semver ranges.`;
/** @type {(contentsStr: string) => ParseResult | ParseError} */
export default function parseNVMRC(contentsStr) {
const rawOptions = parseRawOptions(contentsStr);
const optionsEntries = parseOptionsEntries(rawOptions);
const map = new Map(optionsEntries);
if (!isValidNVMRC(rawOptions, optionsEntries, map)) {
return {
errorMessage: ERROR_MESSAGE,
rawOptions,
success: false,
};
}
return {
options: fromEntries(optionsEntries),
success: true,
};
}