forked from angular-eslint/angular-eslint
/
processors.ts
280 lines (247 loc) · 8.1 KB
/
processors.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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
import { basename } from 'path';
import { getDecorators } from '@typescript-eslint/type-utils';
import ts from 'typescript';
const rangeMap = new Map();
/**
* Because ultimately a user is in control of how and when this processor gets invoked,
* we can't fully protect them against doing more work than is necessary in all cases.
*
* Therefore, before we do a full parse of a TypeScript file to try and extract one or
* more Component declarations we want to do a really quick check for whether or not
* a file is likely to contain them.
*/
export function isFileLikelyToContainComponentDeclarations(
text: string,
filename: string,
): boolean {
/**
* Quickest possible heuristic is based on file extension suffix
*/
if (
[
'.component.ts',
'.page.ts',
'.dialog.ts',
'.modal.ts',
'.popover.ts',
'.bottomsheet.ts',
'.snackbar.ts',
].some((likelySuffix) => filename.endsWith(likelySuffix))
) {
return true;
}
/**
* Next quickest possible heuristic is the presence of the substring 'Component'
* and the substring '@angular/core' within the file contents
*/
if (text.includes('Component') && text.includes('@angular/core')) {
return true;
}
return false;
}
type PreprocessResult = (string | { text: string; filename: string })[];
export function preprocessComponentFile(
text: string,
filename: string,
): PreprocessResult {
// This effectively instructs ESLint that there were no code blocks to extract for the current file
const noopResult = [text];
if (!isFileLikelyToContainComponentDeclarations(text, filename)) {
return noopResult;
}
try {
const sourceFile = ts.createSourceFile(
filename,
text,
ts.ScriptTarget.Latest,
/* setParentNodes */ true,
);
const classDeclarations = sourceFile.statements.filter((s) =>
ts.isClassDeclaration(s),
) as ts.ClassDeclaration[];
if (!classDeclarations || !classDeclarations.length) {
return noopResult;
}
/**
* Find all the Component decorators
*/
const componentDecoratorNodes: ts.Decorator[] = [];
for (const classDeclaration of classDeclarations) {
// NOTE: Intentionally not using ts.getDecorators() as it did not exist prior to TS 4.8
const classDecorators = getDecorators(classDeclaration);
if (!classDecorators) {
continue;
}
for (const decorator of classDecorators) {
if (
ts.isCallExpression(decorator.expression) &&
ts.isIdentifier(decorator.expression.expression) &&
decorator.expression.expression.text === 'Component'
) {
componentDecoratorNodes.push(decorator);
}
}
}
/**
* Ignore malformed Component files
*/
if (!componentDecoratorNodes || !componentDecoratorNodes.length) {
return noopResult;
}
const result: PreprocessResult = [text];
let id = 0;
for (const componentDecoratorNode of componentDecoratorNodes) {
/**
* Ignore malformed component metadata
*/
if (
!ts.isDecorator(componentDecoratorNode) ||
!ts.isCallExpression(componentDecoratorNode.expression) ||
componentDecoratorNode.expression.arguments.length !== 1
) {
continue;
}
const metadata = componentDecoratorNode.expression.arguments[0];
if (!ts.isObjectLiteralExpression(metadata)) {
continue;
}
/**
* Ignore Components which have external template files, they will be linted directly,
* and any that have inline templates which are malformed
*/
const templateProperty = metadata.properties.find(
(id) => id && id.name && id.name.getText() === 'template',
);
if (
metadata.properties.find(
(id) => id && id.name && id.name.getText() === 'templateUrl',
) ||
!templateProperty
) {
continue;
}
if (!ts.isPropertyAssignment(templateProperty)) {
continue;
}
let templateText: string | undefined;
const templatePropertyInitializer = templateProperty.initializer;
if (ts.isNoSubstitutionTemplateLiteral(templatePropertyInitializer)) {
templateText = templatePropertyInitializer.rawText;
}
if (ts.isTemplateExpression(templatePropertyInitializer)) {
templateText = templatePropertyInitializer.getText();
}
if (ts.isStringLiteral(templatePropertyInitializer)) {
templateText = templatePropertyInitializer.text;
}
// The template initializer is somehow not a string literal or a string template
if (!templateText) {
continue;
}
const baseFilename = basename(filename);
const inlineTemplateTmpFilename = `inline-template-${baseFilename}-${++id}.component.html`;
const start = templateProperty.initializer.getStart();
const end = templateProperty.initializer.getEnd();
rangeMap.set(inlineTemplateTmpFilename, {
range: [start, end],
lineAndCharacter: {
start: sourceFile.getLineAndCharacterOfPosition(start),
end: sourceFile.getLineAndCharacterOfPosition(end),
},
});
/**
* We are ultimately returning an array containing both the original source,
* and a new fragment representing each of the inline HTML templates found.
* Each fragment must have an appropriate .html extension so that it can be
* linted using the right rules and plugins.
*
* The postprocessor will handle tying things back to the right position
* in the original file, so this temporary filename will never be visible
* to the end user.
*/
result.push({
text: templateText,
filename: inlineTemplateTmpFilename,
});
}
return result;
} catch (err) {
console.log(err);
console.error(
'preprocess: ERROR could not parse @Component() metadata',
filename,
);
return noopResult;
}
}
export function postprocessComponentFile(
multiDimensionalMessages: {
ruleId: string;
severity: number;
message: string;
line: number;
column: number;
nodeType: string;
messageId: string;
endLine: number;
endColumn: number;
fix?: {
range: number[];
text: string;
};
}[][],
filename: string,
): readonly unknown[] {
const messagesFromComponentSource = multiDimensionalMessages[0];
/**
* If the Component did not have one or more inline templates defined within it
* there will only be one item in the multiDimensionalMessages
*/
if (multiDimensionalMessages.length === 1) {
return messagesFromComponentSource;
}
/**
* There could be multiple inline templates found within the current file,
* so they are represented by all of the multiDimensionalMessages after the
* first one (which is the file itself)
*/
const messagesFromAllInlineTemplateHTML = multiDimensionalMessages.slice(1);
/**
* Adjust message location data to apply it back to the
* original file
*/
const res = [
...messagesFromComponentSource,
...messagesFromAllInlineTemplateHTML.flatMap(
(messagesFromInlineTemplateHTML, i) => {
const baseFilename = basename(filename);
const inlineTemplateTmpFilename = `inline-template-${baseFilename}-${++i}.component.html`;
const rangeData = rangeMap.get(inlineTemplateTmpFilename);
if (!rangeData) {
return [];
}
return messagesFromInlineTemplateHTML.map((message) => {
message.line = message.line + rangeData.lineAndCharacter.start.line;
message.endLine =
message.endLine + rangeData.lineAndCharacter.start.line;
if (message.fix) {
const startOffset = rangeData.range[0];
message.fix.range = [
startOffset + message.fix.range[0],
startOffset + message.fix.range[1],
];
}
return message;
});
},
),
];
return res;
}
export default {
'extract-inline-html': {
preprocess: preprocessComponentFile,
postprocess: postprocessComponentFile,
supportsAutofix: true,
},
};