-
Notifications
You must be signed in to change notification settings - Fork 6.8k
/
Copy pathnoUnescapedHtmlTagRule.ts
63 lines (52 loc) · 2.03 KB
/
noUnescapedHtmlTagRule.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
import ts from 'typescript';
import * as Lint from 'tslint';
import * as utils from 'tsutils';
const ERROR_MESSAGE =
'An HTML tag delimiter (< or >) may only appear in a JSDoc comment if it is escaped.' +
' This prevents failures in document generation caused by a misinterpreted tag.';
/**
* Rule that walks through all comments inside of the library and adds failures when it
* detects unescaped HTML tags inside of multi-line comments.
*/
export class Rule extends Lint.Rules.AbstractRule {
apply(sourceFile: ts.SourceFile) {
return this.applyWithWalker(new NoUnescapedHtmlTagWalker(sourceFile, this.getOptions()));
}
}
class NoUnescapedHtmlTagWalker extends Lint.RuleWalker {
override visitSourceFile(sourceFile: ts.SourceFile) {
utils.forEachComment(sourceFile, (fullText, commentRange) => {
const htmlIsEscaped = this._parseForHtml(
fullText.substring(commentRange.pos, commentRange.end),
);
if (commentRange.kind === ts.SyntaxKind.MultiLineCommentTrivia && !htmlIsEscaped) {
this.addFailureAt(commentRange.pos, commentRange.end - commentRange.pos, ERROR_MESSAGE);
}
});
super.visitSourceFile(sourceFile);
}
/** Gets whether the comment's HTML, if any, is properly escaped */
private _parseForHtml(fullText: string): boolean {
const matches = /[<>]/;
const backtickCount = fullText.split('`').length - 1;
// An odd number of backticks or html without backticks is invalid
if (backtickCount % 2 || (!backtickCount && matches.test(fullText))) {
return false;
}
// Text without html is valid
if (!matches.test(fullText)) {
return true;
}
// < and > must always be between two matching backticks.
// Whether an opening backtick has been found without a closing pair
let openBacktick = false;
for (let i = 0; i < fullText.length; i++) {
if (fullText[i] === '`') {
openBacktick = !openBacktick;
} else if (matches.test(fullText[i]) && !openBacktick) {
return false;
}
}
return true;
}
}