-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathlighthouse_runner.js
More file actions
366 lines (347 loc) · 10.6 KB
/
lighthouse_runner.js
File metadata and controls
366 lines (347 loc) · 10.6 KB
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
355
356
357
358
359
360
361
362
363
364
365
366
const Crawler = require('simplecrawler');
const lighthouse = require('lighthouse');
const generateReport = require('lighthouse/report/generator/report-generator');
const chromeLauncher = require('chrome-launcher');
const fs = require('fs');
const path = require('path');
const os = require('os');
const Spinner = require('cli-spinner').Spinner;
Spinner.setDefaultSpinnerDelay(100);
let autoOpen = false;
let port;
let outputMode;
let threads;
let formFactor;
let _spinner;
let progressBar;
const runnerConfig = require('./config/runnerConfiguration');
const allowedList = require('./allowedList').allowedList;
const {
_readReportDirectory,
_createWriteStreams,
_processCSVFiles,
parallelLimit,
createFileTime,
_parseProgramURLs,
_setupCrawlerConfig,
_populateCrawledURLList,
_determineResultingFilePath,
_writeReportResultFile,
_printNumberOfReports,
_waitForStreamsToClose,
openReports,
openReportsWithoutServer,
_closeWriteStreams,
_getNumberOfReports,
_setupProgressBarReportCreation,
_setupProgressBarAggregateCsv
} = require('./helpers');
const {
_opts,
_desktopOpts
} = require('./lighthouse_opts');
/**
* Launches a headless instance of chrome and runs Lighthouse on that instance.
*
* @param {*} url A URL that the headless instance will navigate to
* @param {*} opts Any options to pass into Chrome
* @param {*} [config=null] Any special options passed to Lighthouse
* @returns Lighthouse Result object (LHR)
*/
/* istanbul ignore next */
async function launchChromeAndRunLighthouseAsync(url, opts, config = null) {
try {
const chrome = await chromeLauncher.launch({
chromeFlags: opts.chromeFlags
});
opts.port = chrome.port;
const results = await lighthouse(url, opts, config);
await chrome.kill();
return results.lhr;
} catch (e) {
throw e;
}
};
/**
* Function to process the Lighthouse Result object(s)
*
* @param {[string]} urlList Lighthouse will run an audit for each URL in this list
* @param {[{}]} opts Any options to pass into Chrome
* @param {string} tempFilePath A path to store the resulting HTML files
*/
/* istanbul ignore next */
async function processReports(urlList, opts, tempFilePath) {
let desktopOpts = opts[0];
let mobileOpts = opts[1];
try {
for (let i = 0; i < urlList.length; i++) {
let currentUrl = urlList[i];
if (formFactor === 'mobile' || formFactor === 'all') {
await launchChromeAndRunLighthouseAsync(currentUrl, mobileOpts)
.then(results => {
let processObj = {
"currentUrl": currentUrl,
"results": results,
"tempFilePath": tempFilePath,
"opts": mobileOpts
};
processResults(processObj);
})
.catch((err) => {
console.error(err);
throw err;
});
}
if (formFactor === 'desktop' || formFactor === 'all') {
await launchChromeAndRunLighthouseAsync(currentUrl, desktopOpts)
.then(results => {
let processObj = {
"currentUrl": currentUrl,
"results": results,
"tempFilePath": tempFilePath,
"opts": desktopOpts
};
processResults(processObj);
})
.catch(err => {
console.error(err);
throw err;
});
}
}
} catch (e) {
console.error(e);
}
};
/* istanbul ignore next */
const processResults = (processObj) => {
let currentUrl = processObj.currentUrl;
let opts = processObj.opts;
let tempFilePath = processObj.tempFilePath;
let results = processObj.results;
let splitUrl = processObj.currentUrl.split('//');
let replacedUrl = splitUrl[1].replace(/\//g, "_");
let report = generateReport.generateReport(results, opts.output);
let filePath;
filePath = _determineResultingFilePath(opts, filePath, tempFilePath, replacedUrl);
// https://stackoverflow.com/questions/34811222/writefile-no-such-file-or-directory
_writeReportResultFile(filePath, report, opts, currentUrl, tempFilePath);
progressBar.increment();
};
/**
* Listener function for 'queueadd' event from simplecrawler.
*
* @param {{uriPath: string}} queueItem a URL that has been picked up by the crawler
*/
/* istanbul ignore next */
const queueAdd = (queueItem, urlList) => {
const [endOfURLPath] = queueItem.uriPath.split('/').slice(-1);
const [fileExtension] = endOfURLPath.split('.').slice(-1);
const isValidWebPage = allowedList.includes(fileExtension);
if (isValidWebPage) {
urlList.push(queueItem.url);
console.info(`Pushed: ${queueItem.url}`);
// if end of the path is /xyz/, this is still a valid path
} if (endOfURLPath.length === 0) {
urlList.push(queueItem.url);
console.info(`\n Pushed: ${queueItem.url}`);
}
else {
// if uri path is clean/no file path
if (!endOfURLPath.includes('.')) {
urlList.push(queueItem.url);
console.info(`\n Pushed: ${queueItem.url}`);
}
}
};
/* istanbul ignore next */
/**
*
*
* @param {String []} urlList List of valid urls from simplecrawler
* @param {boolean} autoOpen
*/
const complete = (urlList, autoOpen) => {
/*
? https://github.com/GoogleChrome/lighthouse/tree/master/lighthouse-core/config
? for more information on config options for lighthouse
*/
_spinner.stop(true);
let opts = _opts;
opts.output = outputMode;
let desktopOpts = _desktopOpts;
desktopOpts.output = outputMode;
const fileTime = createFileTime();
// tempFilePath is wherever we want to store the generated report
let tempFilePath = path.join(process.cwd(), "lighthouse", fileTime);
if (!fs.existsSync(tempFilePath)) {
fs.mkdirSync(tempFilePath, { recursive: true });
}
_printNumberOfReports(formFactor, urlList);
progressBar = _setupProgressBarReportCreation(formFactor, urlList);
/*
async start function
This prevents the CPU from getting bogged down when Lighthouse tries to run
a report on every URL in the URL list
*/
(async () => {
try {
let combinedOpts = [desktopOpts, opts];
const promises = await parallelLimit(
[
processReports(urlList, combinedOpts, tempFilePath)
],
threads);
await Promise.all(promises);
progressBar.stop();
console.log('Done creating reports!');
if (outputMode === 'csv') {
aggregateCSVReports(tempFilePath, formFactor);
}
} catch (e) {
throw (e);
}
if (autoOpen) {
openReports(port);
}
})();
};
/**
* Given a directory path to CSV reports, create two aggregate reports from the data.
* One aggregate report is for desktop data and the other report is for mobile data.
*
* @param {string} directoryPath
* @param {string} formFactor
* @returns {boolean} didAggregateSuccessfully
*/
const aggregateCSVReports = async (directoryPath, formFactor) => {
let didAggregateSuccessfully = true;
const parsedDirectoryPath = path.parse(directoryPath);
const timestamp = parsedDirectoryPath.base;
let files = _readReportDirectory(directoryPath);
if (!files) {
return false;
}
let [desktopWriteStream, mobileWriteStream] = _createWriteStreams(timestamp, directoryPath, formFactor);
let progressBar = _setupProgressBarAggregateCsv(desktopWriteStream, mobileWriteStream, files);
const aggregateName = "_aggregateReport";
files = files.filter(fileName => !fileName.includes(aggregateName));
let processCSVObject = {
files,
directoryPath,
desktopWriteStream,
mobileWriteStream,
progressBar
};
try {
_processCSVFiles(processCSVObject);
}
catch (e) {
console.error(e);
didAggregateSuccessfully = false;
} finally {
progressBar.stop();
_closeWriteStreams();
}
console.info("Waiting for streams to close!");
await _waitForStreamsToClose();
console.info("Streams closed!");
return didAggregateSuccessfully;
};
const _parseProgramParameters = (options) => {
outputMode = options.format;
port = options.port;
if (options.device === 'mobile' || options.device === 'desktop') {
formFactor = options.device;
} else {
formFactor = 'all';
}
if (options.threads === undefined) {
threads = os.cpus().length;
} else {
threads = options.threads;
}
if (options.express === undefined) {
autoOpen = runnerConfig.autoOpenReports;
} else {
autoOpen = options.express;
}
if(!options.verbose) {
console.info = function () {};
}
};
/**
* Sets up the 'queueadd' and 'complete' events for the crawler
*
* @param {string} domainRoot
* @param {Crawler} simpleCrawler
* @param {boolean} isDomainRootAnArray
* @param {string[]} urlList
* @returns
*/
const _setupCrawlerEvents = (domainRoot, simpleCrawler, isDomainRootAnArray, urlList) => {
if (isDomainRootAnArray) {
simpleCrawler = Crawler(domainRoot[0].href)
.on('queueadd', (queueItem) => {
queueAdd(queueItem, urlList)
})
.on('complete', () => {
complete(urlList, autoOpen);
});
} else {
simpleCrawler = Crawler(domainRoot.href)
.on('queueadd', (queueItem) => {
queueAdd(queueItem, urlList)
})
.on('complete', () => {
complete(urlList, autoOpen);
});
}
return simpleCrawler;
};
/**
* Determines if the chrome-launcher package can find an installed Chromium/Chrome executable.
*
*/
const determineIfChromeIsInstalled = () => {
try {
chromeLauncher.getChromePath();
}
catch (e) {
console.error("You need to install Chromium or Chrome in order to use auto-lighthouse.");
throw e;
}
}
/**
* Main function.
* This kicks off the Lighthouse Runner process
* @param {commander} program - An instance of a Commander.js program
*/
function main(program) {
determineIfChromeIsInstalled();
let domainRoot;
let simpleCrawler;
let programOptions = (program.opts === undefined) ? program : program.opts();
_parseProgramParameters(programOptions);
domainRoot = _parseProgramURLs(programOptions);
let isDomainRootAnArray = Array.isArray(domainRoot);
let urlList = [];
simpleCrawler = _setupCrawlerEvents(domainRoot, simpleCrawler, isDomainRootAnArray, urlList);
_setupCrawlerConfig(simpleCrawler, programOptions);
_populateCrawledURLList(isDomainRootAnArray, domainRoot, simpleCrawler, urlList);
if (autoOpen) {
console.log('Automatically opening reports when done!');
} else {
console.log('Not automatically opening reports when done!');
}
console.info('Starting simple crawler on', simpleCrawler.host + '!');
_spinner = new Spinner('Crawling domains... %s');
_spinner.start();
return simpleCrawler.start();
}
module.exports = {
main,
openReports,
openReportsWithoutServer,
aggregateCSVReports
};