Skip to content

Commit 0f418a8

Browse files
authoredDec 14, 2020
deps: update yargs to latest (#11794)
1 parent a589db5 commit 0f418a8

File tree

11 files changed

+584
-430
lines changed

11 files changed

+584
-430
lines changed
 

‎lighthouse-cli/bin.js

-15
Original file line numberDiff line numberDiff line change
@@ -102,21 +102,6 @@ async function begin() {
102102
' Please use "--emulated-form-factor=none" instead.');
103103
}
104104

105-
if (typeof cliFlags.extraHeaders === 'string') {
106-
// TODO: LH.Flags.extraHeaders is sometimes actually a string at this point, but needs to be
107-
// copied over to LH.Settings.extraHeaders, which is LH.Crdp.Network.Headers. Force
108-
// the conversion here, but long term either the CLI flag or the setting should have
109-
// a different name.
110-
/** @type {string} */
111-
let extraHeadersStr = cliFlags.extraHeaders;
112-
// If not a JSON object, assume it's a path to a JSON file.
113-
if (extraHeadersStr.substr(0, 1) !== '{') {
114-
extraHeadersStr = fs.readFileSync(extraHeadersStr, 'utf-8');
115-
}
116-
117-
cliFlags.extraHeaders = JSON.parse(extraHeadersStr);
118-
}
119-
120105
if (cliFlags.precomputedLanternDataPath) {
121106
const lanternDataStr = fs.readFileSync(cliFlags.precomputedLanternDataPath, 'utf8');
122107
/** @type {LH.PrecomputedLanternData} */

‎lighthouse-cli/cli-flags.js

+327-131
Large diffs are not rendered by default.

‎lighthouse-cli/test/cli/bin-test.js

-19
Original file line numberDiff line numberDiff line change
@@ -145,25 +145,6 @@ describe('CLI bin', function() {
145145
});
146146
});
147147

148-
describe('extraHeaders', () => {
149-
it('should convert extra headers to object', async () => {
150-
// @ts-expect-error - see TODO: in bin.js
151-
cliFlags = {...cliFlags, extraHeaders: '{"foo": "bar"}'};
152-
await bin.begin();
153-
154-
expect(getRunLighthouseArgs()[1]).toHaveProperty('extraHeaders', {foo: 'bar'});
155-
});
156-
157-
it('should read extra headers from file', async () => {
158-
const headersFile = require.resolve('../fixtures/extra-headers/valid.json');
159-
// @ts-expect-error - see TODO: in bin.js
160-
cliFlags = {...cliFlags, extraHeaders: headersFile};
161-
await bin.begin();
162-
163-
expect(getRunLighthouseArgs()[1]).toHaveProperty('extraHeaders', require(headersFile));
164-
});
165-
});
166-
167148
describe('precomputedLanternData', () => {
168149
it('should read lantern data from file', async () => {
169150
const lanternDataFile = require.resolve('../fixtures/lantern-data.json');

‎lighthouse-cli/test/cli/cli-flags-test.js

+21
Original file line numberDiff line numberDiff line change
@@ -73,4 +73,25 @@ describe('CLI bin', function() {
7373
]);
7474
expect(flags.blockedUrlPatterns).toEqual(['.*x,y\\.png']);
7575
});
76+
77+
describe('extraHeaders', () => {
78+
it('should convert extra headers to object', async () => {
79+
const flags = getFlags([
80+
'http://www.example.com',
81+
'--extra-headers="{"foo": "bar"}"',
82+
].join(' '));
83+
84+
expect(flags).toHaveProperty('extraHeaders', {foo: 'bar'});
85+
});
86+
87+
it('should read extra headers from file', async () => {
88+
const headersFile = require.resolve('../fixtures/extra-headers/valid.json');
89+
const flags = getFlags([
90+
'http://www.example.com',
91+
`--extra-headers=${headersFile}`,
92+
].join(' '));
93+
94+
expect(flags).toHaveProperty('extraHeaders', require(headersFile));
95+
});
96+
});
7697
});

‎lighthouse-cli/test/smokehouse/frontends/smokehouse-bin.js

