-
Notifications
You must be signed in to change notification settings - Fork 14
/
delegation.js
65 lines (53 loc) · 1.68 KB
/
delegation.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
export function createDelegatee(config, rootContext) {
const { definition, options } = config;
if (!definition) {
// May need to update the es-x dependency, or check that the lookup name is not
// prefixed with es-x/
throw new Error('Rule instance not given');
}
// All except report() are added later. Define necessary ones for used rules.
// https://eslint.org/docs/latest/extend/custom-rules#the-context-object
const contextLaterAdded = {
getScope: () => rootContext.getScope(),
getSourceCode: () => rootContext.getSourceCode(),
get settings() {
return rootContext.settings;
},
get parserServices() {
return rootContext.parserServices;
},
};
// Would use ES Proxy, but context's properties aren't overridable
const context = {
...rootContext,
...contextLaterAdded,
options,
report,
};
function report(params) {
// Discard fixer; we can't declare the rule as fixable because not all delegatees are.
// Look up messageId on delegate meta; report() would look it up on root rule meta.
const { fix, message, messageId, ...otherParams } = params;
rootContext.report({
...otherParams,
message: messageId ? definition.meta.messages[messageId] : message,
});
}
return definition.create(context);
}
export function delegatingVisitor(delegatees) {
const delegator = {};
delegatees.forEach((visitor) => {
for (const [key] of Object.entries(visitor)) {
delegator[key] = (...args) => delegate(key, args);
}
});
function delegate(key, args) {
delegatees.forEach((visitor) => {
if (visitor[key]) {
visitor[key](...args);
}
});
}
return delegator;
}