-
Notifications
You must be signed in to change notification settings - Fork 9.4k
/
run.js
278 lines (243 loc) · 10.1 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
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
/**
* @license Copyright 2017 The Lighthouse Authors. 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 */
import path from 'path';
import psList from 'ps-list';
import * as ChromeLauncher from 'chrome-launcher';
import yargsParser from 'yargs-parser';
import log from 'lighthouse-logger';
import open from 'open';
import * as Printer from './printer.js';
import lighthouse from '../lighthouse-core/index.js';
import {getLhrFilenamePrefix} from '../report/generator/file-namer.js';
import * as assetSaver from '../lighthouse-core/lib/asset-saver.js';
import URL from '../lighthouse-core/lib/url-shim.js';
/** @typedef {Error & {code: string, friendlyMessage?: string}} ExitError */
const _RUNTIME_ERROR_CODE = 1;
const _PROTOCOL_TIMEOUT_EXIT_CODE = 67;
/**
* exported for testing
* @param {string|Array<string>} flags
* @return {Array<string>}
*/
function parseChromeFlags(flags = '') {
// flags will be a string if there is only one chrome-flag parameter:
// i.e. `lighthouse --chrome-flags="--user-agent='My Agent' --headless"`
// flags will be an array if there are multiple chrome-flags parameters
// i.e. `lighthouse --chrome-flags="--user-agent='My Agent'" --chrome-flags="--headless"`
const trimmedFlags = (Array.isArray(flags) ? flags : [flags])
// `child_process.execFile` and other programmatic invocations will pass Lighthouse arguments atomically.
// Many developers aren't aware of this and attempt to pass arguments to LH as they would to a shell `--chromeFlags="--headless --no-sandbox"`.
// In this case, yargs will see `"--headless --no-sandbox"` and treat it as a single argument instead of the intended `--headless --no-sandbox`.
// We remove quotes that surround the entire expression to make this work.
// i.e. `child_process.execFile("lighthouse", ["http://google.com", "--chrome-flags='--headless --no-sandbox'")`
// the following regular expression removes those wrapping quotes:
.map((flagsGroup) => flagsGroup.replace(/^\s*('|")(.+)\1\s*$/, '$2').trim())
.join(' ').trim();
const parsed = yargsParser(trimmedFlags, {
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,
ignoreDefaultFlags: flags.chromeIgnoreDefaultFlags,
chromeFlags: parseChromeFlags(flags.chromeFlags),
logLevel: flags.logLevel,
});
}
/** @return {never} */
function printConnectionErrorAndExit() {
console.error('Unable to connect to Chrome');
return process.exit(_RUNTIME_ERROR_CODE);
}
/** @return {never} */
function printProtocolTimeoutErrorAndExit() {
console.error('Debugger protocol timed out while connecting to Chrome.');
return process.exit(_PROTOCOL_TIMEOUT_EXIT_CODE);
}
/**
* @param {ExitError} err
* @return {never}
*/
function printRuntimeErrorAndExit(err) {
console.error('Runtime error encountered:', err.friendlyMessage || err.message);
if (err.stack) {
console.error(err.stack);
}
return process.exit(_RUNTIME_ERROR_CODE);
}
/**
* @param {ExitError} err
* @return {never}
*/
function printErrorAndExit(err) {
if (err.code === 'ECONNREFUSED') {
return printConnectionErrorAndExit();
} else if (err.code === 'CRI_TIMEOUT') {
return printProtocolTimeoutErrorAndExit();
} else {
return printRuntimeErrorAndExit(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' ?
getLhrFilenamePrefix(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) {
open(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;
/** @type {NodeJS.Timeout} */
let timeout;
const timeoutPromise = new Promise((_, reject) => {
timeout = setTimeout(() => reject(new Error('Timed out waiting to kill Chrome')), 5000);
});
return Promise.race([
launchedChrome.kill(),
timeoutPromise,
]).catch(async err => {
const runningProcesses = await psList();
if (!runningProcesses.some(proc => proc.pid === launchedChrome.pid)) {
log.warn('CLI', 'Warning: Chrome process could not be killed because it already exited.');
return;
}
throw new Error(`Couldn't quit Chrome process. ${err}`);
}).finally(() => {
clearTimeout(timeout);
});
}
/**
* @param {string} url
* @param {LH.CliFlags} flags
* @param {LH.Config.Json|undefined} config
* @param {ChromeLauncher.LaunchedChrome} launchedChrome
* @return {Promise<LH.RunnerResult|undefined>}
*/
async function runLighthouseWithFraggleRock(url, flags, config, launchedChrome) {
const fraggleRock = (await import('../lighthouse-core/fraggle-rock/api.js')).default;
const puppeteer = (await import('puppeteer')).default;
const browser = await puppeteer.connect({browserURL: `http://localhost:${launchedChrome.port}`});
const page = await browser.newPage();
flags.channel = 'fraggle-rock-cli';
const configContext = {configPath: flags.configPath, settingsOverrides: flags};
return fraggleRock.navigation({url, page, config, configContext});
}
/**
* @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;
const shouldUseLocalChrome = URL.isLikeLocalhost(flags.hostname);
if (shouldGather && shouldUseLocalChrome) {
launchedChrome = await getDebuggableChrome(flags);
flags.port = launchedChrome.port;
}
const runnerResult = flags.fraggleRock && launchedChrome ?
await runLighthouseWithFraggleRock(url, flags, config, launchedChrome) :
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);
// Runtime errors indicate something was *very* wrong with the page result.
// We don't want the user to have to parse the report to figure it out, so we'll still exit
// with an error code after we saved the results.
if (runnerResult && runnerResult.lhr.runtimeError) {
const {runtimeError} = runnerResult.lhr;
return printErrorAndExit({
name: 'LHError',
friendlyMessage: runtimeError.message,
code: runtimeError.code,
message: runtimeError.message,
});
}
return runnerResult;
} catch (err) {
await potentiallyKillChrome(launchedChrome).catch(() => {});
return printErrorAndExit(err);
}
}
export {
parseChromeFlags,
saveResults,
runLighthouse,
};