/
hint.ts
198 lines (155 loc) · 6.38 KB
/
hint.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
/**
* @fileoverview Validating html using `the Nu HTML checker`;
* https://validator.w3.org/nu/
*/
/*
* ------------------------------------------------------------------------------
* Requirements
* ------------------------------------------------------------------------------
*/
import uniqBy = require('lodash/uniqBy');
import { OptionsWithUrl } from 'request';
import { debug as d } from '@hint/utils-debug';
import { HintContext, IHint } from 'hint';
import { ProblemLocation, Severity } from '@hint/utils-types';
import { HTMLEvents, HTMLParse } from '@hint/parser-html';
import meta from './meta';
import { getMessage } from './i18n.import';
const debug: debug.IDebugger = d(__filename);
type CheckerData = {
event: HTMLParse;
failed: boolean;
promise: Promise<any>;
};
/*
* ------------------------------------------------------------------------------
* Public
* ------------------------------------------------------------------------------
*/
export default class HtmlCheckerHint implements IHint {
public static readonly meta = meta;
public constructor(context: HintContext<HTMLEvents>) {
/** The promise that represents the scan by HTML checker. */
let htmlCheckerPromises: CheckerData[] = [];
/** Array of strings that needes to be ignored from the checker result. */
let ignoredMessages: string[];
/** The options to pass to the HTML checker. */
const scanOptions = {
body: '',
headers: {
'Content-Type': 'text/html; charset=utf-8',
'User-Agent': 'hint'
},
method: 'POST',
qs: { out: 'json' },
url: ''
};
/** If the result messages should be grouped. */
let groupMessage: boolean;
type HtmlError = {
extract: string; // code snippet
firstColumn: number;
lastLine: number;
hiliteStart: number;
message: string;
subType: keyof typeof Severity;
};
const loadHintConfig = () => {
const ignore = (context.hintOptions && context.hintOptions.ignore) || [];
const validator = (context.hintOptions && context.hintOptions.validator) || 'https://validator.w3.org/nu/';
groupMessage = !(context.hintOptions && context.hintOptions.details);
scanOptions.url = validator;
ignoredMessages = Array.isArray(ignore) ? ignore : [ignore];
};
// Filter out ignored and redundant messages.
const filter = (messages: HtmlError[]): HtmlError[] => {
const noIgnoredMesssages = messages.filter((message) => {
return !ignoredMessages.includes(message.message);
});
if (!groupMessage) {
return noIgnoredMesssages;
}
return uniqBy(noIgnoredMesssages, 'message');
};
const locateAndReport = (resource: string) => {
return (messageItem: HtmlError): void => {
const position: ProblemLocation = {
column: messageItem.firstColumn,
elementColumn: messageItem.hiliteStart + 1,
elementLine: 1, // We will pass in the single-line code snippet generated from the HTML checker, so the elementLine is always 1
line: messageItem.lastLine
};
context.report(resource, messageItem.message, {
codeLanguage: 'html',
codeSnippet: messageItem.extract,
location: position,
severity: Severity[messageItem.subType]
});
};
};
const notifyError = (resource: string, error: any) => {
debug(`Error getting HTML checker result for ${resource}.`, error);
context.report(resource, getMessage('couldNotGetResult', context.language, [resource, error.toString()]));
};
const requestRetry = async (options: OptionsWithUrl, retries: number = 3): Promise<any> => {
const requestAsync = (await import('@hint/utils-network')).requestAsync;
const delay = (await import('@hint/utils')).delay;
try {
return await requestAsync(options);
} catch (e) {
if (retries === 0) {
throw e;
}
await delay(500);
return await requestRetry(options, retries - 1);
}
};
const checkHTML = (data: HTMLParse): CheckerData => {
const options = Object.assign({}, scanOptions, { body: data.html });
return {
event: data,
failed: false,
promise: options.body ? requestRetry(options) : Promise.resolve({ messages: [] })
};
};
const start = (data: HTMLParse) => {
const check: CheckerData = checkHTML(data);
htmlCheckerPromises.push(check);
};
const end = async () => {
if (htmlCheckerPromises.length === 0) {
return;
}
for (const check of htmlCheckerPromises) {
if (check.failed) {
return;
}
const { resource } = check.event;
const locateAndReportByResource = locateAndReport(resource);
let result;
debug(`Waiting for HTML checker results for ${resource}`);
try {
result = JSON.parse(await check.promise);
} catch (e) {
notifyError(resource, e);
return;
}
debug(`Received HTML checker results for ${resource}`);
const filteredMessages: HtmlError[] = filter(result.messages);
try {
filteredMessages.forEach((messageItem: HtmlError) => {
locateAndReportByResource(messageItem);
});
} catch (e) {
debug(`Error reporting the HTML checker results.`, e);
return;
}
}
// Clear htmlCheckerPromises for watcher.
htmlCheckerPromises = [];
};
loadHintConfig();
context.on('parse::end::html', start);
context.on('scan::end', end);
}
}