forked from dollarshaveclub/es-check
-
Notifications
You must be signed in to change notification settings - Fork 15
/
detectFeatures.js
83 lines (73 loc) · 2.3 KB
/
detectFeatures.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
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
const acorn = require('acorn');
const walk = require('acorn-walk');
const { ES_FEATURES } = require('./constants');
const { checkMap } = require('./utils');
const detectFeatures = (code, ecmaVersion, sourceType) => {
const ast = acorn.parse(code, {
ecmaVersion: 'latest',
sourceType,
});
/**
* @note Flatten all checks
*/
const allChecks = Object.entries(ES_FEATURES).map(([featureName, { astInfo }]) => ({
featureName,
nodeType: astInfo.nodeType,
astInfo,
}));
/**
* @note A universal visitor for any node type:
* - Filters checks that match the current node’s type
* - Calls the relevant checker function
* - If true => mark the feature as found
*/
const foundFeatures = Object.keys(ES_FEATURES).reduce((acc, f) => {
acc[f] = false;
return acc;
}, {});
const universalVisitor = (node) => {
allChecks
.filter(({ nodeType }) => nodeType === node.type)
.forEach(({ featureName, astInfo }) => {
const checker = checkMap[node.type] || checkMap.default;
if (checker(node, astInfo)) {
foundFeatures[featureName] = true;
}
});
};
/**
* @note Build the visitors object for acorn-walk.
* Each unique nodeType gets the same universalVisitor.
*/
const nodeTypes = [...new Set(allChecks.map((c) => c.nodeType))];
const visitors = nodeTypes.reduce((acc, nt) => {
acc[nt] = universalVisitor;
return acc;
}, {});
walk.simple(ast, visitors);
/**
* @note Check if any found feature requires a higher version than requested.
* We assume each entry in ES_FEATURES has a `minVersion` property.
*/
const unsupportedFeatures = Object.entries(ES_FEATURES).reduce((acc = [], [featureName, { minVersion }]) => {
// If feature is used but requires a newer version than ecmaVersion, it's unsupported
if (foundFeatures[featureName] && minVersion > ecmaVersion) {
acc.push(featureName);
}
return acc;
}, []);
/**
* @note Fail if any unsupported features were used.
*/
if (unsupportedFeatures.length > 0) {
throw new Error(
`Unsupported features detected: ${unsupportedFeatures.join(', ')}. ` +
`These require a higher ES version than ${ecmaVersion}.`
);
}
return {
foundFeatures,
unsupportedFeatures,
}
};
module.exports = detectFeatures;