+39-16
Original file line numberDiff line numberDiff line change
@@ -69,31 +69,54 @@ function getDefinitionsToRun(allTestDefns, requestedIds, {invertMatch}) {
6969
* CLI entry point.
7070
*/
7171
async function begin() {
72-
const argv = yargs
72+
const rawArgv = yargs
7373
.help('help')
7474
.usage('node $0 [<options>] <test-ids>')
7575
.example('node $0 -j=1 pwa seo', 'run pwa and seo tests serially')
7676
.example('node $0 --invert-match byte', 'run all smoke tests but `byte`')
77-
.describe({
78-
'debug': 'Save test artifacts and output verbose logs',
79-
'jobs': 'Manually set the number of jobs to run at once. `1` runs all tests serially',
80-
'retries': 'The number of times to retry failing tests before accepting. Defaults to 0',
81-
'runner': 'The method of running Lighthouse',
82-
'tests-path': 'The path to a set of test definitions to run. Defaults to core smoke tests.',
83-
'invert-match': 'Run all available tests except the ones provided',
77+
.option('_', {
78+
array: true,
79+
type: 'string',
8480
})
85-
.boolean(['debug', 'invert-match'])
86-
.alias({
87-
'jobs': 'j',
81+
.options({
82+
'debug': {
83+
type: 'boolean',
84+
default: false,
85+
describe: 'Save test artifacts and output verbose logs',
86+
},
87+
'jobs': {
88+
type: 'number',
89+
alias: 'j',
90+
describe: 'Manually set the number of jobs to run at once. `1` runs all tests serially',
91+
},
92+
'retries': {
93+
type: 'number',
94+
describe: 'The number of times to retry failing tests before accepting. Defaults to 0',
95+
},
96+
'runner': {
97+
default: 'cli',
98+
choices: ['cli', 'bundle'],
99+
describe: 'The method of running Lighthouse',
100+
},
101+
'tests-path': {
102+
type: 'string',
103+
describe: 'The path to a set of test definitions to run. Defaults to core smoke tests.',
104+
},
105+
'invert-match': {
106+
type: 'boolean',
107+
default: false,
108+
describe: 'Run all available tests except the ones provided',
109+
},
88110
})
89-
.choices('runner', ['cli', 'bundle'])
90-
.default('runner', 'cli')
91111
.wrap(yargs.terminalWidth())
92112
.argv;
93113

94-
// TODO: use .number() when yargs is updated
95-
const jobs = argv.jobs !== undefined ? Number(argv.jobs) : undefined;
96-
const retries = argv.retries !== undefined ? Number(argv.retries) : undefined;
114+
// Augmenting yargs type with auto-camelCasing breaks in tsc@4.1.2 and @types/yargs@15.0.11,
115+
// so for now cast to add yarg's camelCase properties to type.
116+
const argv = /** @type {typeof rawArgv & CamelCasify<typeof rawArgv>} */ (rawArgv);
117+
118+
const jobs = Number.isFinite(argv.jobs) ? argv.jobs : undefined;
119+
const retries = Number.isFinite(argv.retries) ? argv.retries : undefined;
97120

98121
const runnerPath = runnerPaths[/** @type {keyof typeof runnerPaths} */ (argv.runner)];
99122
if (argv.runner === 'bundle') {

‎lighthouse-core/scripts/compare-runs.js

+20-5
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ const {ProgressLogger} = require('./lantern/collect/common.js');
2727
const LH_ROOT = `${__dirname}/../..`;
2828
const ROOT_OUTPUT_DIR = `${LH_ROOT}/timings-data`;
2929

30-
const argv = yargs
30+
const rawArgv = yargs
3131
.help('help')
3232
.describe({
3333
// common flags
@@ -51,12 +51,14 @@ const argv = yargs
5151
'delta-property-sort': 'Property to sort by its delta',
5252
'desc': 'Set to override default ascending sort',
5353
})
54+
.option('n', {type: 'number', default: 1})
5455
.string('filter')
56+
.string('url-filter')
5557
.alias({'gather': 'G', 'audit': 'A'})
5658
.default('report-exclude', 'key|min|max|stdev|^n$')
5759
.default('delta-property-sort', 'mean')
5860
.default('output', 'table')
59-
.array('urls')
61+
.option('urls', {array: true, type: 'string'})
6062
.string('lh-flags')
6163
.default('desc', false)
6264
.default('sort-by-absolute-value', false)
@@ -65,6 +67,10 @@ const argv = yargs
6567
.wrap(yargs.terminalWidth())
6668
.argv;
6769

70+
// Augmenting yargs type with auto-camelCasing breaks in tsc@4.1.2 and @types/yargs@15.0.11,
71+
// so for now cast to add yarg's camelCase properties to type.
72+
const argv = /** @type {typeof rawArgv & CamelCasify<typeof rawArgv>} */ (rawArgv);
73+
6874
const reportExcludeRegex =
6975
argv.reportExclude !== 'none' ? new RegExp(argv.reportExclude, 'i') : null;
7076

@@ -120,12 +126,15 @@ function round(value) {
120126
* @param {number} total
121127
* @return {string}
122128
*/
123-
function getProgressBar(i, total = argv.n * argv.urls.length) {
129+
function getProgressBar(i, total = argv.n * (argv.urls || []).length) {
124130
const bars = new Array(Math.round(i * 40 / total)).fill('▄').join('').padEnd(40);
125131
return `${i + 1} / ${total} [${bars}]`;
126132
}
127133

128134
async function gather() {
135+
if (typeof argv.name !== 'string') {
136+
throw new Error('expected entry for name option');
137+
}
129138
const outputDir = dir(argv.name);
130139
if (fs.existsSync(outputDir)) {
131140
console.log('Collection already started - resuming.');
@@ -136,7 +145,7 @@ async function gather() {
136145
progress.log('Gathering…');
137146

138147
let progressCount = 0;
139-
for (const url of argv.urls) {
148+
for (const url of argv.urls || []) {
140149
const urlFolder = `${outputDir}/${urlToFolder(url)}`;
141150
await mkdir(urlFolder, {recursive: true});
142151

@@ -161,12 +170,15 @@ async function gather() {
161170
}
162171

163172
async function audit() {
173+
if (typeof argv.name !== 'string') {
174+
throw new Error('expected entry for name option');
175+
}
164176
const outputDir = dir(argv.name);
165177
const progress = new ProgressLogger();
166178
progress.log('Auditing…');
167179

168180
let progressCount = 0;
169-
for (const url of argv.urls) {
181+
for (const url of argv.urls || []) {
170182
const urlDir = `${outputDir}/${urlToFolder(url)}`;
171183
for (let i = 0; i < argv.n; i++) {
172184
const gatherDir = `${urlDir}/${i}`;
@@ -309,6 +321,9 @@ function isNumber(value) {
309321
}
310322

311323
function summarize() {
324+
if (typeof argv.name !== 'string') {
325+
throw new Error('expected entry for name option');
326+
}
312327
const results = aggregateResults(argv.name);
313328
print(filter(results));
314329
}

‎package.json

+3-3
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@
114114
"@types/semver": "^5.5.0",
115115
"@types/update-notifier": "^4.1.0",
116116
"@types/ws": "^4.0.1",
117-
"@types/yargs": "^8.0.2",
117+
"@types/yargs": "^15.0.11",
118118
"@types/yargs-parser": "^15.0.0",
119119
"@typescript-eslint/parser": "^4.7.0",
120120
"@wardpeet/brfs": "2.1.0",
@@ -188,8 +188,8 @@
188188
"third-party-web": "^0.12.2",
189189
"update-notifier": "^4.1.0",
190190
"ws": "3.3.2",
191-
"yargs": "3.32.0",
192-
"yargs-parser": "^18.1.3"
191+
"yargs": "^16.1.1",
192+
"yargs-parser": "^20.2.4"
193193
},
194194
"repository": "GoogleChrome/lighthouse",
195195
"keywords": [

‎readme.md

+53-55
Original file line numberDiff line numberDiff line change
@@ -70,79 +70,77 @@ By default, Lighthouse writes the report to an HTML file. You can control the ou
7070
```
7171
$ lighthouse --help
7272
73-
lighthouse <url>
73+
lighthouse <url> <options>
7474
7575
Logging:
76-
--verbose Displays verbose logging [boolean]
77-
--quiet Displays no progress, debug logs or errors [boolean]
76+
--verbose Displays verbose logging [boolean] [default: false]
77+
--quiet Displays no progress, debug logs, or errors [boolean] [default: false]
7878
7979
Configuration:
80-
--save-assets Save the trace & devtools log to disk [boolean]
81-
--list-all-audits Prints a list of all available audits and exits [boolean]
82-
--list-trace-categories Prints a list of all required trace categories and exits [boolean]
83-
--print-config Print the normalized config for the given config and options, then exit. [boolean]
84-
--additional-trace-categories Additional categories to capture with the trace (comma-delimited).
80+
--save-assets Save the trace contents & devtools logs to disk [boolean] [default: false]
81+
--list-all-audits Prints a list of all available audits and exits [boolean] [default: false]
82+
--list-trace-categories Prints a list of all required trace categories and exits [boolean] [default: false]
83+
--print-config Print the normalized config for the given config and options, then exit. [boolean] [default: false]
84+
--additional-trace-categories Additional categories to capture with the trace (comma-delimited). [string]
8585
--config-path The path to the config JSON.
86-
An example config file: lighthouse-core/config/lr-desktop-config.js
87-
--budget-path The path to the budget.json file for LightWallet.
88-
--chrome-flags Custom flags to pass to Chrome (space-delimited). For a full list of flags, see
89-
http://peter.sh/experiments/chromium-command-line-switches/.
90-
91-
Environment variables:
92-
CHROME_PATH: Explicit path of intended Chrome binary. If set must point to an executable of a build of
93-
Chromium version 66.0 or later. By default, any detected Chrome Canary or Chrome (stable) will be launched.
94-
[default: ""]
95-
--port The port to use for the debugging protocol. Use 0 for a random port [default: 0]
96-
--preset Use a built-in configuration. [choices: "experimental", "perf"]
97-
WARNING: If the --config-path flag is provided, this preset will be ignored.
98-
--hostname The hostname to use for the debugging protocol. [default: "localhost"]
99-
--max-wait-for-load The timeout (in milliseconds) to wait before the page is considered done loading and the run should continue.
100-
WARNING: Very high values can lead to large traces and instability [default: 45000]
101-
--emulated-form-factor Controls the emulated device form factor (mobile vs. desktop) if not disabled [choices: "mobile", "desktop", "none"] [default: "mobile"]
102-
--enable-error-reporting Enables error reporting, overriding any saved preference. --no-enable-error-reporting will do the opposite. More:
103-
https://git.io/vFFTO
104-
--gather-mode, -G Collect artifacts from a connected browser and save to disk. If audit-mode is not also enabled, the run will quit
105-
early. [boolean]
106-
--audit-mode, -A Process saved artifacts from disk [boolean]
86+
An example config file: lighthouse-core/config/lr-desktop-config.js [string]
87+
--preset Use a built-in configuration.
88+
WARNING: If the --config-path flag is provided, this preset will be ignored. [string] [choices: "perf", "experimental"]
89+
--chrome-flags Custom flags to pass to Chrome (space-delimited). For a full list of flags, see https://bit.ly/chrome-flags
90+
Additionally, use the CHROME_PATH environment variable to use a specific Chrome binary. Requires Chromium version 66.0 or later. If omitted, any detected Chrome Canary or Chrome stable will be used. [string] [default: ""]
91+
--port The port to use for the debugging protocol. Use 0 for a random port [number] [default: 0]
92+
--hostname The hostname to use for the debugging protocol. [string] [default: "localhost"]
93+
--emulated-form-factor Controls the emulated device form factor (mobile vs. desktop) if not disabled [string] [choices: "mobile", "desktop", "none"]
94+
--max-wait-for-load The timeout (in milliseconds) to wait before the page is considered done loading and the run should continue. WARNING: Very high values can lead to large traces and instability [number]
95+
--enable-error-reporting Enables error reporting, overriding any saved preference. --no-enable-error-reporting will do the opposite. More: https://git.io/vFFTO [boolean]
96+
--gather-mode, -G Collect artifacts from a connected browser and save to disk. (Artifacts folder path may optionally be provided). If audit-mode is not also enabled, the run will quit early.
97+
--audit-mode, -A Process saved artifacts from disk. (Artifacts folder path may be provided, otherwise defaults to ./latest-run/)
98+
--only-audits Only run the specified audits [array]
99+
--only-categories Only run the specified categories. Available categories: accessibility, best-practices, performance, pwa, seo [array]
100+
--skip-audits Run everything except these audits [array]
101+
--budget-path The path to the budget.json file for LightWallet. [string]
107102
108103
Output:
109-
--output Reporter for the results, supports multiple values [choices: "json", "html", "csv"] [default: "html"]
104+
--output Reporter for the results, supports multiple values. choices: "json", "html", "csv" [array] [default: ["html"]]
110105
--output-path The file path to output the results. Use 'stdout' to write to stdout.
111-
If using JSON output, default is stdout.
112-
If using HTML or CSV output, default is a file in the working directory with a name based on the test URL and date.
113-
If using multiple outputs, --output-path is appended with the standard extension for each output type. "reports/my-run" -> "reports/my-run.report.html", "reports/my-run.report.json", etc.
114-
Example: --output-path=./lighthouse-results.html
115-
--view Open HTML report in your browser [boolean]
106+
If using JSON output, default is stdout.
107+
If using HTML or CSV output, default is a file in the working directory with a name based on the test URL and date.
108+
If using multiple outputs, --output-path is appended with the standard extension for each output type. "reports/my-run" -> "reports/my-run.report.html", "reports/my-run.report.json", etc.
109+
Example: --output-path=./lighthouse-results.html [string]
110+
--view Open HTML report in your browser [boolean] [default: false]
116111
117112
Options:
118-
--help Show help [boolean]
119-
--version Show version number [boolean]
120-
--cli-flags-path The path to a JSON file that contains the desired CLI flags to apply.
121-
Flags specified at the command line will still override the file-based ones.
122-
--blocked-url-patterns Block any network requests to the specified URL patterns [array]
123-
--disable-storage-reset Disable clearing the browser cache and other storage APIs before a run [boolean]
124-
--throttling-method Controls throttling method [choices: "devtools", "provided", "simulate"]
113+
--version Show version number [boolean]
114+
--help Show help [boolean]
115+
--cli-flags-path The path to a JSON file that contains the desired CLI flags to apply. Flags specified at the command line will still override the file-based ones.
116+
--locale The locale/language the report should be formatted in
117+
--blocked-url-patterns Block any network requests to the specified URL patterns [array]
118+
--disable-storage-reset Disable clearing the browser cache and other storage APIs before a run [boolean]
119+
--throttling-method Controls throttling method [string] [choices: "devtools", "provided", "simulate"]
120+
--throttling
125121
--throttling.rttMs Controls simulated network RTT (TCP layer)
126122
--throttling.throughputKbps Controls simulated network download throughput
127123
--throttling.requestLatencyMs Controls emulated network RTT (HTTP layer)
128124
--throttling.downloadThroughputKbps Controls emulated network download throughput
129125
--throttling.uploadThroughputKbps Controls emulated network upload throughput
130126
--throttling.cpuSlowdownMultiplier Controls simulated + emulated CPU throttling
131-
--extra-headers Set extra HTTP Headers to pass with request [string]
127+
--extra-headers Set extra HTTP Headers to pass with request
128+
--precomputed-lantern-data-path Path to the file where lantern simulation data should be read from, overwriting the lantern observed estimates for RTT and server latency. [string]
129+
--lantern-data-output-path Path to the file where lantern simulation data should be written to, can be used in a future run with the `precomputed-lantern-data-path` flag. [string]
130+
--plugins Run the specified plugins [array]
131+
--channel [string] [default: "cli"]
132+
--chrome-ignore-default-flags [boolean] [default: false]
132133
133134
Examples:
134-
lighthouse <url> --view Opens the HTML report in a browser after the run completes
135-
lighthouse <url> --config-path=./myconfig.js Runs Lighthouse with your own configuration: custom audits, report
136-
generation, etc.
137-
lighthouse <url> --output=json --output-path=./report.json --save-assets Save trace, devtoolslog, and named JSON report.
138-
lighthouse <url> --emulated-form-factor=none Disable device emulation and all throttling.
139-
--throttling-method=provided
140-
lighthouse <url> --chrome-flags="--window-size=412,660" Launch Chrome with a specific window size
141-
lighthouse <url> --quiet --chrome-flags="--headless" Launch Headless Chrome, turn off logging
142-
lighthouse <url> --extra-headers "{\"Cookie\":\"monster=blue\"}" Stringify\'d JSON HTTP Header key/value pairs to send in requests
143-
lighthouse <url> --extra-headers=./path/to/file.json Path to JSON file of HTTP Header key/value pairs to send in requests
144-
lighthouse <url> --only-categories=performance,pwa Only run the specified categories. Available categories: accessibility,
145-
best-practices, performance, pwa, seo.
135+
lighthouse <url> --view Opens the HTML report in a browser after the run completes
136+
lighthouse <url> --config-path=./myconfig.js Runs Lighthouse with your own configuration: custom audits, report generation, etc.
137+
lighthouse <url> --output=json --output-path=./report.json --save-assets Save trace, screenshots, and named JSON report.
138+
lighthouse <url> --emulated-form-factor=none --throttling-method=provided Disable device emulation and all throttling
139+
lighthouse <url> --chrome-flags="--window-size=412,660" Launch Chrome with a specific window size
140+
lighthouse <url> --quiet --chrome-flags="--headless" Launch Headless Chrome, turn off logging
141+
lighthouse <url> --extra-headers "{\"Cookie\":\"monster=blue\", \"x-men\":\"wolverine\"}" Stringify'd JSON HTTP Header key/value pairs to send in requests
142+
lighthouse <url> --extra-headers=./path/to/file.json Path to JSON file of HTTP Header key/value pairs to send in requests
143+
lighthouse <url> --only-categories=performance,pwa Only run the specified categories. Available categories: accessibility, best-practices, performance, pwa, seo
146144
147145
For more information on Lighthouse, see https://developers.google.com/web/tools/lighthouse/.
148146
```

‎tsconfig.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
"compilerOptions": {
33
"noEmit": true,
44
"module": "commonjs",
5-
"target": "ES2019",
5+
"target": "ES2020",
66
"allowJs": true,
77
"checkJs": true,
88
"strict": true,

‎types/externs.d.ts

+29-1
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,34 @@ declare global {
6464
type FirstParamType<T extends (arg1: any, ...args: any[]) => any> =
6565
T extends (arg1: infer P, ...args: any[]) => any ? P : never;
6666

67+
/**
68+
* Split string `S` on delimiter `D`.
69+
* From https://github.com/microsoft/TypeScript/pull/40336#issue-476562046
70+
*/
71+
type Split<S extends string, D extends string> =
72+
string extends S ? string[] :
73+
S extends '' ? [] :
74+
S extends `${infer T}${D}${infer U}` ? [T, ...Split<U, D>] :
75+
[S];
76+
77+
/**
78+
* Join an array of strings using camelCase capitalization rules.
79+
*/
80+
type StringsToCamelCase<T extends unknown[]> =
81+
T extends [] ? '' :
82+
T extends [string, ...infer U] ? `${T[0]}${Capitalize<StringsToCamelCase<U>>}` :
83+
string;
84+
85+
/**
86+
* If `S` is a kebab-style string `S`, convert to camelCase.
87+
*/
88+
type KebabToCamelCase<S> = S extends string ? StringsToCamelCase<Split<S, '-'>> : S;
89+
90+
/** Returns T with any kebab-style property names rewritten as camelCase. */
91+
type CamelCasify<T> = {
92+
[K in keyof T as KebabToCamelCase<K>]: T[K];
93+
}
94+
6795
module LH {
6896
// re-export useful type modules under global LH module.
6997
export import Crdp = _Crdp;
@@ -170,7 +198,7 @@ declare global {
170198
chromeIgnoreDefaultFlags: boolean;
171199
chromeFlags: string | string[];
172200
/** Output path for the generated results. */
173-
outputPath: string;
201+
outputPath?: string;
174202
/** Flag to save the trace contents and screenshots to disk. */
175203
saveAssets: boolean;
176204
/** Flag to open the report immediately. */

‎yarn.lock

+91-184
Large diffs are not rendered by default.

0 commit comments

Comments
 (0)
Please sign in to comment.