/
method-signature-style.ts
236 lines (217 loc) · 7.11 KB
/
method-signature-style.ts
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
228
229
230
231
232
233
234
235
236
import {
AST_NODE_TYPES,
TSESTree,
} from '@typescript-eslint/experimental-utils';
import * as util from '../util';
export type Options = [('property' | 'method')?];
export type MessageIds = 'errorMethod' | 'errorProperty';
export default util.createRule<Options, MessageIds>({
name: 'method-signature-style',
meta: {
type: 'suggestion',
docs: {
description: 'Enforces using a particular method signature syntax.',
category: 'Best Practices',
recommended: false,
},
fixable: 'code',
messages: {
errorMethod:
'Shorthand method signature is forbidden. Use a function property instead.',
errorProperty:
'Function property signature is forbidden. Use a method shorthand instead.',
},
schema: [
{
enum: ['property', 'method'],
},
],
},
defaultOptions: ['property'],
create(context, [mode]) {
const sourceCode = context.getSourceCode();
function getMethodKey(
node: TSESTree.TSMethodSignature | TSESTree.TSPropertySignature,
): string {
let key = sourceCode.getText(node.key);
if (node.computed) {
key = `[${key}]`;
}
if (node.optional) {
key = `${key}?`;
}
if (node.readonly) {
key = `readonly ${key}`;
}
return key;
}
function getMethodParams(
node: TSESTree.TSMethodSignature | TSESTree.TSFunctionType,
): string {
let params = '()';
if (node.params.length > 0) {
const openingParen = util.nullThrows(
sourceCode.getTokenBefore(node.params[0], util.isOpeningParenToken),
'Missing opening paren before first parameter',
);
const closingParen = util.nullThrows(
sourceCode.getTokenAfter(
node.params[node.params.length - 1],
util.isClosingParenToken,
),
'Missing closing paren after last parameter',
);
params = sourceCode.text.substring(
openingParen.range[0],
closingParen.range[1],
);
}
if (node.typeParameters != null) {
const typeParams = sourceCode.getText(node.typeParameters);
params = `${typeParams}${params}`;
}
return params;
}
function getMethodReturnType(
node: TSESTree.TSMethodSignature | TSESTree.TSFunctionType,
): string {
return sourceCode.getText(node.returnType!.typeAnnotation);
}
function getDelimiter(node: TSESTree.Node): string {
const lastToken = sourceCode.getLastToken(node);
if (
lastToken &&
(util.isSemicolonToken(lastToken) || util.isCommaToken(lastToken))
) {
return lastToken.value;
}
return '';
}
function isNodeParentModuleDeclaration(node: TSESTree.Node): boolean {
if (!node.parent) {
return false;
}
if (node.parent.type === AST_NODE_TYPES.TSModuleDeclaration) {
return true;
}
if (node.parent.type === AST_NODE_TYPES.Program) {
return false;
}
return isNodeParentModuleDeclaration(node.parent);
}
return {
TSMethodSignature(methodNode): void {
if (mode === 'method') {
return;
}
const parent = methodNode.parent;
const members =
parent?.type === AST_NODE_TYPES.TSInterfaceBody
? parent.body
: parent?.type === AST_NODE_TYPES.TSTypeLiteral
? parent.members
: [];
const duplicatedKeyMethodNodes: TSESTree.TSMethodSignature[] = members.filter(
(element): element is TSESTree.TSMethodSignature =>
element.type === AST_NODE_TYPES.TSMethodSignature &&
element !== methodNode &&
getMethodKey(element) === getMethodKey(methodNode),
);
const isParentModule = isNodeParentModuleDeclaration(methodNode);
if (duplicatedKeyMethodNodes.length > 0) {
if (isParentModule) {
context.report({
node: methodNode,
messageId: 'errorMethod',
});
} else {
context.report({
node: methodNode,
messageId: 'errorMethod',
*fix(fixer) {
const methodNodes = [
methodNode,
...duplicatedKeyMethodNodes,
].sort((a, b) => (a.range[0] < b.range[0] ? -1 : 1));
const typeString = methodNodes.reduce(
(str, node, idx, nodes) => {
const params = getMethodParams(node);
const returnType = getMethodReturnType(node);
return `${str}(${params} => ${returnType})${
idx !== nodes.length - 1 ? ' & ' : ''
}`;
},
'',
);
const key = getMethodKey(methodNode);
const delimiter = getDelimiter(methodNode);
yield fixer.replaceText(
methodNode,
`${key}: ${typeString}${delimiter}`,
);
for (const node of duplicatedKeyMethodNodes) {
const lastToken = sourceCode.getLastToken(node);
if (lastToken) {
const nextToken = sourceCode.getTokenAfter(lastToken);
if (nextToken) {
yield fixer.remove(node);
yield fixer.replaceTextRange(
[lastToken.range[1], nextToken.range[0]],
'',
);
}
}
}
},
});
}
return;
}
if (isParentModule) {
context.report({
node: methodNode,
messageId: 'errorMethod',
});
} else {
context.report({
node: methodNode,
messageId: 'errorMethod',
fix: fixer => {
const key = getMethodKey(methodNode);
const params = getMethodParams(methodNode);
const returnType = getMethodReturnType(methodNode);
const delimiter = getDelimiter(methodNode);
return fixer.replaceText(
methodNode,
`${key}: ${params} => ${returnType}${delimiter}`,
);
},
});
}
},
TSPropertySignature(propertyNode): void {
const typeNode = propertyNode.typeAnnotation?.typeAnnotation;
if (typeNode?.type !== AST_NODE_TYPES.TSFunctionType) {
return;
}
if (mode === 'property') {
return;
}
context.report({
node: propertyNode,
messageId: 'errorProperty',
fix: fixer => {
const key = getMethodKey(propertyNode);
const params = getMethodParams(typeNode);
const returnType = getMethodReturnType(typeNode);
const delimiter = getDelimiter(propertyNode);
return fixer.replaceText(
propertyNode,
`${key}${params}: ${returnType}${delimiter}`,
);
},
});
},
};
},
});