-
Notifications
You must be signed in to change notification settings - Fork 9.3k
/
run.js
230 lines (198 loc) · 7.44 KB
/
run.js
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
/**
* @license Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
'use strict';
/* eslint-disable no-console */
const path = require('path');
const Printer = require('./printer.js');
const ChromeLauncher = require('chrome-launcher');
const yargsParser = require('yargs-parser');
const lighthouse = require('../lighthouse-core/index.js');
const log = require('lighthouse-logger');
const getFilenamePrefix = require('../lighthouse-core/lib/file-namer.js').getFilenamePrefix;
const assetSaver = require('../lighthouse-core/lib/asset-saver.js');
const opn = require('opn');
const _RUNTIME_ERROR_CODE = 1;
const _PROTOCOL_TIMEOUT_EXIT_CODE = 67;
const _PAGE_HUNG_EXIT_CODE = 68;
const _INSECURE_DOCUMENT_REQUEST_EXIT_CODE = 69;
/**
* exported for testing
* @param {string} flags
* @return {Array<string>}
*/
function parseChromeFlags(flags = '') {
const parsed = yargsParser(
flags.trim(), {configuration: {'camel-case-expansion': false, 'boolean-negation': false}});
return Object
.keys(parsed)
// Remove unnecessary _ item provided by yargs,
.filter(key => key !== '_')
// Avoid '=true', then reintroduce quotes
.map(key => {
if (parsed[key] === true) return `--${key}`;
// ChromeLauncher passes flags to Chrome as atomic arguments, so do not double quote
// i.e. `lighthouse --chrome-flags="--user-agent='My Agent'"` becomes `chrome "--user-agent=My Agent"`
// see https://github.com/GoogleChrome/lighthouse/issues/3744
return `--${key}=${parsed[key]}`;
});
}
/**
* Attempts to connect to an instance of Chrome with an open remote-debugging
* port. If none is found, launches a debuggable instance.
* @param {LH.CliFlags} flags
* @return {Promise<ChromeLauncher.LaunchedChrome>}
*/
function getDebuggableChrome(flags) {
return ChromeLauncher.launch({
port: flags.port,
chromeFlags: parseChromeFlags(flags.chromeFlags),
logLevel: flags.logLevel,
});
}
/** @return {never} */
function showConnectionError() {
console.error('Unable to connect to Chrome');
return process.exit(_RUNTIME_ERROR_CODE);
}
/** @return {never} */
function showProtocolTimeoutError() {
console.error('Debugger protocol timed out while connecting to Chrome.');
return process.exit(_PROTOCOL_TIMEOUT_EXIT_CODE);
}
/** @param {LH.LighthouseError} err @return {never} */
function showPageHungError(err) {
console.error('Page hung:', err.friendlyMessage);
return process.exit(_PAGE_HUNG_EXIT_CODE);
}
/** @param {LH.LighthouseError} err @return {never} */
function showInsecureDocumentRequestError(err) {
console.error('Insecure document request:', err.friendlyMessage);
return process.exit(_INSECURE_DOCUMENT_REQUEST_EXIT_CODE);
}
/**
* @param {LH.LighthouseError} err
* @return {never}
*/
function showRuntimeError(err) {
console.error('Runtime error encountered:', err.friendlyMessage || err.message);
if (err.stack) {
console.error(err.stack);
}
return process.exit(_RUNTIME_ERROR_CODE);
}
/**
* @param {LH.LighthouseError} err
* @return {never}
*/
function handleError(err) {
if (err.code === 'ECONNREFUSED') {
return showConnectionError();
} else if (err.code === 'CRI_TIMEOUT') {
return showProtocolTimeoutError();
} else if (err.code === 'PAGE_HUNG') {
return showPageHungError(err);
} else if (err.code === 'INSECURE_DOCUMENT_REQUEST') {
return showInsecureDocumentRequestError(err);
} else {
return showRuntimeError(err);
}
}
/**
* @param {LH.RunnerResult} runnerResult
* @param {LH.CliFlags} flags
* @return {Promise<void>}
*/
async function saveResults(runnerResult, flags) {
const cwd = process.cwd();
if (flags.lanternDataOutputPath) {
const devtoolsLog = runnerResult.artifacts.devtoolsLogs.defaultPass;
await assetSaver.saveLanternNetworkData(devtoolsLog, flags.lanternDataOutputPath);
}
const shouldSaveResults = flags.auditMode || (flags.gatherMode === flags.auditMode);
if (!shouldSaveResults) return;
const {lhr, artifacts, report} = runnerResult;
// Use the output path as the prefix for all generated files.
// If no output path is set, generate a file prefix using the URL and date.
const configuredPath = !flags.outputPath || flags.outputPath === 'stdout' ?
getFilenamePrefix(lhr) :
flags.outputPath.replace(/\.\w{2,4}$/, '');
const resolvedPath = path.resolve(cwd, configuredPath);
if (flags.saveAssets) {
await assetSaver.saveAssets(artifacts, lhr.audits, resolvedPath);
}
for (const outputType of flags.output) {
const extension = outputType;
const output = report[flags.output.indexOf(outputType)];
let outputPath = `${resolvedPath}.report.${extension}`;
// If there was only a single output and the user specified an outputPath, force usage of it.
if (flags.outputPath && flags.output.length === 1) outputPath = flags.outputPath;
await Printer.write(output, outputType, outputPath);
if (outputType === Printer.OutputMode[Printer.OutputMode.html]) {
if (flags.view) {
opn(outputPath, {wait: false});
} else {
// eslint-disable-next-line max-len
log.log('CLI', 'Protip: Run lighthouse with `--view` to immediately open the HTML report in your browser');
}
}
}
}
/**
* Attempt to kill the launched Chrome, if defined.
* @param {ChromeLauncher.LaunchedChrome=} launchedChrome
* @return {Promise<void>}
*/
async function potentiallyKillChrome(launchedChrome) {
if (!launchedChrome) return;
return Promise.race([
launchedChrome.kill(),
new Promise((_, reject) => setTimeout(reject, 5000, 'Timed out.')),
]).catch(err => {
throw new Error(`Couldn't quit Chrome process. ${err}`);
});
}
/**
* @param {string} url
* @param {LH.CliFlags} flags
* @param {LH.Config.Json|undefined} config
* @return {Promise<LH.RunnerResult|undefined>}
*/
async function runLighthouse(url, flags, config) {
/** @param {any} reason */
async function handleTheUnhandled(reason) {
process.stderr.write(`Unhandled Rejection. Reason: ${reason}\n`);
await potentiallyKillChrome(launchedChrome).catch(() => {});
setTimeout(_ => {
process.exit(1);
}, 100);
}
process.on('unhandledRejection', handleTheUnhandled);
/** @type {ChromeLauncher.LaunchedChrome|undefined} */
let launchedChrome;
try {
const shouldGather = flags.gatherMode || flags.gatherMode === flags.auditMode;
if (shouldGather) {
launchedChrome = await getDebuggableChrome(flags);
flags.port = launchedChrome.port;
}
const runnerResult = await lighthouse(url, flags, config);
// If in gatherMode only, there will be no runnerResult.
if (runnerResult) {
await saveResults(runnerResult, flags);
}
await potentiallyKillChrome(launchedChrome);
process.removeListener('unhandledRejection', handleTheUnhandled);
return runnerResult;
} catch (err) {
await potentiallyKillChrome(launchedChrome).catch(() => {});
handleError(err);
}
}
module.exports = {
parseChromeFlags,
saveResults,
runLighthouse,
};