lighthouse 9.2.0-dev.20220104 → 9.2.0-dev.20220108

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -232,6 +232,10 @@ async function runLighthouse(url, flags, config) {
232
232
  let launchedChrome;
233
233
 
234
234
  try {
235
+ if (url && flags.auditMode && !flags.gatherMode) {
236
+ log.warn('CLI', 'URL parameter is ignored if -A flag is used without -G flag');
237
+ }
238
+
235
239
  const shouldGather = flags.gatherMode || flags.gatherMode === flags.auditMode;
236
240
  const shouldUseLocalChrome = URL.isLikeLocalhost(flags.hostname);
237
241
  if (shouldGather && shouldUseLocalChrome) {
@@ -36,6 +36,7 @@ const coreTestDefnsPath =
36
36
  const runnerPaths = {
37
37
  cli: '../lighthouse-runners/cli.js',
38
38
  bundle: '../lighthouse-runners/bundle.js',
39
+ devtools: '../lighthouse-runners/devtools.js',
39
40
  };
40
41
 
41
42
  /**
@@ -151,7 +152,7 @@ async function begin() {
151
152
  },
152
153
  'runner': {
153
154
  default: 'cli',
154
- choices: ['cli', 'bundle'],
155
+ choices: ['cli', 'bundle', 'devtools'],
155
156
  describe: 'The method of running Lighthouse',
156
157
  },
157
158
  'tests-path': {
@@ -0,0 +1,103 @@
1
+ /**
2
+ * @license Copyright 2021 The Lighthouse Authors. All Rights Reserved.
3
+ * 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
4
+ * 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.
5
+ */
6
+ 'use strict';
7
+
8
+ /**
9
+ * @fileoverview A runner that launches Chrome and executes Lighthouse via DevTools.
10
+ */
11
+
12
+ import fs from 'fs';
13
+ import os from 'os';
14
+ import {spawn} from 'child_process';
15
+
16
+ import {LH_ROOT} from '../../../../root.js';
17
+
18
+ const devtoolsDir =
19
+ process.env.DEVTOOLS_PATH || `${LH_ROOT}/.tmp/chromium-web-tests/devtools/devtools-frontend`;
20
+
21
+ /**
22
+ * @param {string} command
23
+ * @param {string[]} args
24
+ */
25
+ async function spawnAndLog(command, args) {
26
+ let log = '';
27
+
28
+ /** @type {Promise<void>} */
29
+ const promise = new Promise((resolve, reject) => {
30
+ const spawnHandle = spawn(command, args);
31
+ spawnHandle.on('close', code => {
32
+ if (code === 0) resolve();
33
+ else reject(new Error(`Command exited with code ${code}`));
34
+ });
35
+ spawnHandle.on('error', reject);
36
+ spawnHandle.stdout.on('data', data => {
37
+ console.log(data.toString());
38
+ log += `STDOUT: ${data.toString()}`;
39
+ });
40
+ spawnHandle.stderr.on('data', data => {
41
+ console.log(data.toString());
42
+ log += `STDERR: ${data.toString()}`;
43
+ });
44
+ });
45
+ await promise;
46
+
47
+ return log;
48
+ }
49
+
50
+ /** @type {Promise<void>} */
51
+ let buildDevtoolsPromise;
52
+ /**
53
+ * Download/pull latest DevTools, build Lighthouse for DevTools, roll to DevTools, and build DevTools.
54
+ */
55
+ async function buildDevtools() {
56
+ if (process.env.CI) return;
57
+
58
+ process.env.DEVTOOLS_PATH = devtoolsDir;
59
+ await spawnAndLog('bash', ['lighthouse-core/test/chromium-web-tests/download-devtools.sh']);
60
+ await spawnAndLog('bash', ['lighthouse-core/test/chromium-web-tests/roll-devtools.sh']);
61
+ }
62
+
63
+ /**
64
+ * Launch Chrome and do a full Lighthouse run via DevTools.
65
+ * By default, the latest DevTools frontend is used (.tmp/chromium-web-tests/devtools/devtools-frontend)
66
+ * unless DEVTOOLS_PATH is set.
67
+ * CHROME_PATH determines which Chrome is used–otherwise the default is puppeteer's chrome binary.
68
+ * @param {string} url
69
+ * @param {LH.Config.Json=} configJson
70
+ * @param {{isDebug?: boolean}=} testRunnerOptions
71
+ * @return {Promise<{lhr: LH.Result, artifacts: LH.Artifacts, log: string}>}
72
+ */
73
+ async function runLighthouse(url, configJson, testRunnerOptions = {}) {
74
+ if (!buildDevtoolsPromise) buildDevtoolsPromise = buildDevtools();
75
+ await buildDevtoolsPromise;
76
+
77
+ const outputDir = fs.mkdtempSync(os.tmpdir() + '/lh-smoke-cdt-runner-');
78
+ const args = [
79
+ 'run-devtools',
80
+ url,
81
+ `--custom-devtools-frontend=file://${devtoolsDir}/out/Default/gen/front_end`,
82
+ '--output-dir', outputDir,
83
+ ];
84
+ if (configJson) {
85
+ args.push('--config', JSON.stringify(configJson));
86
+ }
87
+
88
+ const log = await spawnAndLog('yarn', args);
89
+ const lhr = JSON.parse(fs.readFileSync(`${outputDir}/lhr-0.json`, 'utf-8'));
90
+ const artifacts = JSON.parse(fs.readFileSync(`${outputDir}/artifacts-0.json`, 'utf-8'));
91
+
92
+ if (testRunnerOptions.isDebug) {
93
+ console.log(`${url} results saved at ${outputDir}`);
94
+ } else {
95
+ fs.rmSync(outputDir, {recursive: true, force: true});
96
+ }
97
+
98
+ return {lhr, artifacts, log};
99
+ }
100
+
101
+ export {
102
+ runLighthouse,
103
+ };
@@ -118,14 +118,15 @@ Smokehouse Frontends Lighthouse Runners
118
118
  | | | | | <lhr | +--------------+
119
119
  +------------+ | +-------+-------+ | | |
120
120
  | ^ +-->+ bundle.js |
121
- +------------+ | | | |
122
- | | | | +--------------+
123
- | lib.js +----+ v
124
- | | +--------+--------+
125
- +------------+ | |
126
- | report/assert |
127
- | |
128
- +-----------------+
121
+ +------------+ | | | | |
122
+ | | | | | +--------------+
123
+ | lib.js +----+ v |
124
+ | | +--------+--------+ |
125
+ +------------+ | | | +--------------+
126
+ | report/assert | | | |
127
+ | | +-->+ devtools.js |
128
+ +-----------------+ | |
129
+ +--------------+
129
130
  ```
130
131
 
131
132
  ### Smokehouse frontends
@@ -142,6 +143,7 @@ Smokehouse Frontends Lighthouse Runners
142
143
 
143
144
  - `lighthouse-runners/cli.js` - the original test runner, exercising the Lighthouse CLI from command-line argument parsing to the results written to disk on completion.
144
145
  - `lighthouse-runners/bundle.js` - a smoke test runner that operates on an already-bundled version of Lighthouse for end-to-end testing of that version.
146
+ - `lighthouse-runners/devtools.js` - a smoke test runner that operates on Lighthouse running from inside DevTools.
145
147
 
146
148
  ## Custom smoke tests (for plugins et al.)
147
149
 
@@ -22,6 +22,7 @@ const {initializeConfig} = require('../config/config.js');
22
22
  const {getBaseArtifacts, finalizeArtifacts} = require('./base-artifacts.js');
23
23
  const format = require('../../../shared/localization/format.js');
24
24
  const LighthouseError = require('../../lib/lh-error.js');
25
+ const URL = require('../../lib/url-shim.js');
25
26
  const {getPageLoadError} = require('../../lib/navigation-error.js');
26
27
  const Trace = require('../../gather/gatherers/trace.js');
27
28
  const DevtoolsLog = require('../../gather/gatherers/devtools-log.js');
@@ -279,7 +280,7 @@ async function _cleanup({requestedUrl, driver, config}) {
279
280
  * @return {Promise<LH.RunnerResult|undefined>}
280
281
  */
281
282
  async function navigation(options) {
282
- const {url: requestedUrl, page, configContext = {}} = options;
283
+ const {url, page, configContext = {}} = options;
283
284
  const {config} = initializeConfig(options.config, {...configContext, gatherMode: 'navigation'});
284
285
  const computedCache = new Map();
285
286
  const internalOptions = {
@@ -289,6 +290,7 @@ async function navigation(options) {
289
290
  return Runner.run(
290
291
  async () => {
291
292
  const driver = new Driver(page);
293
+ const requestedUrl = URL.normalizeUrl(url);
292
294
  const context = {driver, config, requestedUrl, options: internalOptions};
293
295
  const {baseArtifacts} = await _setup(context);
294
296
  const {artifacts} = await _navigations({...context, baseArtifacts, computedCache});
@@ -297,7 +299,6 @@ async function navigation(options) {
297
299
  return finalizeArtifacts(baseArtifacts, artifacts);
298
300
  },
299
301
  {
300
- url: requestedUrl,
301
302
  config,
302
303
  computedCache: new Map(),
303
304
  }
@@ -51,7 +51,6 @@ async function snapshot(options) {
51
51
  return finalizeArtifacts(baseArtifacts, artifacts);
52
52
  },
53
53
  {
54
- url,
55
54
  config,
56
55
  computedCache,
57
56
  }
@@ -64,7 +64,6 @@ async function startTimespan(options) {
64
64
  return finalizeArtifacts(baseArtifacts, artifacts);
65
65
  },
66
66
  {
67
- url: finalUrl,
68
67
  config,
69
68
  computedCache,
70
69
  }
@@ -9,6 +9,7 @@ const Runner = require('./runner.js');
9
9
  const log = require('lighthouse-logger');
10
10
  const ChromeProtocol = require('./gather/connections/cri.js');
11
11
  const Config = require('./config/config.js');
12
+ const URL = require('./lib/url-shim.js');
12
13
 
13
14
  /** @typedef {import('./gather/connections/connection.js')} Connection */
14
15
 
@@ -42,12 +43,12 @@ async function lighthouse(url, flags = {}, configJSON, userConnection) {
42
43
 
43
44
  const config = generateConfig(configJSON, flags);
44
45
  const computedCache = new Map();
45
- const options = {url, config, computedCache};
46
+ const options = {config, computedCache};
46
47
  const connection = userConnection || new ChromeProtocol(flags.port, flags.hostname);
47
48
 
48
49
  // kick off a lighthouse run
49
- /** @param {{requestedUrl: string}} runnerData */
50
- const gatherFn = ({requestedUrl}) => {
50
+ const gatherFn = () => {
51
+ const requestedUrl = URL.normalizeUrl(url);
51
52
  return Runner._gatherArtifactsFromBrowser(requestedUrl, options, connection);
52
53
  };
53
54
  return Runner.run(gatherFn, options);
@@ -10,6 +10,7 @@
10
10
  */
11
11
 
12
12
  const {Util} = require('../util-commonjs.js');
13
+ const LHError = require('../lib/lh-error.js');
13
14
 
14
15
  /** @typedef {import('./network-request.js')} NetworkRequest */
15
16
 
@@ -248,6 +249,20 @@ class URLShim extends URL {
248
249
  if (ext === 'jpg') return 'image/jpeg';
249
250
  return `image/${ext}`;
250
251
  }
252
+
253
+ /**
254
+ * @param {string|undefined} url
255
+ * @return {string}
256
+ */
257
+ static normalizeUrl(url) {
258
+ // Verify the url is valid and that protocol is allowed
259
+ if (url && this.isValid(url) && this.isProtocolAllowed(url)) {
260
+ // Use canonicalized URL (with trailing slashes and such)
261
+ return new URL(url).href;
262
+ } else {
263
+ throw new LHError(LHError.errors.INVALID_URL);
264
+ }
265
+ }
251
266
  }
252
267
 
253
268
  URLShim.URL = URL;
@@ -16,7 +16,6 @@ const stackPacks = require('./lib/stack-packs.js');
16
16
  const assetSaver = require('./lib/asset-saver.js');
17
17
  const fs = require('fs');
18
18
  const path = require('path');
19
- const URL = require('./lib/url-shim.js');
20
19
  const Sentry = require('./lib/sentry.js');
21
20
  const generateReport = require('../report/generator/report-generator.js').generateReport;
22
21
  const LHError = require('./lib/lh-error.js');
@@ -29,8 +28,8 @@ const {version: lighthouseVersion} = require('../package.json');
29
28
  class Runner {
30
29
  /**
31
30
  * @template {LH.Config.Config | LH.Config.FRConfig} TConfig
32
- * @param {(runnerData: {requestedUrl: string, config: TConfig, driverMock?: Driver}) => Promise<LH.Artifacts>} gatherFn
33
- * @param {{config: TConfig, computedCache: Map<string, ArbitraryEqualityMap>, url?: string, driverMock?: Driver}} runOpts
31
+ * @param {(runnerData: {config: TConfig, driverMock?: Driver}) => Promise<LH.Artifacts>} gatherFn
32
+ * @param {{config: TConfig, computedCache: Map<string, ArbitraryEqualityMap>, driverMock?: Driver}} runOpts
34
33
  * @return {Promise<LH.RunnerResult|undefined>}
35
34
  */
36
35
  static async run(gatherFn, runOpts) {
@@ -52,47 +51,7 @@ class Runner {
52
51
  data: sentryContext?.extra,
53
52
  });
54
53
 
55
- // User can run -G solo, -A solo, or -GA together
56
- // -G and -A will run partial lighthouse pipelines,
57
- // and -GA will run everything plus save artifacts and lhr to disk.
58
-
59
- // Gather phase
60
- // Either load saved artifacts off disk or from the browser
61
- let artifacts;
62
- let requestedUrl;
63
- if (settings.auditMode && !settings.gatherMode) {
64
- // No browser required, just load the artifacts from disk.
65
- const path = Runner._getDataSavePath(settings);
66
- artifacts = assetSaver.loadArtifacts(path);
67
- requestedUrl = artifacts.URL.requestedUrl;
68
-
69
- if (!requestedUrl) {
70
- throw new Error('Cannot run audit mode on empty URL');
71
- }
72
- if (runOpts.url && !URL.equalWithExcludedFragments(runOpts.url, requestedUrl)) {
73
- throw new Error('Cannot run audit mode on different URL');
74
- }
75
- } else {
76
- // verify the url is valid and that protocol is allowed
77
- if (runOpts.url && URL.isValid(runOpts.url) && URL.isProtocolAllowed(runOpts.url)) {
78
- // Use canonicalized URL (with trailing slashes and such)
79
- requestedUrl = new URL(runOpts.url).href;
80
- } else {
81
- throw new LHError(LHError.errors.INVALID_URL);
82
- }
83
-
84
- artifacts = await gatherFn({
85
- requestedUrl,
86
- config: runOpts.config,
87
- driverMock: runOpts.driverMock,
88
- });
89
-
90
- // -G means save these to ./latest-run, etc.
91
- if (settings.gatherMode) {
92
- const path = Runner._getDataSavePath(settings);
93
- await assetSaver.saveArtifacts(artifacts, path);
94
- }
95
- }
54
+ const artifacts = await this.gatherAndManageArtifacts(gatherFn, runOpts);
96
55
 
97
56
  // Potentially quit early
98
57
  if (settings.gatherMode && !settings.auditMode) return;
@@ -133,7 +92,7 @@ class Runner {
133
92
  /** @type {LH.RawIcu<LH.Result>} */
134
93
  const i18nLhr = {
135
94
  lighthouseVersion,
136
- requestedUrl,
95
+ requestedUrl: artifacts.URL.requestedUrl,
137
96
  finalUrl: artifacts.URL.finalUrl,
138
97
  fetchTime: artifacts.fetchTime,
139
98
  gatherMode: artifacts.GatherContext.gatherMode,
@@ -184,6 +143,47 @@ class Runner {
184
143
  }
185
144
  }
186
145
 
146
+ /**
147
+ * User can run -G solo, -A solo, or -GA together
148
+ * -G and -A will run partial lighthouse pipelines,
149
+ * and -GA will run everything plus save artifacts and lhr to disk.
150
+ *
151
+ * @template {LH.Config.Config | LH.Config.FRConfig} TConfig
152
+ * @param {(runnerData: {config: TConfig, driverMock?: Driver}) => Promise<LH.Artifacts>} gatherFn
153
+ * @param {{config: TConfig, driverMock?: Driver}} options
154
+ * @return {Promise<LH.Artifacts>}
155
+ */
156
+ static async gatherAndManageArtifacts(gatherFn, options) {
157
+ const settings = options.config.settings;
158
+
159
+ // Gather phase
160
+ // Either load saved artifacts from disk or from the browser.
161
+ let artifacts;
162
+ if (settings.auditMode && !settings.gatherMode) {
163
+ // No browser required, just load the artifacts from disk.
164
+ const path = this._getDataSavePath(settings);
165
+ artifacts = assetSaver.loadArtifacts(path);
166
+ const requestedUrl = artifacts.URL.requestedUrl;
167
+
168
+ if (!requestedUrl) {
169
+ throw new Error('Cannot run audit mode on empty URL');
170
+ }
171
+ } else {
172
+ artifacts = await gatherFn({
173
+ config: options.config,
174
+ driverMock: options.driverMock,
175
+ });
176
+
177
+ // -G means save these to disk (e.g. ./latest-run).
178
+ if (settings.gatherMode) {
179
+ const path = this._getDataSavePath(settings);
180
+ await assetSaver.saveArtifacts(artifacts, path);
181
+ }
182
+ }
183
+
184
+ return artifacts;
185
+ }
186
+
187
187
  /**
188
188
  * This handles both the auditMode case where gatherer entries need to be merged in and
189
189
  * the gather/audit case where timingEntriesFromRunner contains all entries from this run,
@@ -10,10 +10,23 @@
10
10
 
11
11
  set -euo pipefail
12
12
 
13
- if [ "$OSTYPE" == "msys" ]; then
13
+ unameOut="$(uname -s)"
14
+ case "${unameOut}" in
15
+ Linux*) machine=Linux;;
16
+ Darwin*) machine=Mac;;
17
+ MINGW*) machine=MinGw;;
18
+ *) machine="UNKNOWN:${unameOut}"
19
+ esac
20
+
21
+ if [ "$machine" == "MinGw" ]; then
14
22
  url="https://download-chromium.appspot.com/dl/Win?type=snapshots"
15
- else
23
+ elif [ "$machine" == "Linux" ]; then
16
24
  url="https://download-chromium.appspot.com/dl/Linux_x64?type=snapshots"
25
+ elif [ "$machine" == "Mac" ]; then
26
+ url="https://download-chromium.appspot.com/dl/Mac?type=snapshots"
27
+ else
28
+ echo "unsupported platform"
29
+ exit 1
17
30
  fi
18
31
 
19
32
  if [ -e "$CHROME_PATH" ]; then
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lighthouse",
3
- "version": "9.2.0-dev.20220104",
3
+ "version": "9.2.0-dev.20220108",
4
4
  "description": "Automated auditing, performance metrics, and best practices for the web.",
5
5
  "main": "./lighthouse-core/index.js",
6
6
  "bin": {
@@ -170,7 +170,7 @@
170
170
  "resolve": "^1.20.0",
171
171
  "rollup": "^2.52.7",
172
172
  "rollup-plugin-node-resolve": "^5.2.0",
173
- "rollup-plugin-polyfill-node": "^0.7.0",
173
+ "rollup-plugin-polyfill-node": "^0.8.0",
174
174
  "rollup-plugin-replace": "^2.2.0",
175
175
  "rollup-plugin-shim": "^1.0.0",
176
176
  "rollup-plugin-terser": "^7.0.2",