/
engine.ts
354 lines (283 loc) · 12 KB
/
engine.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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
/**
* @fileoverview hint engine object, gets the configuration and loads
* the connectors, hints and analyzes.
*/
/*
* ------------------------------------------------------------------------------
* Requirements
* ------------------------------------------------------------------------------
*/
import * as url from 'url';
import chalk from 'chalk';
import { EventEmitter2 as EventEmitter } from 'eventemitter2';
import remove = require('lodash/remove');
import * as logger from '@hint/utils/dist/src/logging';
import { HttpHeaders } from '@hint/utils/dist/src/types/http-header';
import { debug as d } from '@hint/utils/dist/src/debug';
import { HTMLElement, HTMLDocument } from '@hint/utils/dist/src/dom/html';
import { getSeverity } from './config/config-hints';
import {
Events,
HintConfig,
HintResources,
IConnector,
IConnectorConstructor,
IFetchOptions,
IFormatter,
IHint,
IHintConstructor,
NetworkData,
Parser,
Problem,
ProblemLocation,
Severity,
StringKeyOf
} from './types';
import { HintContext } from './hint-context';
import { HintScope } from './enums/hint-scope';
import { Configuration } from './config';
import { Category } from './enums/category';
const debug: debug.IDebugger = d(__filename);
/*
* ------------------------------------------------------------------------------
* Public interface
* ------------------------------------------------------------------------------
*/
export class Engine<E extends Events = Events> extends EventEmitter {
// TODO: review which ones need to be private or not
private parsers: Parser[]
private hints: Map<string, IHint>
private connector: IConnector
private messages: Problem[]
private browserslist: string[] = [];
private ignoredUrls: Map<string, RegExp[]>;
private _formatters: IFormatter[]
private _timeout: number = 60000;
/** The DOM of the loaded page. */
public get pageDOM(): HTMLDocument | undefined {
return this.connector.dom;
}
/** The HTML of the loaded page. */
public get pageContent(): string | undefined {
return this.connector.html;
}
/** The headers used in the requests. */
public get pageHeaders(): HttpHeaders | undefined {
return this.connector.headers;
}
/** The list of targetted browsers. */
public get targetedBrowsers(): string[] {
return this.browserslist;
}
/** The list of configured formatters. */
public get formatters(): IFormatter[] {
return this._formatters;
}
/** The max time an event should run. */
public get timeout(): number {
return this._timeout;
}
private isIgnored(urls: RegExp[], resource: string): boolean {
if (!urls) {
return false;
}
return urls.some((urlIgnored: RegExp) => {
return urlIgnored.test(resource);
});
}
public constructor(config: Configuration, resources: HintResources) {
super({
delimiter: '::',
maxListeners: 0,
wildcard: true
});
debug('Initializing hint engine');
this._timeout = config.hintsTimeout;
this.messages = [];
this.browserslist = config.browserslist;
this.ignoredUrls = config.ignoredUrls;
const Connector: IConnectorConstructor | null = resources.connector;
const connectorId = config.connector && config.connector.name;
if (!Connector) {
throw new Error(`Connector "${connectorId}" not found`);
}
this.connector = new Connector(this, config.connector && config.connector.options);
this._formatters = resources.formatters.map((Formatter) => {
return new Formatter();
});
this.parsers = resources.parsers.map((ParserConstructor) => {
debug(`Loading parser`);
return new ParserConstructor(this);
});
debug(`Parsers loaded: ${this.parsers.length}`);
this.hints = new Map();
/**
* Returns the configuration for a given hint ID. In the case of a hint
* pointing to a path, it will return the content of the first entry
* in the config that contains the ID. E.g.:
* * `../hint-x-content-type-options` is the key in the config
* * `x-content-type-options` is the ID of the hint
* * One of the keys in the config `includes` the hint ID so it's a match
*
* @param id The id of the hint
*/
const getHintConfig = (id: string): HintConfig | HintConfig[] => {
if (config.hints[id]) {
return config.hints[id];
}
const hintEntries = Object.keys(config.hints);
const idParts = id.split('/');
/**
* At this point we are trying to find the configuration of a hint specified
* via a path.
* The id of a hint (define in `Hint.meta.id`) will be `packageName/hint-id`
* but most likely the code is not going to be on a path that ends like that
* and will be more similar to `packageName/dist/src/hint-id.js`
*
* To solve this, we iterate over all the keys of the `hints` object until
* we find the first entry that includes all the parts of the id
* (`packageName` and `hint-id` in the example).
*
* E.g.:
* * `../hint-packageName/dist/src/hint-id.js` --> Passes
* * `../hint-packageAnotherName/dist/src/hint-id.js` --> Fails because
* `packageName` is not in that path
*/
const hintKey = hintEntries.find((entry) => {
return idParts.every((idPart) => {
return entry.includes(idPart);
});
});
return config.hints[hintKey || ''];
};
resources.hints.forEach((Hint) => {
debug('Loading hints');
const id = Hint.meta.id;
const ignoreHint = (HintCtor: IHintConstructor): boolean => {
const ignoredConnectors: string[] = HintCtor.meta.ignoredConnectors || [];
return (connectorId === 'local' && HintCtor.meta.scope === HintScope.site) ||
(connectorId !== 'local' && HintCtor.meta.scope === HintScope.local) ||
ignoredConnectors.includes(connectorId || '');
};
const getIgnoredUrls = () => {
const urlsIgnoredForAll = this.ignoredUrls.get('all') || [];
const urlsIgnoredForHint = this.ignoredUrls.get(id) || [];
return urlsIgnoredForAll.concat(urlsIgnoredForHint);
};
const hintOptions: HintConfig | HintConfig[] = getHintConfig(id);
const severity: Severity | null = getSeverity(hintOptions);
if (ignoreHint(Hint)) {
debug(`Hint "${id}" is disabled for the connector "${connectorId}"`);
// TODO: I don't think we should have a dependency on logger here. Maybe send a warning event?
logger.log(chalk.yellow(`Warning: The hint "${id}" will be ignored for the connector "${connectorId}"`));
} else if (severity) {
const context: HintContext = new HintContext(id, this, severity, hintOptions, Hint.meta, getIgnoredUrls());
const hint: IHint = new Hint(context);
this.hints.set(id, hint);
} else {
debug(`Hint "${id}" is disabled`);
}
});
}
public onHintEvent<K extends StringKeyOf<E>>(id: string, eventName: K, listener: (data: E[K], event: string) => void) {
const that = this;
const createEventHandler = (handler: (data: E[K], event: string) => void, hintId: string) => {
/*
* Using fake `this` parameter for typing: https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters
* `this.event` defined by eventemitter2: https://github.com/EventEmitter2/EventEmitter2#differences-non-breaking-compatible-with-existing-eventemitter
*/
return function (this: { event: string }, event: E[K]): Promise<any> | null {
const urlsIgnoredForAll = that.ignoredUrls.get('all') || [];
const urlsIgnoredForHint = that.ignoredUrls.get(hintId) || [];
const urlsIgnored = urlsIgnoredForHint.concat(urlsIgnoredForAll);
const eventName = this.event; // eslint-disable-line no-invalid-this
if (that.isIgnored(urlsIgnored, (event as any).resource)) {
return null;
}
// If a hint is spending a lot of time to finish we should ignore it.
return new Promise((resolve) => {
let immediateId: any;
const timeoutId = setTimeout(() => {
if (immediateId) {
clearImmediate(immediateId);
immediateId = null;
}
debug(`Hint ${hintId} timeout`);
resolve(null);
}, that._timeout);
immediateId = setImmediate(async () => {
const result: any = await handler(event, eventName);
if (timeoutId) {
clearTimeout(timeoutId);
}
resolve(result);
});
});
};
};
this.on(eventName as any, createEventHandler(listener, id));
}
public fetchContent(target: string | url.URL, headers?: object): Promise<NetworkData> {
return this.connector.fetchContent(target, headers);
}
public evaluate(source: string) {
return this.connector.evaluate(source);
}
/** Releases any used resource and/or browser. */
public async close() {
await this.connector.close();
}
/** Reports a message from one of the hints. */
public report(hintId: string, category: Category, severity: Severity, sourceCode: string, location: ProblemLocation | null, message: string, resource: string, codeLanguage: string | undefined) {
const problem: Problem = {
category,
codeLanguage,
hintId,
location: location || { column: -1, line: -1 },
message,
resource,
severity,
sourceCode
};
this.messages.push(problem);
}
public clean(fileUrl: url.URL) {
const file = url.format(fileUrl);
remove(this.messages, (message) => {
return message.resource === file;
});
}
public clear() {
this.messages = [];
}
public async notify(this: Engine<Events>, resource: string) {
await this.emitAsync('print', {
problems: this.messages,
resource
});
}
/** Runs all the configured hints on a target */
public async executeOn(target: url.URL, options?: IFetchOptions): Promise<Problem[]> {
const start: number = Date.now();
debug(`Starting the analysis on ${target.href}`);
await this.connector.collect(target, options);
debug(`Total runtime ${Date.now() - start}`);
return this.messages;
}
public querySelectorAll(selector: string): HTMLElement[] {
return this.connector.querySelectorAll(selector);
}
public emit<K extends StringKeyOf<E>>(event: K, data: E[K]): boolean {
return super.emit(event, data);
}
public emitAsync<K extends StringKeyOf<E>>(event: K, data: E[K]): Promise<any[]> {
const ignoredUrls = this.ignoredUrls.get('all') || [];
if (this.isIgnored(ignoredUrls, (data as any).resource)) {
return Promise.resolve([]);
}
return super.emitAsync(event, data);
}
public on<K extends StringKeyOf<E>>(event: K, listener: (data: E[K]) => void): this {
return super.on(event, listener);
}
}