code
stringlengths 10
343k
| docstring
stringlengths 36
21.9k
| func_name
stringlengths 1
3.35k
| language
stringclasses 1
value | repo
stringlengths 7
58
| path
stringlengths 4
131
| url
stringlengths 44
195
| license
stringclasses 5
values |
---|---|---|---|---|---|---|---|
async function runCommand(options) {
const whichWizardPrompt = options.wizard
? options
: await inquirer.prompt([
{
type: 'list',
name: 'wizard',
message: 'Which wizard do you want to run?',
choices: ['new-project', 'reset-build-token', 'reset-admin-token'],
},
]);
switch (whichWizardPrompt.wizard) {
case 'new-project':
await runNewProjectWizard(options);
break;
case 'reset-build-token':
await runResetTokenWizard('build', options);
break;
case 'reset-admin-token':
await runResetTokenWizard('admin', options);
break;
default:
throw new Error(`Unrecognized wizard: ${whichWizardPrompt.wizard}`);
}
} | @param {LHCI.WizardCommand.Options} options
@return {Promise<void>} | runCommand ( options ) | javascript | GoogleChrome/lighthouse-ci | packages/cli/src/wizard/wizard.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/cli/src/wizard/wizard.js | Apache-2.0 |
function runChildCommand(command, args = []) {
const combinedArgs = [process.argv[1], command, ...args, ...getOverrideArgsForCommand(command)];
const {status = -1} = childProcess.spawnSync(process.argv[0], combinedArgs.filter(Boolean), {
stdio: 'inherit',
});
process.stdout.write('\n');
return {status: status || 0};
} | @param {'collect'|'assert'|'upload'|'healthcheck'} command
@param {string[]} [args]
@return {{status: number}} | runChildCommand ( command , args = [ ] ) | javascript | GoogleChrome/lighthouse-ci | packages/cli/src/autorun/autorun.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/cli/src/autorun/autorun.js | Apache-2.0 |
function getOverrideArgsForCommand(command, args = process.argv) {
const argPrefix = `--${command}.`;
return args
.filter(arg => arg.startsWith(argPrefix) || /--no-?lighthouserc/i.test(arg))
.map(arg => arg.replace(argPrefix, '--'));
} | @param {'collect'|'assert'|'upload'|'healthcheck'} command
@param {string[]} [args] | getOverrideArgsForCommand ( command , args = process . argv ) | javascript | GoogleChrome/lighthouse-ci | packages/cli/src/autorun/autorun.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/cli/src/autorun/autorun.js | Apache-2.0 |
async function runCommand(options) {
const rcFilePath = resolveRcFilePath(options.config);
const rcFile = rcFilePath && loadRcFile(rcFilePath);
const ciConfiguration = rcFile ? flattenRcToConfig(rcFile) : {};
_.merge(ciConfiguration, _.pick(options, ['assert', 'collect', 'upload']));
const defaultFlags = options.config ? [`--config=${options.config}`] : [];
let hasFailure = false;
const healthcheckStatus = runChildCommand('healthcheck', [...defaultFlags, '--fatal']).status;
if (healthcheckStatus !== 0) process.exit(healthcheckStatus);
const collectHasUrlOrBuildDir =
ciConfiguration.collect &&
(ciConfiguration.collect.url || ciConfiguration.collect.staticDistDir);
const collectArgs = collectHasUrlOrBuildDir
? [getStartServerCommandFlag()]
: [`--static-dist-dir=${findBuildDir()}`];
const collectStatus = runChildCommand('collect', [...defaultFlags, ...collectArgs]).status;
if (collectStatus !== 0) process.exit(collectStatus);
// We'll run assertions if there's assert options OR they haven't configured anything to do with the results
if (ciConfiguration.assert || (!ciConfiguration.assert && !ciConfiguration.upload)) {
const assertArgs = ciConfiguration.assert ? [] : [`--preset=lighthouse:recommended`];
const assertStatus = runChildCommand('assert', [...defaultFlags, ...assertArgs]).status;
hasFailure = assertStatus !== 0;
}
// We'll run upload only if they've configured the upload command
if (ciConfiguration.upload) {
const uploadStatus = runChildCommand('upload', defaultFlags).status;
if (options.failOnUploadFailure && uploadStatus !== 0) process.exit(uploadStatus);
if (uploadStatus !== 0) process.stderr.write(`WARNING: upload command failed.\n`);
}
if (hasFailure) {
process.stderr.write(`assert command failed. Exiting with status code 1.\n`);
process.exit(1);
}
process.stdout.write(`Done running autorun.\n`);
} | @param {LHCI.AutorunCommand.Options} options
@return {Promise<void>} | runCommand ( options ) | javascript | GoogleChrome/lighthouse-ci | packages/cli/src/autorun/autorun.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/cli/src/autorun/autorun.js | Apache-2.0 |
async function runCommand(options) {
const {budgetsFile, assertions, assertMatrix, preset, lhr} = options;
const areAssertionsSet = Boolean(assertions || assertMatrix || preset);
if (!areAssertionsSet && !budgetsFile) throw new Error('No assertions to use');
if (budgetsFile && areAssertionsSet) throw new Error('Cannot use both budgets AND assertions');
// If we have a budgets file, convert it to our assertions format.
if (budgetsFile) options = await convertBudgetsToAssertions(readBudgets(budgetsFile));
const lhrs = loadSavedLHRs(lhr).map(json => JSON.parse(json));
const uniqueUrls = new Set(lhrs.map(lhr => lhr.finalUrl));
const allResults = getAllAssertionResults(options, lhrs);
const groupedResults = _.groupBy(allResults, result => result.url);
process.stderr.write(
`Checking assertions against ${uniqueUrls.size} URL(s), ${lhrs.length} total run(s)\n\n`
);
let hasFailure = false;
for (const results of groupedResults) {
const url = results[0].url;
// Sort the results by
// - Failing audits with error level alphabetical
// - Failing audits with warn level alphabetical
// - Passing audits alphabetical
const sortedResults = results.sort((a, b) => {
const {level: levelA = 'error', auditId: auditIdA = 'unknown', passed: passedA} = a;
const {level: levelB = 'error', auditId: auditIdB = 'unknown', passed: passedB} = b;
if (passedA !== passedB) return String(passedA).localeCompare(String(passedB));
if (passedA) return auditIdA.localeCompare(auditIdB);
return levelA.localeCompare(levelB) || auditIdA.localeCompare(auditIdB);
});
process.stderr.write(`${sortedResults.length} result(s) for ${log.bold}${url}${log.reset} :\n`);
for (const result of sortedResults) {
const {level, passed, auditId} = result;
const isFailure = !passed && level === 'error';
hasFailure = hasFailure || isFailure;
const label = passed ? 'passing' : level === 'warn' ? 'warning' : 'failure';
const icon = passed ? '✅ ' : level === 'warn' ? '⚠️ ' : `${log.redify(log.cross)} `;
const idPart = `${log.bold}${auditId}${log.reset}`;
const propertyPart = result.auditProperty ? `.${result.auditProperty}` : '';
const namePart = `${log.bold}${result.name}${log.reset}`;
const auditTitlePart = result.auditTitle || '';
const documentationPart = result.auditDocumentationLink || '';
const titleAndDocs = [auditTitlePart, documentationPart, result.message]
.filter(Boolean)
.map(s => ` ` + s)
.join('\n');
const humanFriendlyParts = titleAndDocs ? `\n${titleAndDocs}\n` : '';
process.stderr.write(`
${icon} ${idPart}${propertyPart} ${label} for ${namePart} assertion${humanFriendlyParts}
expected: ${result.operator}${log.greenify(result.expected)}
found: ${passed ? log.greenify(result.actual) : log.redify(result.actual)}
${log.dim}all values: ${result.values.join(', ')}${log.reset}\n\n`);
}
}
saveAssertionResults(allResults);
if (hasFailure) {
process.stderr.write(`Assertion failed. Exiting with status code 1.\n`);
process.exit(1);
}
process.stderr.write(`All results processed!\n`);
} | @param {LHCI.AssertCommand.Options} options
@return {Promise<void>} | runCommand ( options ) | javascript | GoogleChrome/lighthouse-ci | packages/cli/src/assert/assert.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/cli/src/assert/assert.js | Apache-2.0 |
function getUrlLabelForGithub(rawUrl, options) {
try {
const url = new URL(rawUrl);
return replaceUrlPatterns(url.pathname, options.urlReplacementPatterns);
} catch (_) {
return replaceUrlPatterns(rawUrl, options.urlReplacementPatterns);
}
} | @param {string} rawUrl
@param {LHCI.UploadCommand.Options} options | getUrlLabelForGithub ( rawUrl , options ) | javascript | GoogleChrome/lighthouse-ci | packages/cli/src/upload/upload.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/cli/src/upload/upload.js | Apache-2.0 |
function getGitHubContext(urlLabel, options) {
const prefix = options.githubStatusContextSuffix
? `lhci${options.githubStatusContextSuffix}`
: 'lhci';
return `${prefix}/url${urlLabel}`;
} | @param {string} urlLabel
@param {LHCI.UploadCommand.Options} options | getGitHubContext ( urlLabel , options ) | javascript | GoogleChrome/lighthouse-ci | packages/cli/src/upload/upload.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/cli/src/upload/upload.js | Apache-2.0 |
async function runGithubStatusCheck(options, targetUrlMap) {
const {githubToken, githubAppToken, githubApiHost, githubAppUrl} = options;
const hash = getCurrentHash();
const slug = getGitHubRepoSlug(githubApiHost);
if (!githubToken && !githubAppToken) {
return print('No GitHub token set, skipping GitHub status check.\n');
}
print('GitHub token found, attempting to set status...\n');
if (!slug) return print(`No GitHub remote found, skipping.\n`);
if (!slug.includes('/')) return print(`Invalid repo slug "${slug}", skipping.\n`);
if (!hash) return print(`Invalid hash "${hash}"\n, skipping.`);
const assertionResults = loadAssertionResults();
const groupedResults = _.groupBy(assertionResults, result => result.url).sort(
(a, b) => a[0].url.length - b[0].url.length
);
if (groupedResults.length) {
for (const group of groupedResults) {
const rawUrl = group[0].url;
const urlLabel = getUrlLabelForGithub(rawUrl, options);
const failedResults = group.filter(result => result.level === 'error' && !result.passed);
const warnResults = group.filter(result => result.level === 'warn' && !result.passed);
const state = failedResults.length ? 'failure' : 'success';
const context = getGitHubContext(urlLabel, options);
const warningsLabel = warnResults.length ? ` with ${warnResults.length} warning(s)` : '';
const description = failedResults.length
? `Failed ${failedResults.length} assertion(s)`
: `Passed${warningsLabel}`;
const targetUrl = targetUrlMap.get(rawUrl) || rawUrl;
await postStatusToGitHub({
slug,
hash,
state,
context,
description,
targetUrl,
githubToken,
githubAppToken,
githubApiHost,
githubAppUrl,
});
}
} else {
/** @type {Array<LH.Result>} */
const lhrs = loadSavedLHRs().map(lhr => JSON.parse(lhr));
/** @type {Array<Array<[LH.Result, LH.Result]>>} */
const lhrsByUrl = _.groupBy(lhrs, lhr => lhr.finalUrl).map(lhrs => lhrs.map(lhr => [lhr, lhr]));
const representativeLhrs = computeRepresentativeRuns(lhrsByUrl);
if (!representativeLhrs.length) return print('No LHRs for status check, skipping.\n');
for (const lhr of representativeLhrs) {
const rawUrl = lhr.finalUrl;
const urlLabel = getUrlLabelForGithub(rawUrl, options);
const state = 'success';
const context = getGitHubContext(urlLabel, options);
const categoriesDescription = Object.values(lhr.categories)
.map(category => `${category.title}: ${Math.round(category.score * 100)}`)
.join(', ');
const description = `${categoriesDescription}`;
const targetUrl = targetUrlMap.get(rawUrl) || rawUrl;
await postStatusToGitHub({
slug,
hash,
state,
context,
description,
targetUrl,
githubToken,
githubAppToken,
githubApiHost,
githubAppUrl,
});
}
}
} | @param {LHCI.UploadCommand.Options} options
@param {Map<string, string>} targetUrlMap
@return {Promise<void>} | runGithubStatusCheck ( options , targetUrlMap ) | javascript | GoogleChrome/lighthouse-ci | packages/cli/src/upload/upload.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/cli/src/upload/upload.js | Apache-2.0 |
async function getPreviousUrlMap(options) {
const slug = getGitHubRepoSlug();
if (!slug) return new Map();
try {
const fetchUrl = new URL(GET_URL_MAP_URL);
fetchUrl.searchParams.set('slug', slug);
const apiResponse = await fetch(fetchUrl.href);
if (!apiResponse.ok) return new Map();
const {success, url} = await apiResponse.json();
if (!success) return new Map();
const mapResponse = await fetch(url);
if (mapResponse.status !== 200) return new Map();
const entries = Object.entries(await mapResponse.json());
return new Map(
entries.map(([k, v]) => [replaceUrlPatterns(k, options.urlReplacementPatterns), v])
);
} catch (err) {
print(`Error while fetching previous urlMap: ${err.message}`);
return new Map();
}
} | Fetches the last public URL mapping from master if it exists.
@param {LHCI.UploadCommand.Options} options
@return {Promise<Map<string, string>>} | getPreviousUrlMap ( options ) | javascript | GoogleChrome/lighthouse-ci | packages/cli/src/upload/upload.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/cli/src/upload/upload.js | Apache-2.0 |
function buildTemporaryStorageLink(compareUrl, urlAudited, previousUrlMap) {
const baseUrl = previousUrlMap.get(urlAudited);
if (!baseUrl) return compareUrl;
const linkUrl = new URL(DIFF_VIEWER_URL);
linkUrl.searchParams.set('baseReport', baseUrl);
linkUrl.searchParams.set('compareReport', compareUrl);
return linkUrl.href;
} | @param {string} compareUrl
@param {string} urlAudited
@param {Map<string, string>} previousUrlMap
@return {string} | buildTemporaryStorageLink ( compareUrl , urlAudited , previousUrlMap ) | javascript | GoogleChrome/lighthouse-ci | packages/cli/src/upload/upload.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/cli/src/upload/upload.js | Apache-2.0 |
async function runCommand(options) {
options.urlReplacementPatterns = options.urlReplacementPatterns.filter(Boolean);
switch (options.target) {
case 'lhci':
try {
return await runLHCITarget(options);
} catch (err) {
if (options.ignoreDuplicateBuildFailure && /Build already exists/.test(err.message)) {
print('Build already exists but ignore requested via options, skipping upload...');
return;
}
throw err;
}
case 'temporary-public-storage':
return runTemporaryPublicStorageTarget(options);
case 'filesystem':
return runFilesystemTarget(options);
default:
throw new Error(`Unrecognized target "${options.target}"`);
}
}
module.exports = {buildCommand, runCommand}; | @param {LHCI.UploadCommand.Options} options
@return {Promise<void>} | runCommand ( options ) | javascript | GoogleChrome/lighthouse-ci | packages/cli/src/upload/upload.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/cli/src/upload/upload.js | Apache-2.0 |
static _requirePuppeteer() {
try {
// eslint-disable-next-line import/no-extraneous-dependencies
return require('puppeteer');
} catch (_) {}
try {
// @ts-ignore - puppeteer-core is API-compatible with puppeteer
// eslint-disable-next-line import/no-extraneous-dependencies
return require('puppeteer-core');
} catch (_) {}
// Try relative to the CWD too in case we're installed globally
try {
return require(path.join(process.cwd(), 'node_modules/puppeteer'));
} catch (_) {}
try {
return require(path.join(process.cwd(), 'node_modules/puppeteer-core'));
} catch (_) {}
} | Returns the puppeteer module. First attempts to require `puppeteer` and then `puppeteer-core`
if puppeteer is not available. They are the exact same API but puppeteer-core requires explicit
setting of `collect.chromePath`.
@return {typeof import('puppeteer')|undefined} | _requirePuppeteer ( ) | javascript | GoogleChrome/lighthouse-ci | packages/cli/src/collect/puppeteer-manager.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/cli/src/collect/puppeteer-manager.js | Apache-2.0 |
static getChromiumPath(options) {
// If we're not using puppeteer, return undefined.
if (!options.puppeteerScript) return undefined;
// Otherwise, check to see if the expected puppeteer download exists.
const puppeteer = PuppeteerManager._requirePuppeteer();
const puppeteerUnknown = /** @type {unknown} */ (puppeteer);
const pupppeteerNode = /** @type {import('puppeteer').PuppeteerNode | undefined} */ (
puppeteerUnknown
);
const chromiumPath = pupppeteerNode && pupppeteerNode.executablePath();
return chromiumPath && fs.existsSync(chromiumPath) ? chromiumPath : undefined;
} | @param {{puppeteerScript?: string}} options
@return {string|undefined} | getChromiumPath ( options ) | javascript | GoogleChrome/lighthouse-ci | packages/cli/src/collect/puppeteer-manager.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/cli/src/collect/puppeteer-manager.js | Apache-2.0 |
async invokePuppeteerScriptForUrl(url) {
const scriptPath = this._options.puppeteerScript;
if (!scriptPath) return;
const browser = await this._getBrowser();
/** @type {PuppeteerScript} */
const script = require(path.join(process.cwd(), scriptPath));
await script(browser, {url, options: this._options});
} | @param {string} url
@return {Promise<void>} | invokePuppeteerScriptForUrl ( url ) | javascript | GoogleChrome/lighthouse-ci | packages/cli/src/collect/puppeteer-manager.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/cli/src/collect/puppeteer-manager.js | Apache-2.0 |
async run(url, options = {}) {
const apiKey = options.psiApiKey;
if (!apiKey) throw new Error('PSI API key must be provided to use the PSI runner');
const client = new PsiClient({apiKey, endpointURL: options.psiApiEndpoint});
return JSON.stringify(await client.run(url, {strategy: options.psiStrategy}));
} | @param {string} url
@param {Partial<LHCI.CollectCommand.Options>} [options]
@return {Promise<string>} | run ( url , options = { } ) | javascript | GoogleChrome/lighthouse-ci | packages/cli/src/collect/psi-runner.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/cli/src/collect/psi-runner.js | Apache-2.0 |
constructor(pathToBuildDir, isSinglePageApplication) {
this._pathToBuildDir = pathToBuildDir;
this._app = express();
this._app.use(compression());
this._app.use('/', express.static(pathToBuildDir));
this._app.use('/app', express.static(pathToBuildDir));
if (isSinglePageApplication) {
this._app.use('/*', (req, res) => res.sendFile(pathToBuildDir + '/index.html'));
}
this._port = 0;
/** @type {undefined|ReturnType<typeof createHttpServer>} */
this._server = undefined;
} | @param {string} pathToBuildDir
@param {boolean|undefined} isSinglePageApplication | constructor ( pathToBuildDir , isSinglePageApplication ) | javascript | GoogleChrome/lighthouse-ci | packages/cli/src/collect/fallback-server.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/cli/src/collect/fallback-server.js | Apache-2.0 |
getAvailableUrls(maxDepth) {
if (maxDepth >= 0) {
maxDepth = Math.floor(maxDepth);
} else {
process.stderr.write(
`WARNING: staticDirFileDiscoveryDepth must be greater than 0. Defaulting to a discovery depth of 2\n`
);
maxDepth = 2;
}
const htmlFiles = FallbackServer.readHtmlFilesInDirectory(this._pathToBuildDir, maxDepth);
return htmlFiles.map(({file}) => `http://localhost:${this._port}/${file}`);
} | @param {number} maxDepth
@return {string[]} | getAvailableUrls ( maxDepth ) | javascript | GoogleChrome/lighthouse-ci | packages/cli/src/collect/fallback-server.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/cli/src/collect/fallback-server.js | Apache-2.0 |
static readHtmlFilesInDirectory(directory, depth) {
const filesAndFolders = fs.readdirSync(directory, {withFileTypes: true});
const files = filesAndFolders.filter(fileOrDir => fileOrDir.isFile()).map(file => file.name);
const folders = filesAndFolders
.filter(fileOrDir => fileOrDir.isDirectory())
.map(dir => dir.name);
const htmlFiles = files
.filter(file => file.endsWith('.html') || file.endsWith('.htm'))
.map(file => ({file, depth: 0}));
if (depth === 0) return htmlFiles;
for (const folder of folders) {
// Don't recurse into hidden folders, things that look like files, or dependency folders
if (folder.includes('.')) continue;
if (IGNORED_FOLDERS_FOR_AUTOFIND.has(folder)) continue;
try {
const fullPath = path.join(directory, folder);
if (!fs.statSync(fullPath).isDirectory()) continue;
htmlFiles.push(
...FallbackServer.readHtmlFilesInDirectory(fullPath, depth - 1).map(({file, depth}) => {
return {file: `${folder}/${file}`, depth: depth + 1};
})
);
} catch (err) {}
}
return htmlFiles;
} | @param {string} directory
@param {number} depth
@return {Array<{file: string, depth: number}>} | readHtmlFilesInDirectory ( directory , depth ) | javascript | GoogleChrome/lighthouse-ci | packages/cli/src/collect/fallback-server.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/cli/src/collect/fallback-server.js | Apache-2.0 |
function checkIgnoredChromeFlagsOption(options) {
const usePuppeteerScript = !!options.puppeteerScript;
const useChromeFlags = options.settings ? !!options.settings.chromeFlags : false;
if (usePuppeteerScript && useChromeFlags) {
process.stderr.write(`WARNING: collect.settings.chromeFlags option will be ignored.\n`);
process.stderr.write(
`WARNING: If you want chromeFlags with puppeteerScript, use collect.puppeteerLaunchOptions.args option.\n`
);
}
} | @param {LHCI.CollectCommand.Options} options
@return {void} | checkIgnoredChromeFlagsOption ( options ) | javascript | GoogleChrome/lighthouse-ci | packages/cli/src/collect/collect.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/cli/src/collect/collect.js | Apache-2.0 |
async function runCommand(options) {
const checkIdsToRun = options.checks || [];
let allPassed = true;
for (const check of checks) {
if (!check.shouldTest(options)) continue;
let result = false;
let message = '';
try {
result = await check.test(options);
} catch (err) {
result = false;
message = `\n ERROR: ${err.message}`;
}
const isWarn = !!check.id && !checkIdsToRun.includes(check.id);
const icon = result ? PASS_ICON : isWarn ? WARN_ICON : FAIL_ICON;
const label = result ? check.label : check.failureLabel;
allPassed = allPassed && (isWarn || result);
process.stdout.write(`${icon} ${label}${message}\n`);
}
if (allPassed) {
process.stdout.write('Healthcheck passed!\n');
} else {
process.stdout.write('Healthcheck failed!\n');
if (options.fatal) process.exit(1);
}
} | @param {LHCI.YargsOptions} options
@return {Promise<void>} | runCommand ( options ) | javascript | GoogleChrome/lighthouse-ci | packages/cli/src/healthcheck/healthcheck.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/cli/src/healthcheck/healthcheck.js | Apache-2.0 |
async function generateReport(lhr) {
// This isn't technically JSON anymore but it works for this test.
const lhrString = JSON.stringify(lhr).replaceAll(`"`, `'`);
const {stdout} = await execAsync(
`node -e "import('lighthouse').then(m=>console.log(m.generateReport(${lhrString})))"`
);
return stdout;
} | Jest does a bad job with esm, so we mock the report generation with a CLI call here. | generateReport ( lhr ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/test/saved-reports.test.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/test/saved-reports.test.js | Apache-2.0 |
async function getDefaultConfig() {
const {stdout} = await execAsync(
`node -e "import('lighthouse').then(c=>console.log(JSON.stringify(c.defaultConfig)))"`
);
return JSON.parse(stdout);
} | Jest does a bad job with esm, so we get the default config via cli here. | getDefaultConfig ( ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/test/presets.test.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/test/presets.test.js | Apache-2.0 |
function getDeltaLabel(delta, deltaType = 'audit') {
if (delta === 0) return 'neutral';
let isImprovement = delta < 0;
if (deltaType === 'score') isImprovement = delta > 0;
return isImprovement ? 'improvement' : 'regression';
} | @param {number} delta
@param {'audit'|'score'} deltaType
@return {DiffLabel} | getDeltaLabel ( delta , deltaType = 'audit' ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/audit-diff-finder.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/audit-diff-finder.js | Apache-2.0 |
function getDiffLabel(diff) {
switch (diff.type) {
case 'error':
return 'regression';
case 'score':
return getDeltaLabel(getDeltaStats(diff).delta, 'score');
case 'numericValue':
case 'itemCount':
case 'itemDelta':
return getDeltaLabel(getDeltaStats(diff).delta, 'audit');
case 'itemAddition':
return 'regression';
case 'itemRemoval':
return 'improvement';
default:
return 'neutral';
}
} | @param {LHCI.AuditDiff} diff
@return {DiffLabel} | getDiffLabel ( diff ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/audit-diff-finder.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/audit-diff-finder.js | Apache-2.0 |
function getRowLabel(diffs) {
if (!diffs.length) return 'no change';
if (diffs.some(diff => diff.type === 'itemAddition')) return 'added';
if (diffs.some(diff => diff.type === 'itemRemoval')) return 'removed';
const itemDeltaDiffs = diffs.filter(
/** @return {diff is LHCI.NumericItemAuditDiff} */ diff => diff.type === 'itemDelta'
);
// All the diffs were worse, it's "worse".
if (itemDeltaDiffs.every(diff => diff.compareValue > diff.baseValue)) return 'worse';
// All the diffs were better, it's "better".
if (itemDeltaDiffs.every(diff => diff.compareValue < diff.baseValue)) return 'better';
// The item had diffs but some were better and some were worse, so we can't decide.
if (itemDeltaDiffs.length) return 'ambiguous';
return 'no change';
} | Given the array of diffs for a particular row, determine its label.
@param {Array<LHCI.AuditDiff>} diffs
@return {RowLabel} | getRowLabel ( diffs ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/audit-diff-finder.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/audit-diff-finder.js | Apache-2.0 |
function getMatchingDiffsForIndex(diffs, compareItemIndex, baseItemIndex) {
return diffs.filter(diff => {
const compareIndex = 'compareItemIndex' in diff ? diff.compareItemIndex : undefined;
const baseIndex = 'baseItemIndex' in diff ? diff.baseItemIndex : undefined;
if (typeof compareIndex === 'number') return compareIndex === compareItemIndex;
if (typeof baseIndex === 'number') return baseIndex === baseItemIndex;
return false;
});
} | @param {Array<LHCI.AuditDiff>} diffs
@param {number|undefined} compareItemIndex
@param {number|undefined} baseItemIndex
@return {Array<LHCI.AuditDiff>} | getMatchingDiffsForIndex ( diffs , compareItemIndex , baseItemIndex ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/audit-diff-finder.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/audit-diff-finder.js | Apache-2.0 |
function getRowLabelForIndex(diffs, compareItemIndex, baseItemIndex) {
return getRowLabel(getMatchingDiffsForIndex(diffs, compareItemIndex, baseItemIndex));
} | Given the array of all diffs for an audit, determine the label for a row with particular item index.
@param {Array<LHCI.AuditDiff>} diffs
@param {number|undefined} compareItemIndex
@param {number|undefined} baseItemIndex
@return {RowLabel} | getRowLabelForIndex ( diffs , compareItemIndex , baseItemIndex ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/audit-diff-finder.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/audit-diff-finder.js | Apache-2.0 |
function getWorstNumericDeltaForIndex(diffs, compareItemIndex, baseItemIndex) {
const matchingDiffs = getMatchingDiffsForIndex(diffs, compareItemIndex, baseItemIndex);
const numericDiffs = matchingDiffs.filter(isNumericAuditDiff);
if (!numericDiffs.length) return undefined;
return Math.max(...numericDiffs.map(diff => getDeltaStats(diff).delta));
} | Given the array of all diffs for an audit, determine the worst numeric delta for a particular row.
Used for sorting.
@param {Array<LHCI.AuditDiff>} diffs
@param {number|undefined} compareItemIndex
@param {number|undefined} baseItemIndex
@return {number|undefined} | getWorstNumericDeltaForIndex ( diffs , compareItemIndex , baseItemIndex ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/audit-diff-finder.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/audit-diff-finder.js | Apache-2.0 |
function isNumericAuditDiff(diff) {
return ['score', 'numericValue', 'itemCount', 'itemDelta'].includes(diff.type);
} | @param {LHCI.AuditDiff} diff
* @return {diff is LHCI.NumericAuditDiff|LHCI.NumericItemAuditDiff} | isNumericAuditDiff ( diff ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/audit-diff-finder.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/audit-diff-finder.js | Apache-2.0 |
function getDeltaStats(diff) {
const {baseValue, compareValue} = diff;
const delta = compareValue - baseValue;
const absoluteDelta = Math.abs(delta);
// Handle the 0 case to avoid messy NaN handling.
if (delta === 0) return {delta, absoluteDelta, percentDelta: 0, percentAbsoluteDelta: 0};
// Percent delta is `delta / baseValue` unless `baseValue == 0`.
// Then `percentDelta` is 100% by arbitrary convention (instead of Infinity/NaN).
const percentDelta = baseValue ? delta / baseValue : 1;
const percentAbsoluteDelta = Math.abs(percentDelta);
return {
delta,
absoluteDelta,
percentDelta,
percentAbsoluteDelta,
};
} | @param {LHCI.NumericAuditDiff | LHCI.NumericItemAuditDiff} diff | getDeltaStats ( diff ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/audit-diff-finder.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/audit-diff-finder.js | Apache-2.0 |
function createAuditDiff(diff) {
const {auditId, type, baseValue, compareValue, baseItemIndex, compareItemIndex, itemKey} = diff;
if (type === 'itemAddition') {
if (typeof compareItemIndex !== 'number') throw new Error('compareItemIndex is not set');
return {auditId, type, compareItemIndex};
}
if (type === 'itemRemoval') {
if (typeof baseItemIndex !== 'number') throw new Error('baseItemIndex is not set');
return {auditId, type, baseItemIndex};
}
if (type === 'displayValue') {
throw new Error('Do not use createAuditDiff for displayValue, just manually create');
}
if (
typeof compareValue !== 'number' ||
typeof baseValue !== 'number' ||
!Number.isFinite(baseValue) ||
!Number.isFinite(compareValue) ||
type === 'error'
) {
return {
auditId,
type: 'error',
attemptedType: type,
baseValue: baseValue || NaN,
compareValue: compareValue || NaN,
};
}
/** @type {LHCI.NumericAuditDiff} */
const numericDiffResult = {
auditId,
type: 'score',
baseValue,
compareValue,
};
if (type === 'itemDelta') {
if (typeof itemKey !== 'string') throw new Error('itemKey is not set');
if (typeof baseItemIndex !== 'number' && typeof compareItemIndex !== 'number') {
throw new Error('Either baseItemIndex or compareItemIndex must be set');
}
return {
...numericDiffResult,
type: 'itemDelta',
baseItemIndex,
compareItemIndex,
itemKey,
};
}
return {...numericDiffResult, type};
} | @param {{auditId: string, type: LHCI.AuditDiffType, baseValue?: number|null, compareValue?: number|null, itemKey?: string, baseItemIndex?: number, compareItemIndex?: number}} diff
@return {LHCI.AuditDiff} | createAuditDiff ( diff ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/audit-diff-finder.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/audit-diff-finder.js | Apache-2.0 |
function findAuditDetailItemKeyDiffs(auditId, baseEntry, compareEntry, headings) {
/** @type {Array<LHCI.AuditDiff>} */
const diffs = [];
for (const key of Object.keys(baseEntry.item)) {
const baseValue = baseEntry.item[key];
const compareValue = compareEntry.item[key];
// If these aren't numeric, comparable values, skip the key.
if (typeof baseValue !== 'number' || typeof compareValue !== 'number') continue;
// If these aren't shown in the table, skip the key.
if (!headings.some(heading => heading.key === key)) continue;
diffs.push(
createAuditDiff({
auditId,
type: 'itemDelta',
itemKey: key,
baseItemIndex: baseEntry.index,
compareItemIndex: compareEntry.index,
baseValue,
compareValue,
})
);
}
return diffs;
} | @param {string} auditId
@param {DetailItemEntry} baseEntry
@param {DetailItemEntry} compareEntry
@param {Array<{key: string | null}>} headings
@return {Array<LHCI.AuditDiff>} | findAuditDetailItemKeyDiffs ( auditId , baseEntry , compareEntry , headings ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/audit-diff-finder.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/audit-diff-finder.js | Apache-2.0 |
function synthesizeItemKeyDiffs(diffs, baseItems, compareItems) {
/** @type {Array<LHCI.AuditDiff>} */
const itemKeyDiffs = [];
for (const diff of diffs) {
if (diff.type !== 'itemAddition' && diff.type !== 'itemRemoval') continue;
const item =
diff.type === 'itemAddition'
? compareItems[diff.compareItemIndex]
: baseItems[diff.baseItemIndex];
for (const key of Object.keys(item)) {
const baseValue = diff.type === 'itemAddition' ? 0 : item[key];
const compareValue = diff.type === 'itemAddition' ? item[key] : 0;
if (typeof compareValue !== 'number' || typeof baseValue !== 'number') continue;
const itemIndexKeyName = diff.type === 'itemAddition' ? 'compareItemIndex' : 'baseItemIndex';
const itemIndexValue =
diff.type === 'itemAddition' ? diff.compareItemIndex : diff.baseItemIndex;
itemKeyDiffs.push(
createAuditDiff({
auditId: diff.auditId,
type: 'itemDelta',
itemKey: key,
[itemIndexKeyName]: itemIndexValue,
baseValue,
compareValue,
})
);
}
}
return itemKeyDiffs;
} | This function creates NumericItemAuditDiffs from itemAddition/itemRemoved diffs. Normally, these
are superfluous data, but in some instances (table details views for example), it's desirable to
understand the diff state of each individual itemKey. The missing values are assumed to be 0
for the purposes of the diff.
@param {Array<LHCI.AuditDiff>} diffs
@param {Array<Record<string, any>>} baseItems
@param {Array<Record<string, any>>} compareItems
@return {Array<LHCI.AuditDiff>} | synthesizeItemKeyDiffs ( diffs , baseItems , compareItems ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/audit-diff-finder.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/audit-diff-finder.js | Apache-2.0 |
function deepPruneItemForKeySerialization(item) {
if (typeof item !== 'object') return item;
if (item === null) return item;
if (Array.isArray(item)) {
return item.map(entry => deepPruneItemForKeySerialization(entry));
} else {
const itemAsRecord = /** @type {Record<string, unknown>} */ (item);
const keys = Object.keys(item);
const keysToKeep = keys.filter(key => !key.startsWith('_'));
/** @type {Record<string, any>} */
const copy = {};
for (const key of keysToKeep) {
copy[key] = deepPruneItemForKeySerialization(itemAsRecord[key]);
}
return copy;
}
} | The items passed to this method can be dirtied by other libraries and contain circular structures.
Prune any private-looking properties that start with `_` throughout the entire object.
@see https://github.com/GoogleChrome/lighthouse-ci/issues/666
@param {unknown} item
@return {unknown} | deepPruneItemForKeySerialization ( item ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/audit-diff-finder.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/audit-diff-finder.js | Apache-2.0 |
function zipBaseAndCompareItems(baseItems, compareItems) {
const groupedByKey = _.groupIntoMap(
[
...baseItems.map((item, i) => ({item, kind: 'base', index: i})),
...compareItems.map((item, i) => ({item, kind: 'compare', index: i})),
],
entry => replaceNondeterministicStrings(getItemKey(entry.item))
);
/** @type {Array<{base?: DetailItemEntry, compare?: DetailItemEntry}>} */
const zipped = [];
for (const entries of groupedByKey.values()) {
const baseItems = entries.filter(entry => entry.kind === 'base');
const compareItems = entries.filter(entry => entry.kind === 'compare');
if (baseItems.length > 1 || compareItems.length > 1) {
// The key is not actually unique, just treat all as added/removed.
for (const entry of entries) {
zipped.push({[entry.kind]: entry});
}
continue;
}
zipped.push({base: baseItems[0], compare: compareItems[0]});
}
return zipped;
} | @param {Array<Record<string, any>>} baseItems
@param {Array<Record<string, any>>} compareItems
@return {Array<{base?: DetailItemEntry, compare?: DetailItemEntry}>} | zipBaseAndCompareItems ( baseItems , compareItems ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/audit-diff-finder.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/audit-diff-finder.js | Apache-2.0 |
function findAuditDetailItemsDiffs(auditId, baseItems, compareItems, headings) {
/** @type {Array<LHCI.AuditDiff>} */
const diffs = [];
for (const {base, compare} of zipBaseAndCompareItems(baseItems, compareItems)) {
if (base && compare) {
diffs.push(...findAuditDetailItemKeyDiffs(auditId, base, compare, headings));
} else if (compare) {
diffs.push({type: 'itemAddition', auditId, compareItemIndex: compare.index});
} else if (base) {
diffs.push({type: 'itemRemoval', auditId, baseItemIndex: base.index});
} else {
throw new Error('Impossible');
}
}
return diffs;
} | @param {string} auditId
@param {Array<Record<string, any>>} baseItems
@param {Array<Record<string, any>>} compareItems
@param {Array<{key: string | null}>} headings
@return {Array<LHCI.AuditDiff>} | findAuditDetailItemsDiffs ( auditId , baseItems , compareItems , headings ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/audit-diff-finder.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/audit-diff-finder.js | Apache-2.0 |
function normalizeDetails(audit) {
if (!audit.details) return {items: [], headings: []};
return {items: audit.details.items || [], headings: audit.details.headings || []};
} | @param {LH.AuditResult} audit
@return {Required<Pick<Required<LH.AuditResult>['details'],'items'|'headings'>>} | normalizeDetails ( audit ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/audit-diff-finder.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/audit-diff-finder.js | Apache-2.0 |
function merge(v1, v2) {
if (Array.isArray(v1)) {
if (!Array.isArray(v2)) return v2;
for (let i = 0; i < Math.max(v1.length, v2.length); i++) {
v1[i] = i < v2.length ? merge(v1[i], v2[i]) : v1[i];
}
return v1;
} else if (typeof v1 === 'object' && v1 !== null) {
if (typeof v2 !== 'object' || v2 === null) return v2;
/** @type {Record<string, *>} */
const o1 = v1;
/** @type {Record<string, *>} */
const o2 = v2;
const o1Keys = new Set(Object.keys(o1));
const o2Keys = new Set(Object.keys(o2));
for (const key of new Set([...o1Keys, ...o2Keys])) {
o1[key] = key in o2 ? merge(o1[key], o2[key]) : o1[key];
}
return v1;
} else {
return v2;
}
} | Recursively merges properties of v2 into v1. Mutates o1 in place, does not return a copy.
@template T
@param {T} v1
@param {T} v2
@return {T} | merge ( v1 , v2 ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/lodash.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/lodash.js | Apache-2.0 |
function kebabCase(s, opts) {
let kebabed = s.replace(/([a-z])([A-Z])/g, '$1-$2');
if (opts && opts.alphanumericOnly) {
kebabed = kebabed
.replace(/[^a-z0-9]+/gi, '-')
.replace(/-+/g, '-')
.replace(/(^-|-$)/g, '');
}
return kebabed.toLowerCase();
} | Converts a string from camelCase to kebab-case.
@param {string} s
@param {{alphanumericOnly?: boolean}} [opts] | kebabCase ( s , opts ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/lodash.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/lodash.js | Apache-2.0 |
function groupIntoMap(items, keyFn) {
/** @type {Map<TKey, Array<TValue>>} */
const groups = new Map();
for (const item of items) {
const key = keyFn(item);
const group = groups.get(key) || [];
group.push(item);
groups.set(key, group);
}
return groups;
} | @template TKey
@template TValue
@param {Array<TValue>} items
@param {(item: TValue) => TKey} keyFn
@return {Map<TKey, Array<TValue>>} | groupIntoMap ( items , keyFn ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/lodash.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/lodash.js | Apache-2.0 |
range(from, to, by = 1) {
/** @type {Array<number>} */
const numbers = [];
for (let i = from; i < to; i += by) {
numbers.push(i);
}
return numbers;
}, | Generates an array of numbers from `from` (inclusive) to `to` (exclusive)
@param {number} from
@param {number} to
@param {number} [by]
@return {Array<number>} | range ( from , to , by = 1 ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/lodash.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/lodash.js | Apache-2.0 |
startCase(s) {
return kebabCase(s)
.split('-')
.map(word => `${word.slice(0, 1).toUpperCase()}${word.slice(1)}`)
.join(' ');
}, | Converts a string from kebab-case or camelCase to Start Case.
@param {string} s | startCase ( s ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/lodash.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/lodash.js | Apache-2.0 |
padStart(s, length, padding = ' ') {
if (s.length >= length) return s;
return `${padding.repeat(length)}${s}`.slice(-length);
}, | @param {string} s
@param {number} length
@param {string} [padding] | padStart ( s , length , padding = ' ' ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/lodash.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/lodash.js | Apache-2.0 |
isEqual(o1, o2, depth = 0) {
// Protect against infinite loops.
if (depth > 100) return false;
// If they don't share the same type they're not equal.
if (typeof o1 !== typeof o2) return false;
// If they're not objects, use referential equality with NaN handling.
if (Number.isNaN(o1) && Number.isNaN(o2)) return true;
if (typeof o1 !== 'object') return o1 === o2;
// Try quick referential equality before perfoming deep comparisons.
if (o1 === o2) return true;
// Check for null.
if (!o1 || !o2) return false;
// At this point we know they're both truthy objects.
// Perform deep inspection on the object's properties.
if (Array.isArray(o1)) {
if (!Array.isArray(o2)) return false;
return o1.every((v, i) => this.isEqual(v, o2[i])) && o1.length === o2.length;
}
const o1Keys = Object.keys(o1).sort();
const o2Keys = Object.keys(o2).sort();
const allChildrenEqual = o1Keys.every(k => this.isEqual(o1[k], o2[k], depth + 1));
return allChildrenEqual && this.isEqual(o1Keys, o2Keys);
}, | @param {any} o1
@param {any} o2
@param {number} [depth]
@return {boolean} | isEqual ( o1 , o2 , depth = 0 ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/lodash.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/lodash.js | Apache-2.0 |
cloneDeep(o) {
return JSON.parse(JSON.stringify(o));
}, | Deep clones an object via JSON.parse/JSON.stringify.
@template T
@param {T} o
@return {T} | cloneDeep ( o ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/lodash.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/lodash.js | Apache-2.0 |
uniqBy(items, keyFn) {
/** @type {Set<TKey>} */
const seen = new Set();
/** @type {Array<TArr>} */
const out = [];
for (const item of items) {
const key = keyFn(item);
if (seen.has(key)) continue;
seen.add(key);
out.push(item);
}
return out;
}, | Filters items by referential uniqueness of the value returned by keyFn.
Unique items are guaranteed to be in the same order of the original array.
@template TArr
@template TKey
@param {Array<TArr>} items
@param {(item: TArr) => TKey} keyFn
@return {Array<TArr>} | uniqBy ( items , keyFn ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/lodash.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/lodash.js | Apache-2.0 |
groupBy(items, keyFn) {
return [...groupIntoMap(items, keyFn).values()];
}, | @template T
@param {Array<T>} items
@param {(item: T) => any} keyFn
@return {Array<Array<T>>} | groupBy ( items , keyFn ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/lodash.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/lodash.js | Apache-2.0 |
maxBy(items, keyFn) {
let maxItem = undefined;
let maxValue = -Infinity;
for (const item of items) {
const value = keyFn(item);
if (value > maxValue) {
maxItem = item;
maxValue = value;
}
}
return maxItem;
}, | @template TArr
@param {Array<TArr>} items
@param {(o: TArr) => number} keyFn | maxBy ( items , keyFn ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/lodash.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/lodash.js | Apache-2.0 |
pick(object, propertiesToPick) {
/** @type {Partial<T>} */
const out = {};
for (const [key_, value] of Object.entries(object)) {
const key = /** @type {keyof T} */ (key_);
if (!propertiesToPick.includes(key)) continue;
out[key] = value;
}
return out;
}, | @template {Object} T
@param {T} object
@param {Array<keyof T>} propertiesToPick
@return {Partial<T>} | pick ( object , propertiesToPick ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/lodash.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/lodash.js | Apache-2.0 |
omit(object, propertiesToDrop, options = {}) {
/** @type {Partial<T>} */
const out = {};
for (const [key_, value] of Object.entries(object)) {
const key = /** @type {keyof T} */ (key_);
if (propertiesToDrop.includes(key)) continue;
if (options.dropUndefined && value === undefined) continue;
out[key] = value;
}
return out;
}, | @template {Object} T
@param {T} object
@param {Array<keyof T>} propertiesToDrop
@param {{dropUndefined?: boolean}} [options]
@return {Partial<T>} | omit ( object , propertiesToDrop , options = { } ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/lodash.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/lodash.js | Apache-2.0 |
function getMedianSortValue(lhr, medianFcp, medianInteractive) {
const distanceFcp = medianFcp - getAuditValue(lhr, 'first-contentful-paint');
const distanceInteractive = medianInteractive - getAuditValue(lhr, 'interactive');
return distanceFcp * distanceFcp + distanceInteractive * distanceInteractive;
} | @param {LH.Result} lhr
@param {number} medianFcp
@param {number} medianInteractive | getMedianSortValue ( lhr , medianFcp , medianInteractive ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/representative-runs.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/representative-runs.js | Apache-2.0 |
function computeRepresentativeRuns(runsByUrl) {
/** @type {Array<T>} */
const representativeRuns = [];
for (const runs of runsByUrl) {
if (!runs.length) continue;
const sortedByFcp = runs
.slice()
.sort(
(a, b) =>
getAuditValue(a[1], 'first-contentful-paint') -
getAuditValue(b[1], 'first-contentful-paint')
);
const medianFcp = getAuditValue(
sortedByFcp[Math.floor(runs.length / 2)][1],
'first-contentful-paint'
);
const sortedByInteractive = runs
.slice()
.sort((a, b) => getAuditValue(a[1], 'interactive') - getAuditValue(b[1], 'interactive'));
const medianInteractive = getAuditValue(
sortedByInteractive[Math.floor(runs.length / 2)][1],
'interactive'
);
const sortedByProximityToMedian = runs
.slice()
.sort(
(a, b) =>
getMedianSortValue(a[1], medianFcp, medianInteractive) -
getMedianSortValue(b[1], medianFcp, medianInteractive)
);
representativeRuns.push(sortedByProximityToMedian[0][0]);
}
return representativeRuns;
} | @template T
@param {Array<Array<[T, LH.Result]>>} runsByUrl
@return {Array<T>} | computeRepresentativeRuns ( runsByUrl ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/representative-runs.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/representative-runs.js | Apache-2.0 |
constructor(options) {
this._options = options || {};
} | @param {{psiApiKey?: string, psiApiEndpoint?: string}} [options] | constructor ( options ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/psi-runner.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/psi-runner.js | Apache-2.0 |
async run(url, options) {
options = {...this._options, ...options};
const apiKey = options.psiApiKey;
if (!apiKey) throw new Error('PSI API key must be provided to use the PSI runner');
const client = new PsiClient({apiKey, endpointURL: options.psiApiEndpoint});
return JSON.stringify(
await client.run(url, {strategy: options.psiStrategy, categories: options.psiCategories})
);
} | @param {string} url
@param {{psiApiKey?: string, psiApiEndpoint?: string, psiStrategy?: 'mobile'|'desktop', psiCategories?: Array<'performance' | 'accessibility' | 'best-practices' | 'seo'>}} [options]
@return {Promise<string>} | run ( url , options ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/psi-runner.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/psi-runner.js | Apache-2.0 |
function recursivelyReplaceDotInKeyName(object) {
if (typeof object !== 'object' || !object) return;
for (const [key, value] of Object.entries(object)) {
recursivelyReplaceDotInKeyName(value);
if (!key.includes('.')) continue;
delete object[key];
object[key.replace(/\./g, ':')] = value;
}
} | Yargs will treat any key with a `.` in the name as a specifier for an object subpath.
This isn't the behavior we want when using the `config` file, just the CLI arguments, so we rename.
Anything that has `.` to `:` and avoid using any keys with `.` in the name throughout LHCI.
This fixes a bug where assertions used `.` in the name but now optionally use `:` as well.
@see https://github.com/GoogleChrome/lighthouse-ci/issues/64
@param {any} object | recursivelyReplaceDotInKeyName ( object ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/lighthouserc.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/lighthouserc.js | Apache-2.0 |
function loadAndParseRcFile(pathToRcFile) {
return convertRcFileToYargsOptions(loadRcFile(pathToRcFile), pathToRcFile);
} | @param {string} pathToRcFile
@return {LHCI.YargsOptions} | loadAndParseRcFile ( pathToRcFile ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/lighthouserc.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/lighthouserc.js | Apache-2.0 |
function loadRcFile(pathToRcFile) {
// Load file
const contents = fs.readFileSync(pathToRcFile, 'utf8');
const rc = parseFileContentToJSON(pathToRcFile, contents);
// Convert all `.` in key names to `:`
recursivelyReplaceDotInKeyName(rc);
return rc;
} | Load file, parse and convert all `.` in key names to `:`
@param {string} pathToRcFile
@return {LHCI.LighthouseRc} | loadRcFile ( pathToRcFile ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/lighthouserc.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/lighthouserc.js | Apache-2.0 |
function parseFileContentToJSON(pathToRcFile, contents) {
// Check if file path ends in .js
if (JS_FILE_EXTENSION_REGEX.test(pathToRcFile)) {
return require(pathToRcFile);
}
// Check if file path ends in .yaml or .yml
if (YAML_FILE_EXTENSION_REGEX.test(pathToRcFile)) {
// Parse yaml content to JSON
return yaml.safeLoad(contents);
}
// Fallback to JSON parsing
return JSON.parse(contents);
} | Parse file content to JSON.
@param {string} pathToRcFile
@param {string} contents
@return {LHCI.LighthouseRc} | parseFileContentToJSON ( pathToRcFile , contents ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/lighthouserc.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/lighthouserc.js | Apache-2.0 |
function findRcFileInDirectory(dir) {
for (const file of RC_FILE_NAMES) {
if (fs.existsSync(path.join(dir, file))) return path.join(dir, file);
}
} | @param {string} dir
@return {string|undefined} | findRcFileInDirectory ( dir ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/lighthouserc.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/lighthouserc.js | Apache-2.0 |
function findRcFile(startDir, opts = {}) {
const {recursive = false} = opts;
let lastDir = '';
let dir = startDir || process.cwd();
if (!recursive) return findRcFileInDirectory(dir);
while (lastDir.length !== dir.length) {
const rcFile = findRcFileInDirectory(dir);
if (rcFile) return rcFile;
lastDir = dir;
dir = path.join(dir, '..');
}
} | @param {string} [startDir]
@param {{recursive?: boolean}} [opts]
@return {string|undefined} | findRcFile ( startDir , opts = { } ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/lighthouserc.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/lighthouserc.js | Apache-2.0 |
function hasOptedOutOfRcDetection(argv = process.argv, env = process.env) {
if (env.LHCI_NO_LIGHTHOUSERC) return true;
if (argv.some(arg => /no-?lighthouserc/i.test(arg))) return true;
return false;
} | @param {string[]} [argv]
@param {Record<string, string|undefined>} [env]
@return {boolean} | hasOptedOutOfRcDetection ( argv = process . argv , env = process . env ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/lighthouserc.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/lighthouserc.js | Apache-2.0 |
function convertRcFileToYargsOptions(rcFile, pathToRcFile) {
const ci = flattenRcToConfig(rcFile);
/** @type {LHCI.YargsOptions} */
let merged = {...ci.wizard, ...ci.assert, ...ci.collect, ...ci.upload, ...ci.server};
if (ci.extends) {
const extendedRcFilePath = path.resolve(path.dirname(pathToRcFile), ci.extends);
const extensionBase = loadAndParseRcFile(extendedRcFilePath);
merged = _.merge(extensionBase, merged);
}
return merged;
} | @param {LHCI.LighthouseRc} rcFile
@param {string} pathToRcFile
@return {LHCI.YargsOptions} | convertRcFileToYargsOptions ( rcFile , pathToRcFile ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/lighthouserc.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/lighthouserc.js | Apache-2.0 |
function resolveRcFilePath(pathToRcFile) {
if (typeof pathToRcFile === 'string') return path.resolve(process.cwd(), pathToRcFile);
return hasOptedOutOfRcDetection() ? undefined : findRcFile();
} | @param {string|undefined} pathToRcFile
@return {string|undefined} | resolveRcFilePath ( pathToRcFile ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/lighthouserc.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/lighthouserc.js | Apache-2.0 |
function isArrayOfUnknownObjects(arr) {
return Array.isArray(arr) && arr.every(isObjectOfUnknownProperties);
} | @param {unknown} arr
@return {arr is Array<Record<string, unknown>>} | isArrayOfUnknownObjects ( arr ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/budget.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/budget.js | Apache-2.0 |
function isObjectOfUnknownProperties(val) {
return typeof val === 'object' && val !== null && !Array.isArray(val);
} | @param {unknown} val
@return {val is Record<string, unknown>} | isObjectOfUnknownProperties ( val ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/budget.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/budget.js | Apache-2.0 |
function isNumber(val) {
return typeof val === 'number' && !isNaN(val);
} | Returns whether `val` is numeric. Will not coerce to a number. `NaN` will
return false, however ±Infinity will return true.
@param {unknown} val
@return {val is number} | isNumber ( val ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/budget.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/budget.js | Apache-2.0 |
static assertNoExcessProperties(obj, objectName) {
const invalidKeys = Object.keys(obj);
if (invalidKeys.length > 0) {
const keys = invalidKeys.join(', ');
throw new Error(`${objectName} has unrecognized properties: [${keys}]`);
}
} | Asserts that obj has no own properties, throwing a nice error message if it does.
`objectName` is included for nicer logging.
@param {Record<string, unknown>} obj
@param {string} objectName | assertNoExcessProperties ( obj , objectName ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/budget.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/budget.js | Apache-2.0 |
static assertNoDuplicateStrings(strings, arrayName) {
const foundStrings = new Set();
for (const string of strings) {
if (foundStrings.has(string)) {
throw new Error(`${arrayName} has duplicate entry of type '${string}'`);
}
foundStrings.add(string);
}
} | Asserts that `strings` has no duplicate strings in it, throwing an error if
it does. `arrayName` is included for nicer logging.
@param {Array<string>} strings
@param {string} arrayName | assertNoDuplicateStrings ( strings , arrayName ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/budget.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/budget.js | Apache-2.0 |
static throwInvalidPathError(path, error) {
throw new Error(
`Invalid path ${path}. ${error}\n` +
`'Path' should be specified using the 'robots.txt' format.\n` +
`Learn more about the 'robots.txt' format here:\n` +
`https://developers.google.com/search/reference/robots_txt#url-matching-based-on-path-values`
);
} | @param {unknown} path
@param {string} error | throwInvalidPathError ( path , error ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/budget.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/budget.js | Apache-2.0 |
function splitMarkdownLink(text) {
/** @type {Array<{isLink: true, text: string, linkHref: string}|{isLink: false, text: string}>} */
const segments = [];
const parts = text.split(/\[([^\]]+?)\]\((https?:\/\/.*?)\)/g);
while (parts.length) {
// Shift off the same number of elements as the pre-split and capture groups.
const [preambleText, linkText, linkHref] = parts.splice(0, 3);
if (preambleText) {
// Skip empty text as it's an artifact of splitting, not meaningful.
segments.push({
isLink: false,
text: preambleText,
});
}
// Append link if there are any.
if (linkText && linkHref) {
segments.push({
isLink: true,
text: linkText,
linkHref,
});
}
}
return segments;
}
module.exports = {splitMarkdownLink}; | @see https://github.com/GoogleChrome/lighthouse/blob/2ff07d29a3e12a75cc844427c567330eb84d4249/lighthouse-core/report/html/renderer/util.js#L320-L347
Split a string on markdown links (e.g. [some link](https://...)) into
segments of plain text that weren't part of a link (marked as
`isLink === false`), and segments with text content and a URL that did make
up a link (marked as `isLink === true`).
@param {string} text
@return {Array<{isLink: true, text: string, linkHref: string}|{isLink: false, text: string}>} | splitMarkdownLink ( text ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/markdown.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/markdown.js | Apache-2.0 |
const isFiniteNumber = x => typeof x === 'number' && Number.isFinite(x); | @param {any} x
@return {x is number} | isFiniteNumber | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/assertions.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/assertions.js | Apache-2.0 |
function normalizeAssertion(assertion) {
if (!assertion) return ['off', {}];
if (typeof assertion === 'string') return [assertion, {}];
return assertion;
} | @param {LHCI.AssertCommand.AssertionFailureLevel | [LHCI.AssertCommand.AssertionFailureLevel, LHCI.AssertCommand.AssertionOptions] | undefined} assertion
@return {[LHCI.AssertCommand.AssertionFailureLevel, LHCI.AssertCommand.AssertionOptions]} | normalizeAssertion ( assertion ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/assertions.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/assertions.js | Apache-2.0 |
function getValueForAggregationMethod(values, aggregationMethod, assertionType) {
if (aggregationMethod === 'median') {
const medianIndex = Math.floor((values.length - 1) / 2);
const sorted = values.slice().sort((a, b) => a - b);
if (values.length % 2 === 1) return sorted[medianIndex];
return (sorted[medianIndex] + sorted[medianIndex + 1]) / 2;
}
const useMin =
(aggregationMethod === 'optimistic' && assertionType.startsWith('max')) ||
(aggregationMethod === 'pessimistic' && assertionType.startsWith('min'));
return useMin ? Math.min(...values) : Math.max(...values);
} | @param {number[]} values
@param {LHCI.AssertCommand.AssertionAggregationMethod} aggregationMethod
@param {LHCI.AssertResults.AssertionType} assertionType
@return {number} | getValueForAggregationMethod ( values , aggregationMethod , assertionType ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/assertions.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/assertions.js | Apache-2.0 |
function getAssertionResultsForBudgetRow(key, actual, expected) {
return getAssertionResult(
[{score: 0, numericValue: actual}],
'pessimistic',
'maxNumericValue',
expected
).map(assertion => {
return {...assertion, auditProperty: key};
});
} | @param {string} key
@param {number} actual
@param {number} expected
@return {LHCI.AssertResults.AssertionResultNoURL[]} | getAssertionResultsForBudgetRow ( key , actual , expected ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/assertions.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/assertions.js | Apache-2.0 |
function getCategoryAssertionResults(auditProperty, assertionOptions, lhrs) {
if (auditProperty.length !== 1) {
throw new Error(`Invalid resource-summary assertion "${auditProperty.join('.')}"`);
}
const categoryId = auditProperty[0];
/** @type {Array<LH.AuditResult|undefined>} */
const psuedoAudits = lhrs.map(lhr => {
const category = lhr.categories[categoryId];
if (!category) return undefined;
return {
score: category.score,
};
});
return getStandardAssertionResults(psuedoAudits, assertionOptions).map(result => ({
...result,
auditProperty: categoryId,
}));
} | Gets the assertion results for a particular audit. This method delegates some of the unique
handling for budgets and auditProperty assertions as necessary.
@param {Array<string>} auditProperty
@param {LHCI.AssertCommand.AssertionOptions} assertionOptions
@param {Array<LH.Result>} lhrs
@return {LHCI.AssertResults.AssertionResultNoURL[]} | getCategoryAssertionResults ( auditProperty , assertionOptions , lhrs ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/assertions.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/assertions.js | Apache-2.0 |
function doesLHRMatchPattern(pattern, lhr) {
return new RegExp(pattern).test(lhr.finalUrl);
} | @param {string} pattern
@param {LH.Result} lhr
@return {boolean} | doesLHRMatchPattern ( pattern , lhr ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/assertions.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/assertions.js | Apache-2.0 |
function getAllAssertionResultsForUrl(baseOptions, unfilteredLhrs) {
const {assertions, auditsToAssert, medianLhrs, lhrs, url, aggregationMethod} =
resolveAssertionOptionsAndLhrs(baseOptions, unfilteredLhrs);
// If we don't have any data, just return early.
if (!lhrs.length) return [];
/** @type {LHCI.AssertResults.AssertionResult[]} */
const results = [];
for (const auditToAssert of auditsToAssert) {
const {assertionKey, auditId, auditProperty} = auditToAssert;
const [level, assertionOptions] = normalizeAssertion(assertions[assertionKey]);
if (level === 'off') continue;
const options = {aggregationMethod, ...assertionOptions};
const lhrsToUseForAudit = options.aggregationMethod === 'median-run' ? medianLhrs : lhrs;
const auditResults = lhrsToUseForAudit.map(lhr => lhr.audits[auditId]);
const assertionResults = getAssertionResultsForAudit(
auditId,
auditProperty,
auditResults,
options,
lhrs
);
for (const result of assertionResults) {
const finalResult = {...result, auditId, level, url};
if (auditToAssert.auditTitle) finalResult.auditTitle = auditToAssert.auditTitle;
if (auditToAssert.auditDocumentationLink) {
finalResult.auditDocumentationLink = auditToAssert.auditDocumentationLink;
}
results.push(finalResult);
}
}
return results;
} | @param {LHCI.AssertCommand.BaseOptions} baseOptions
@param {LH.Result[]} unfilteredLhrs
@return {LHCI.AssertResults.AssertionResult[]} | getAllAssertionResultsForUrl ( baseOptions , unfilteredLhrs ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/assertions.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/assertions.js | Apache-2.0 |
function getAllAssertionResults(options, lhrs) {
const groupedByURL = _.groupBy(lhrs, lhr => lhr.finalUrl);
/** @type {LHCI.AssertCommand.BaseOptions[]} */
let arrayOfOptions = [options];
if (options.assertMatrix) {
if (options.assertions || options.preset || options.budgetsFile || options.aggregationMethod) {
throw new Error('Cannot use assertMatrix with other options');
}
arrayOfOptions = options.assertMatrix;
}
/** @type {LHCI.AssertResults.AssertionResult[]} */
const results = [];
for (const lhrSet of groupedByURL) {
for (const baseOptions of arrayOfOptions) {
results.push(...getAllAssertionResultsForUrl(baseOptions, lhrSet));
}
}
if (options.includePassedAssertions) return results;
return results.filter(result => !result.passed);
} | Computes all assertion results for the given LHR-set and options.
@param {LHCI.AssertCommand.Options} options
@param {LH.Result[]} lhrs
@return {LHCI.AssertResults.AssertionResult[]} | getAllAssertionResults ( options , lhrs ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/assertions.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/assertions.js | Apache-2.0 |
constructor(options) {
this._rootURL = options.rootURL;
/** @type {Record<string, string>} */
this._extraHeaders = options.extraHeaders || {};
this._fetch = options.fetch || fetch;
this._URL = options.URL || URL;
if (options.basicAuth && options.basicAuth.password) {
const {username = ApiClient.DEFAULT_BASIC_AUTH_USERNAME, password} = options.basicAuth;
this._extraHeaders.Authorization = `Basic ${btoa(`${username}:${password}`)}`;
}
/** @type {LHCI.ServerCommand.StorageMethod} */
const typecheck = this; // eslint-disable-line no-unused-vars
} | @param {{rootURL: string, fetch?: import('isomorphic-fetch'), URL?: typeof URL, extraHeaders?: Record<string, string>, basicAuth?: LHCI.ServerCommand.Options['basicAuth']}} options | constructor ( options ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/api-client.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/api-client.js | Apache-2.0 |
_convert404ToUndefined(returnValuePromise) {
return returnValuePromise.catch(err => {
if ('status' in err && err.status === 404) return undefined;
throw err;
});
} | @param {Promise<any>} returnValuePromise
@return {Promise<any>} | _convert404ToUndefined ( returnValuePromise ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/api-client.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/api-client.js | Apache-2.0 |
async _get(rawUrl, query) {
const url = this._normalizeURL(rawUrl);
if (query) {
for (const [key, value] of Object.entries(query)) {
if (value === undefined) continue;
url.searchParams.append(key, value.toString());
}
}
const response = await this._fetch(url.href, {headers: {...this._extraHeaders}});
return this._convertFetchResponseToReturnValue(response);
} | @template {string} T
@param {string} rawUrl
@param {Partial<Record<T, string|number|boolean|undefined>>} [query]
@return {Promise<any>} | _get ( rawUrl , query ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/api-client.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/api-client.js | Apache-2.0 |
async _post(url, body) {
return this._fetchWithRequestBody('POST', url, body);
} | @param {string} url
@param {*} body
@return {Promise<any>} | _post ( url , body ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/api-client.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/api-client.js | Apache-2.0 |
async _delete(rawUrl) {
const headers = {...this._extraHeaders};
const response = await this._fetch(this._normalizeURL(rawUrl).href, {
method: 'DELETE',
headers,
});
return this._convertFetchResponseToReturnValue(response);
} | @param {string} rawUrl
@return {Promise<void>} | _delete ( rawUrl ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/api-client.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/api-client.js | Apache-2.0 |
async getProjectToken(project) {
return (await this._get(`/v1/projects/${project.id}/token`)).token;
} | @param {LHCI.ServerCommand.Project} project
@return {Promise<string>} | getProjectToken ( project ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/api-client.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/api-client.js | Apache-2.0 |
async updateProject(projectUpdates) {
return this._put(`/v1/projects/${projectUpdates.id}`, projectUpdates);
} | @param {Pick<LHCI.ServerCommand.Project, 'id'|'baseBranch'|'externalUrl'|'name'>} projectUpdates
@return {Promise<void>} | updateProject ( projectUpdates ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/api-client.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/api-client.js | Apache-2.0 |
async getBuilds(projectId, options = {}) {
return this._get(`/v1/projects/${projectId}/builds`, options);
} | @param {string} projectId
@param {LHCI.ServerCommand.GetBuildsOptions} [options]
@return {Promise<LHCI.ServerCommand.Build[]>} | getBuilds ( projectId , options = { } ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/api-client.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/api-client.js | Apache-2.0 |
async createBuild(unsavedBuild) {
return this._post(`/v1/projects/${unsavedBuild.projectId}/builds`, unsavedBuild);
} | @param {StrictOmit<LHCI.ServerCommand.Build, 'id'>} unsavedBuild
@return {Promise<LHCI.ServerCommand.Build>} | createBuild ( unsavedBuild ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/api-client.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/api-client.js | Apache-2.0 |
async sealBuild(projectId, buildId) {
return this._put(`/v1/projects/${projectId}/builds/${buildId}/lifecycle`, 'sealed');
} | @param {string} projectId
@param {string} buildId
@return {Promise<void>} | sealBuild ( projectId , buildId ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/api-client.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/api-client.js | Apache-2.0 |
async findBuildById(projectId, buildId) {
return this._convert404ToUndefined(this._get(`/v1/projects/${projectId}/builds/${buildId}`));
} | @param {string} projectId
@param {string} buildId
@return {Promise<LHCI.ServerCommand.Build | undefined>} | findBuildById ( projectId , buildId ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/api-client.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/api-client.js | Apache-2.0 |
async getRuns(projectId, buildId, options = {}) {
return this._get(`/v1/projects/${projectId}/builds/${buildId}/runs`, options);
} | @param {string} projectId
@param {string} buildId
@param {LHCI.ServerCommand.GetRunsOptions} [options]
@return {Promise<LHCI.ServerCommand.Run[]>} | getRuns ( projectId , buildId , options = { } ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/api-client.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/api-client.js | Apache-2.0 |
async getUrls(projectId, buildId) {
if (buildId) return this._get(`/v1/projects/${projectId}/builds/${buildId}/urls`);
return this._get(`/v1/projects/${projectId}/urls`);
} | @param {string} projectId
@param {string} [buildId]
@return {Promise<{url: string}[]>} | getUrls ( projectId , buildId ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/api-client.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/api-client.js | Apache-2.0 |
async createRun(run) {
return this._post(`/v1/projects/${run.projectId}/builds/${run.buildId}/runs`, run);
} | @param {StrictOmit<LHCI.ServerCommand.Run, 'id'>} run
@return {Promise<LHCI.ServerCommand.Run>} | createRun ( run ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/api-client.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/api-client.js | Apache-2.0 |
async getStatistics(projectId, buildId) {
return this._get(`/v1/projects/${projectId}/builds/${buildId}/statistics`);
} | @param {string} projectId
@param {string} buildId
@return {Promise<Array<LHCI.ServerCommand.Statistic>>} | getStatistics ( projectId , buildId ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/api-client.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/api-client.js | Apache-2.0 |
function loadSavedLHRs(directoryOrPath) {
directoryOrPath = directoryOrPath || LHCI_DIR;
if (directoryOrPath === LHCI_DIR) {
ensureDirectoryExists();
}
if (fs.lstatSync(directoryOrPath).isFile()) {
return [fs.readFileSync(directoryOrPath, 'utf8')];
}
/** @type {string[]} */
const lhrs = [];
for (const file of fs.readdirSync(directoryOrPath)) {
if (!LHR_REGEX.test(file)) continue;
const filePath = path.join(LHCI_DIR, file);
lhrs.push(fs.readFileSync(filePath, 'utf8'));
}
return lhrs;
} | @param {string} [directoryOrPath]
@return {string[]} | loadSavedLHRs ( directoryOrPath ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/saved-reports.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/saved-reports.js | Apache-2.0 |
async function getHTMLReportForLHR(lhr) {
const {generateReport} = await import('lighthouse');
// @ts-expect-error TODO: Import exact types from Lighthouse.
return generateReport(lhr);
} | @param {LH.Result} lhr
@return {Promise<string>} | getHTMLReportForLHR ( lhr ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/saved-reports.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/saved-reports.js | Apache-2.0 |
function writeUrlMapToFile(targetUrlMap) {
/** @type {Record<string, string>} */
const urlMapAsObject = {};
for (const [testedUrl, link] of targetUrlMap.entries()) {
urlMapAsObject[testedUrl] = link;
}
fs.writeFileSync(URL_LINK_MAP_PATH, JSON.stringify(urlMapAsObject, null, 2));
} | @param {Map<string, string>} targetUrlMap | writeUrlMapToFile ( targetUrlMap ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/saved-reports.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/saved-reports.js | Apache-2.0 |
function replaceUrlPatterns(url, sedLikeReplacementPatterns) {
let replaced = url;
for (const pattern of sedLikeReplacementPatterns) {
const match = pattern.match(/^s(.)(.*)\1(.*)\1([gim]*)$/);
if (!match) throw new Error(`Invalid URL replacement pattern "${pattern}"`);
const [needle, replacement, flags] = match.slice(2);
const regex = new RegExp(needle, flags);
replaced = replaced.replace(regex, replacement);
}
return replaced;
}
/**
* @param {Map<string, string>} targetUrlMap
*/
function writeUrlMapToFile(targetUrlMap) {
/** @type {Record<string, string>} */
const urlMapAsObject = {};
for (const [testedUrl, link] of targetUrlMap.entries()) {
urlMapAsObject[testedUrl] = link;
}
fs.writeFileSync(URL_LINK_MAP_PATH, JSON.stringify(urlMapAsObject, null, 2));
}
module.exports = {
getHTMLReportForLHR,
loadSavedLHRs,
saveLHR,
clearSavedReportsAndLHRs,
loadAssertionResults,
saveAssertionResults,
getSavedReportsDirectory,
replaceUrlPatterns,
writeUrlMapToFile,
}; | @param {string} url
@param {string[]} sedLikeReplacementPatterns | replaceUrlPatterns ( url , sedLikeReplacementPatterns ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/saved-reports.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/saved-reports.js | Apache-2.0 |
constructor(options) {
this._apiKey = options.apiKey;
this._endpointURL = options.endpointURL || PSI_URL;
this._fetch = options.fetch || fetch;
this._URL = options.URL || URL;
} | @param {{apiKey: string, endpointURL?: string, fetch?: import('isomorphic-fetch'), URL?: typeof import('url').URL, extraHeaders?: Record<string, string>, basicAuth?: LHCI.ServerCommand.Options['basicAuth']}} options | constructor ( options ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/psi-client.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/psi-client.js | Apache-2.0 |
async run(urlToTest, options = {}) {
const {
strategy = 'mobile',
locale = 'en_US',
categories = ['performance', 'accessibility', 'best-practices', 'seo'],
} = options;
const url = new this._URL(this._endpointURL);
url.searchParams.set('url', urlToTest);
url.searchParams.set('locale', locale);
url.searchParams.set('strategy', strategy);
url.searchParams.set('key', this._apiKey);
categories.forEach(category => url.searchParams.append('category', category));
const response = await this._fetch(url.href);
const body = await response.json();
if (body.lighthouseResult) return body.lighthouseResult;
if (body.error) {
const {code = 'UNKNOWN', message = 'Unknown reason'} = body.error;
const error = new Error(`PSI Failed (${code}): ${message}`);
// @ts-ignore - append information to the error
error.originalError = body.error;
throw error;
}
throw new Error(`Unexpected PSI response: ${JSON.stringify(body)}`);
} | @param {string} urlToTest
@param {{strategy?: 'mobile'|'desktop', locale?: string, categories?: Array<'performance' | 'accessibility' | 'best-practices' | 'seo'>}} [options]
@return {Promise<LH.Result>} | run ( urlToTest , options = { } ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/psi-client.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/psi-client.js | Apache-2.0 |
function runCommandsUntilFirstSuccess(commands) {
/** @type {import('child_process').SpawnSyncReturns<string>|undefined} */
let result;
for (const [command, args] of commands) {
result = childProcess.spawnSync(command, args, {encoding: 'utf8'});
if (result.status === 0) break;
}
if (!result) throw new Error('Must specify at least one command');
return result;
} | @param {Array<[string, ReadonlyArray<string>]>} commands
@return {import('child_process').SpawnSyncReturns<string>} | runCommandsUntilFirstSuccess ( commands ) | javascript | GoogleChrome/lighthouse-ci | packages/utils/src/build-context.js | https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/utils/src/build-context.js | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.