Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

misc: use codemod for optional chaining #13503

Merged
merged 9 commits into from
Dec 20, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion flow-report/src/common.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ const FlowStepThumbnail: FunctionComponent<{
}

let thumbnail;
if (frames && frames.length) {
if (frames?.length) {
thumbnail = frames[frames.length - 1].data;
if (lhr.gatherMode === 'timespan') {
return <FlowStepAnimatedThumbnail frames={frames} width={width} height={height} />;
Expand Down
2 changes: 1 addition & 1 deletion flow-report/src/sidebar/flow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export const SidebarFlow: FunctionComponent = () => {
mode={lhr.gatherMode}
href={`#index=${index}`}
label={name}
isCurrent={index === (hashState && hashState.index)}
isCurrent={index === hashState?.index}
/>
</>;
})
Expand Down
3 changes: 1 addition & 2 deletions flow-report/src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,7 @@ function getScreenDimensions(reportResult: LH.Result) {
function getFullPageScreenshot(reportResult: LH.Result) {
const fullPageScreenshotAudit = reportResult.audits['full-page-screenshot'];
const fullPageScreenshot =
fullPageScreenshotAudit &&
fullPageScreenshotAudit.details &&
fullPageScreenshotAudit?.details &&
fullPageScreenshotAudit.details.type === 'full-page-screenshot' &&
fullPageScreenshotAudit.details;

Expand Down
2 changes: 1 addition & 1 deletion lighthouse-cli/run.js
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ async function runLighthouse(url, flags, config) {
// Runtime errors indicate something was *very* wrong with the page result.
// We don't want the user to have to parse the report to figure it out, so we'll still exit
// with an error code after we saved the results.
if (runnerResult && runnerResult.lhr.runtimeError) {
if (runnerResult?.lhr.runtimeError) {
const {runtimeError} = runnerResult.lhr;
return printErrorAndExit({
name: 'LHError',
Expand Down
2 changes: 1 addition & 1 deletion lighthouse-cli/test/smokehouse/lighthouse-runners/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ async function internalRun(url, tmpPath, configJson, options) {

// There should either be both an error exitCode and a lhr.runtimeError or neither.
if (Boolean(exitCode) !== Boolean(lhr.runtimeError)) {
const runtimeErrorCode = lhr.runtimeError && lhr.runtimeError.code;
const runtimeErrorCode = lhr.runtimeError?.code;
throw new ChildProcessError(`Lighthouse did not exit with an error correctly, exiting with ${exitCode} but with runtimeError '${runtimeErrorCode}'`, // eslint-disable-line max-len
localConsole.getLog());
}
Expand Down
2 changes: 1 addition & 1 deletion lighthouse-cli/test/smokehouse/report-assert.js
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ function makeComparison(name, actualResult, expectedResult) {
*/
function pruneExpectations(localConsole, lhr, expected, reportOptions) {
const isFraggleRock = lhr.configSettings.channel === 'fraggle-rock-cli';
const isBundled = reportOptions && reportOptions.isBundled;
const isBundled = reportOptions?.isBundled;

/**
* Lazily compute the Chrome version because some reports are explicitly asserting error conditions.
Expand Down
2 changes: 1 addition & 1 deletion lighthouse-cli/test/smokehouse/smokehouse.js
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ function getShardedDefinitions(testDefns, shardArg) {
// eslint-disable-next-line max-len
const errorMessage = `'shard' must be of the form 'n/d' and n and d must be positive integers with 1 ≤ n ≤ d. Got '${shardArg}'`;
const match = /^(?<shardNumber>\d+)\/(?<shardTotal>\d+)$/.exec(shardArg);
assert(match && match.groups, errorMessage);
assert(match?.groups, errorMessage);
const shardNumber = Number(match.groups.shardNumber);
const shardTotal = Number(match.groups.shardTotal);
assert(shardNumber > 0 && Number.isInteger(shardNumber), errorMessage);
Expand Down
8 changes: 4 additions & 4 deletions lighthouse-core/audits/accessibility/axe-audit.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ class AxeAudit extends Audit {
// If aXe reports an error, then bubble it up to the caller
const incomplete = artifacts.Accessibility.incomplete || [];
const incompleteResult = incomplete.find(result => result.id === this.meta.id);
if (incompleteResult && incompleteResult.error) {
if (incompleteResult?.error) {
return {
score: null,
errorMessage: `axe-core Error: ${incompleteResult.error.message || 'Unknown error'}`,
Expand All @@ -58,8 +58,8 @@ class AxeAudit extends Audit {
const violations = artifacts.Accessibility.violations || [];
const failureCases = isInformative ? violations.concat(incomplete) : violations;
const rule = failureCases.find(result => result.id === this.meta.id);
const impact = rule && rule.impact;
const tags = rule && rule.tags;
const impact = rule?.impact;
const tags = rule?.tags;

// Handle absence of aXe failure results for informative rules as 'not applicable'
// This scenario indicates that no action is required by the web property owner
Expand All @@ -73,7 +73,7 @@ class AxeAudit extends Audit {

/** @type {LH.Audit.Details.Table['items']}>} */
let items = [];
if (rule && rule.nodes) {
if (rule?.nodes) {
items = rule.nodes.map(axeNode => ({
node: {
...Audit.makeNodeItem(axeNode.node),
Expand Down
4 changes: 2 additions & 2 deletions lighthouse-core/audits/audit.js
Original file line number Diff line number Diff line change
Expand Up @@ -360,8 +360,8 @@ class Audit {

score,
scoreDisplayMode,
numericValue: numericProduct && numericProduct.numericValue,
numericUnit: numericProduct && numericProduct.numericUnit,
numericValue: numericProduct?.numericValue,
numericUnit: numericProduct?.numericUnit,

displayValue: product.displayValue,
explanation: product.explanation,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ class UnusedBytes extends Audit {
const gatherContext = artifacts.GatherContext;
const trace = artifacts.traces[Audit.DEFAULT_PASS];
const devtoolsLog = artifacts.devtoolsLogs[Audit.DEFAULT_PASS];
const settings = context && context.settings || {};
const settings = context?.settings || {};
const simulatorOptions = {
devtoolsLog,
settings,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ class DuplicatedJavascript extends ByteEfficiencyAudit {
*/
static async audit_(artifacts, networkRecords, context) {
const ignoreThresholdInBytes =
context.options && context.options.ignoreThresholdInBytes || IGNORE_THRESHOLD_IN_BYTES;
context.options?.ignoreThresholdInBytes || IGNORE_THRESHOLD_IN_BYTES;
const duplication =
await DuplicatedJavascript._getDuplicationGroupedByNodeModules(artifacts, context);
const mainDocumentRecord = NetworkAnalyzer.findOptionalMainDocument(networkRecords);
Expand Down
6 changes: 3 additions & 3 deletions lighthouse-core/audits/dobetterweb/inspector-issues.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ class IssuesPanelEntries extends Audit {
static getMixedContentRow(mixedContentIssues) {
const requestUrls = new Set();
for (const issue of mixedContentIssues) {
const requestUrl = (issue.request && issue.request.url) || issue.mainResourceURL;
const requestUrl = issue.request?.url || issue.mainResourceURL;
requestUrls.add(requestUrl);
}
return {
Expand All @@ -77,7 +77,7 @@ class IssuesPanelEntries extends Audit {
static getSameSiteCookieRow(sameSiteCookieIssues) {
const requestUrls = new Set();
for (const issue of sameSiteCookieIssues) {
const requestUrl = (issue.request && issue.request.url) || issue.cookieUrl;
const requestUrl = (issue.request?.url) || issue.cookieUrl;
if (requestUrl) {
requestUrls.add(requestUrl);
}
Expand All @@ -102,7 +102,7 @@ class IssuesPanelEntries extends Audit {
static getBlockedByResponseRow(blockedByResponseIssues) {
const requestUrls = new Set();
for (const issue of blockedByResponseIssues) {
const requestUrl = issue.request && issue.request.url;
const requestUrl = issue.request?.url;
if (requestUrl) {
requestUrls.add(requestUrl);
}
Expand Down
2 changes: 1 addition & 1 deletion lighthouse-core/audits/dobetterweb/uses-http2.js
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ class UsesHTTP2Audit extends Audit {
};
}

const settings = context && context.settings || {};
const settings = context?.settings || {};
const simulatorOptions = {
devtoolsLog,
settings,
Expand Down
2 changes: 1 addition & 1 deletion lighthouse-core/audits/font-display.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ class FontDisplay extends Audit {
// Find the font-display value by matching a single token, optionally surrounded by whitespace,
// followed either by a semicolon or the end of a block.
const fontDisplayMatch = declaration.match(/font-display\s*:\s*(\w+)\s*(;|\})/);
const rawFontDisplay = (fontDisplayMatch && fontDisplayMatch[1]) || '';
const rawFontDisplay = fontDisplayMatch?.[1] || '';
const hasPassingFontDisplay = passingFontDisplayRegex.test(rawFontDisplay);
const targetURLSet = hasPassingFontDisplay ? passingURLs : failingURLs;

Expand Down
2 changes: 1 addition & 1 deletion lighthouse-core/audits/installable-manifest.js
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ class InstallableManifest extends Audit {
* If there is an argument value, get it.
* We only expect a `minimum-icon-size-in-pixels` errorArg[0] for two errorIds, currently.
*/
const value0 = err.errorArguments && err.errorArguments.length && err.errorArguments[0].value;
const value0 = err.errorArguments?.length && err.errorArguments[0].value;

if (matchingString && err.errorArguments.length !== UIStringArguments.length) {
// Matching string, but have the incorrect number of arguments for the message.
Expand Down
2 changes: 1 addition & 1 deletion lighthouse-core/audits/maskable-icon.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ class MaskableIcon extends Audit {
}
const maskableIconCheck = manifestValues.allChecks.find(i => i.id === 'hasMaskableIcon');
return {
score: (maskableIconCheck && maskableIconCheck.passing) ? 1 : 0,
score: maskableIconCheck?.passing ? 1 : 0,
};
}
}
Expand Down
2 changes: 1 addition & 1 deletion lighthouse-core/audits/multi-check-audit.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ class MultiCheckAudit extends Audit {
allChecks: undefined,
};

if (result.manifestValues && result.manifestValues.allChecks) {
if (result.manifestValues?.allChecks) {
result.manifestValues.allChecks.forEach(check => {
detailsItem[check.id] = check.passing;
});
Expand Down
8 changes: 4 additions & 4 deletions lighthouse-core/audits/network-requests.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,10 @@ class NetworkRequests extends Audit {
undefined : (time - earliestStartTime) * 1000;

const results = records.map(record => {
const endTimeDeltaMs = record.lrStatistics && record.lrStatistics.endTimeDeltaMs;
const TCPMs = record.lrStatistics && record.lrStatistics.TCPMs;
const requestMs = record.lrStatistics && record.lrStatistics.requestMs;
const responseMs = record.lrStatistics && record.lrStatistics.responseMs;
const endTimeDeltaMs = record.lrStatistics?.endTimeDeltaMs;
const TCPMs = record.lrStatistics?.TCPMs;
const requestMs = record.lrStatistics?.requestMs;
const responseMs = record.lrStatistics?.responseMs;

return {
url: URL.elideDataURI(record.url),
Expand Down
2 changes: 1 addition & 1 deletion lighthouse-core/audits/preload-lcp-image.js
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ class PreloadLCPImageAudit extends Audit {
const node = modifiedNodesById.get(nodeId);
if (!node) throw new Error('Impossible - node should never be undefined');
const timings = simulationAfterChanges.nodeTimings.get(node);
const endTime = timings && timings.endTime || 0;
const endTime = timings?.endTime || 0;
maxDependencyEndTime = Math.max(maxDependencyEndTime, endTime);
}

Expand Down
2 changes: 1 addition & 1 deletion lighthouse-core/audits/themed-omnibox.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ class ThemedOmnibox extends MultiCheckAudit {
return {
failures,
manifestValues,
themeColor: (themeColorMeta && themeColorMeta.content) || null,
themeColor: themeColorMeta?.content || null,
};
}
}
Expand Down
4 changes: 2 additions & 2 deletions lighthouse-core/audits/valid-source-maps.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ class ValidSourceMaps extends Audit {
}

// Sources content errors.
if (sourceMap && sourceMap.map) {
if (sourceMap?.map) {
const sourcesContent = sourceMap.map.sourcesContent || [];
let missingSourcesContentCount = 0;
for (let i = 0; i < sourceMap.map.sources.length; i++) {
Expand All @@ -108,7 +108,7 @@ class ValidSourceMaps extends Audit {
if (sourceMap || errors.length) {
results.push({
scriptUrl: scriptElement.src,
sourceMapUrl: sourceMap && sourceMap.sourceMapUrl,
sourceMapUrl: sourceMap?.sourceMapUrl,
subItems: {
type: /** @type {const} */ ('subitems'),
items: errors,
Expand Down
2 changes: 1 addition & 1 deletion lighthouse-core/computed/image-records.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ class ImageRecords {

for (const element of data.ImageElements) {
const networkRecord = indexedNetworkRecords[element.src];
const mimeType = networkRecord && networkRecord.mimeType;
const mimeType = networkRecord?.mimeType;

// Don't change the guessed mime type if no mime type was found.
imageRecords.push({
Expand Down
2 changes: 1 addition & 1 deletion lighthouse-core/computed/js-bundles.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ class JSBundles {
const mapUrl = SourceMap.sourceMapUrl || 'compiled.js.map';
const map = new SDK.TextSourceMap(compiledUrl, mapUrl, rawMap);

const content = scriptElement && scriptElement.content ? scriptElement.content : '';
const content = scriptElement?.content ? scriptElement.content : '';
const sizes = computeGeneratedFileSizes(map, content);

const bundle = {
Expand Down
2 changes: 1 addition & 1 deletion lighthouse-core/computed/metrics/lantern-metric.js
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ class LanternMetricArtifact {
const processedTrace = await ProcessedTrace.request(trace, context);
const processedNavigation = await ProcessedNavigation.request(processedTrace, context);
const simulator = data.simulator ||
await LoadSimulator.request({devtoolsLog, settings}, context);
(await LoadSimulator.request({devtoolsLog, settings}, context));

const optimisticGraph = this.getOptimisticGraph(graph, processedNavigation);
const pessimisticGraph = this.getPessimisticGraph(graph, processedNavigation);
Expand Down
70 changes: 35 additions & 35 deletions lighthouse-core/computed/metrics/timing-summary.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,22 +67,22 @@ class TimingSummary {
/** @type {LH.Artifacts.TimingSummary} */
const metrics = {
// Include the simulated/observed performance metrics
firstContentfulPaint: firstContentfulPaint && firstContentfulPaint.timing,
firstContentfulPaintTs: firstContentfulPaint && firstContentfulPaint.timestamp,
firstContentfulPaintAllFrames: firstContentfulPaintAllFrames && firstContentfulPaintAllFrames.timing,
firstContentfulPaintAllFramesTs: firstContentfulPaintAllFrames && firstContentfulPaintAllFrames.timestamp,
firstMeaningfulPaint: firstMeaningfulPaint && firstMeaningfulPaint.timing,
firstMeaningfulPaintTs: firstMeaningfulPaint && firstMeaningfulPaint.timestamp,
largestContentfulPaint: largestContentfulPaint && largestContentfulPaint.timing,
largestContentfulPaintTs: largestContentfulPaint && largestContentfulPaint.timestamp,
largestContentfulPaintAllFrames: largestContentfulPaintAllFrames && largestContentfulPaintAllFrames.timing,
largestContentfulPaintAllFramesTs: largestContentfulPaintAllFrames && largestContentfulPaintAllFrames.timestamp,
interactive: interactive && interactive.timing,
interactiveTs: interactive && interactive.timestamp,
speedIndex: speedIndex && speedIndex.timing,
speedIndexTs: speedIndex && speedIndex.timestamp,
totalBlockingTime: totalBlockingTime && totalBlockingTime.timing,
maxPotentialFID: maxPotentialFID && maxPotentialFID.timing,
firstContentfulPaint: firstContentfulPaint?.timing,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

firstContentfulPaintTs: firstContentfulPaint?.timestamp,
firstContentfulPaintAllFrames: firstContentfulPaintAllFrames?.timing,
firstContentfulPaintAllFramesTs: firstContentfulPaintAllFrames?.timestamp,
firstMeaningfulPaint: firstMeaningfulPaint?.timing,
firstMeaningfulPaintTs: firstMeaningfulPaint?.timestamp,
largestContentfulPaint: largestContentfulPaint?.timing,
largestContentfulPaintTs: largestContentfulPaint?.timestamp,
largestContentfulPaintAllFrames: largestContentfulPaintAllFrames?.timing,
largestContentfulPaintAllFramesTs: largestContentfulPaintAllFrames?.timestamp,
interactive: interactive?.timing,
interactiveTs: interactive?.timestamp,
speedIndex: speedIndex?.timing,
speedIndexTs: speedIndex?.timestamp,
totalBlockingTime: totalBlockingTime?.timing,
maxPotentialFID: maxPotentialFID?.timing,
cumulativeLayoutShift,
cumulativeLayoutShiftMainFrame,
totalCumulativeLayoutShift,
Expand All @@ -91,26 +91,26 @@ class TimingSummary {
observedTimeOrigin: processedTrace.timings.timeOrigin,
observedTimeOriginTs: processedTrace.timestamps.timeOrigin,
// For now, navigationStart is always timeOrigin.
observedNavigationStart: processedNavigation && processedNavigation.timings.timeOrigin,
observedNavigationStartTs: processedNavigation && processedNavigation.timestamps.timeOrigin,
observedFirstPaint: processedNavigation && processedNavigation.timings.firstPaint,
observedFirstPaintTs: processedNavigation && processedNavigation.timestamps.firstPaint,
observedFirstContentfulPaint: processedNavigation && processedNavigation.timings.firstContentfulPaint,
observedFirstContentfulPaintTs: processedNavigation && processedNavigation.timestamps.firstContentfulPaint,
observedFirstContentfulPaintAllFrames: processedNavigation && processedNavigation.timings.firstContentfulPaintAllFrames,
observedFirstContentfulPaintAllFramesTs: processedNavigation && processedNavigation.timestamps.firstContentfulPaintAllFrames,
observedFirstMeaningfulPaint: processedNavigation && processedNavigation.timings.firstMeaningfulPaint,
observedFirstMeaningfulPaintTs: processedNavigation && processedNavigation.timestamps.firstMeaningfulPaint,
observedLargestContentfulPaint: processedNavigation && processedNavigation.timings.largestContentfulPaint,
observedLargestContentfulPaintTs: processedNavigation && processedNavigation.timestamps.largestContentfulPaint,
observedLargestContentfulPaintAllFrames: processedNavigation && processedNavigation.timings.largestContentfulPaintAllFrames,
observedLargestContentfulPaintAllFramesTs: processedNavigation && processedNavigation.timestamps.largestContentfulPaintAllFrames,
observedNavigationStart: processedNavigation?.timings.timeOrigin,
observedNavigationStartTs: processedNavigation?.timestamps.timeOrigin,
observedFirstPaint: processedNavigation?.timings.firstPaint,
observedFirstPaintTs: processedNavigation?.timestamps.firstPaint,
observedFirstContentfulPaint: processedNavigation?.timings.firstContentfulPaint,
observedFirstContentfulPaintTs: processedNavigation?.timestamps.firstContentfulPaint,
observedFirstContentfulPaintAllFrames: processedNavigation?.timings.firstContentfulPaintAllFrames,
observedFirstContentfulPaintAllFramesTs: processedNavigation?.timestamps.firstContentfulPaintAllFrames,
observedFirstMeaningfulPaint: processedNavigation?.timings.firstMeaningfulPaint,
observedFirstMeaningfulPaintTs: processedNavigation?.timestamps.firstMeaningfulPaint,
observedLargestContentfulPaint: processedNavigation?.timings.largestContentfulPaint,
observedLargestContentfulPaintTs: processedNavigation?.timestamps.largestContentfulPaint,
observedLargestContentfulPaintAllFrames: processedNavigation?.timings.largestContentfulPaintAllFrames,
observedLargestContentfulPaintAllFramesTs: processedNavigation?.timestamps.largestContentfulPaintAllFrames,
observedTraceEnd: processedTrace.timings.traceEnd,
observedTraceEndTs: processedTrace.timestamps.traceEnd,
observedLoad: processedNavigation && processedNavigation.timings.load,
observedLoadTs: processedNavigation && processedNavigation.timestamps.load,
observedDomContentLoaded: processedNavigation && processedNavigation.timings.domContentLoaded,
observedDomContentLoadedTs: processedNavigation && processedNavigation.timestamps.domContentLoaded,
observedLoad: processedNavigation?.timings.load,
observedLoadTs: processedNavigation?.timestamps.load,
observedDomContentLoaded: processedNavigation?.timings.domContentLoaded,
observedDomContentLoadedTs: processedNavigation?.timestamps.domContentLoaded,
observedCumulativeLayoutShift: cumulativeLayoutShift,
observedCumulativeLayoutShiftMainFrame: cumulativeLayoutShiftMainFrame,
observedTotalCumulativeLayoutShift: totalCumulativeLayoutShift,
Expand All @@ -128,7 +128,7 @@ class TimingSummary {

/** @type {Record<string,boolean>} */
const debugInfo = {
lcpInvalidated: !!(processedNavigation && processedNavigation.lcpInvalidated),
lcpInvalidated: !!processedNavigation?.lcpInvalidated,
};

return {metrics, debugInfo};
Expand Down
Loading