lighthouse 9.5.0-dev.20220508 → 9.5.0-dev.20220511

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -63,14 +63,16 @@ class ExperimentalInteractionToNextPaint extends Audit {
63
63
 
64
64
  const trace = artifacts.traces[Audit.DEFAULT_PASS];
65
65
  const metricData = {trace, settings};
66
- const responsivenessEvent = await ComputedResponsivenes.request(metricData, context);
66
+ const interactionEvent = await ComputedResponsivenes.request(metricData, context);
67
67
 
68
68
  // TODO: include the no-interaction state in the report instead of using n/a.
69
- if (responsivenessEvent === null) {
69
+ if (interactionEvent === null) {
70
70
  return {score: null, notApplicable: true};
71
71
  }
72
72
 
73
- const timing = responsivenessEvent.args.data.maxDuration;
73
+ // TODO: remove workaround once 103.0.5052.0 is sufficiently released.
74
+ const timing = interactionEvent.name === 'FallbackTiming' ?
75
+ interactionEvent.duration : interactionEvent.args.data.duration;
74
76
 
75
77
  return {
76
78
  score: Audit.computeLogNormalScore({p10: context.options.p10, median: context.options.median},
@@ -0,0 +1,280 @@
1
+ /**
2
+ * @license Copyright 2022 The Lighthouse Authors. All Rights Reserved.
3
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
4
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
5
+ */
6
+ 'use strict';
7
+
8
+ const Audit = require('./audit.js');
9
+ const ComputedResponsivenes = require('../computed/metrics/responsiveness.js');
10
+ const ProcessedTrace = require('../computed/processed-trace.js');
11
+ const i18n = require('../lib/i18n/i18n.js');
12
+ const NetworkRecords = require('../computed/network-records.js');
13
+ const MainThreadTasks = require('../lib/tracehouse/main-thread-tasks.js');
14
+ const {taskGroups} = require('../lib/tracehouse/task-groups.js');
15
+ const TraceProcessor = require('../lib/tracehouse/trace-processor.js');
16
+ const {getExecutionTimingsByURL} = require('../lib/tracehouse/task-summary.js');
17
+ const inpThresholds = require('./metrics/experimental-interaction-to-next-paint.js').defaultOptions;
18
+ const LHError = require('../lib/lh-error.js');
19
+
20
+ /** @typedef {import('../computed/metrics/responsiveness.js').EventTimingEvent} EventTimingEvent */
21
+ /** @typedef {import('../lib/tracehouse/main-thread-tasks.js').TaskNode} TaskNode */
22
+
23
+ const TASK_THRESHOLD = 1;
24
+
25
+ const UIStrings = {
26
+ /** Title of a diagnostic audit that provides detail on the main thread work the browser did during a key user interaction. This descriptive title is shown to users when the amount is acceptable and no user action is required. */
27
+ title: 'Minimizes work during key interaction',
28
+ /** Title of a diagnostic audit that provides detail on the main thread work the browser did during a key user interaction. This imperative title is shown to users when there is a significant amount of execution time that could be reduced. */
29
+ failureTitle: 'Minimize work during key interaction',
30
+ /** Description of the work-during-interaction metric. This description is displayed within a tooltip when the user hovers on the metric name to see more. No character length limits. 'Learn More' becomes link text to additional documentation. */
31
+ description: 'This is the thread-blocking work occurring during the Interaction to Next Paint measurement. [Learn more](https://web.dev/inp/).',
32
+ /** Label for a column in a data table; entries will be information on the time that the browser is delayed before responding to user input. Ideally fits within a ~40 character limit. */
33
+ inputDelay: 'Input delay',
34
+ /** Label for a column in a data table; entries will be information on the time taken by code processing user input that delays a response to the user. Ideally fits within a ~40 character limit. */
35
+ processingDelay: 'Processing delay',
36
+ /** Label for a column in a data table; entries will be information on the time that the browser is delayed before presenting a response to user input on screen. Ideally fits within a ~40 character limit. */
37
+ presentationDelay: 'Presentation delay',
38
+ /**
39
+ * @description Summary text that identifies the time the browser took to process a user interaction.
40
+ * @example {mousedown} interactionType
41
+ */
42
+ displayValue: `{timeInMs, number, milliseconds}\xa0ms spent on event '{interactionType}'`,
43
+ /** Label for a column in a data table; entries will the UI element that was the target of a user interaction (for example, a button that was clicked on). Ideally fits within a ~40 character limit. */
44
+ eventTarget: 'Event target',
45
+ };
46
+
47
+ const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings);
48
+
49
+ /**
50
+ * @fileoverview This metric gives a high-percentile measure of responsiveness to input.
51
+ */
52
+ class WorkDuringInteraction extends Audit {
53
+ /**
54
+ * @return {LH.Audit.Meta}
55
+ */
56
+ static get meta() {
57
+ return {
58
+ id: 'work-during-interaction',
59
+ title: str_(UIStrings.title),
60
+ failureTitle: str_(UIStrings.failureTitle),
61
+ description: str_(UIStrings.description),
62
+ scoreDisplayMode: Audit.SCORING_MODES.NUMERIC,
63
+ supportedModes: ['timespan'],
64
+ requiredArtifacts: ['traces', 'devtoolsLogs', 'TraceElements'],
65
+ };
66
+ }
67
+
68
+ /**
69
+ * @param {TaskNode} task
70
+ * @param {TaskNode|undefined} parent
71
+ * @param {number} startTs
72
+ * @param {number} endTs
73
+ * @return {number}
74
+ */
75
+ static recursivelyClipTasks(task, parent, startTs, endTs) {
76
+ const taskEventStart = task.event.ts;
77
+ const taskEventEnd = task.endEvent?.ts ?? task.event.ts + Number(task.event.dur || 0);
78
+
79
+ task.startTime = Math.max(startTs, Math.min(endTs, taskEventStart)) / 1000;
80
+ task.endTime = Math.max(startTs, Math.min(endTs, taskEventEnd)) / 1000;
81
+ task.duration = task.endTime - task.startTime;
82
+
83
+ const childTime = task.children
84
+ .map(child => WorkDuringInteraction.recursivelyClipTasks(child, task, startTs, endTs))
85
+ .reduce((sum, child) => sum + child, 0);
86
+ task.selfTime = task.duration - childTime;
87
+ return task.duration;
88
+ }
89
+
90
+ /**
91
+ * Clip the tasks by the start and end points. Take the easy route and drop
92
+ * to duration 0 if out of bounds, since only durations are needed in the
93
+ * end (for now).
94
+ * Assumes owned tasks, so modifies in place. Can be called multiple times on
95
+ * the same `tasks` because always computed from original event timing.
96
+ * @param {Array<TaskNode>} tasks
97
+ * @param {number} startTs
98
+ * @param {number} endTs
99
+ */
100
+ static clipTasksByTs(tasks, startTs, endTs) {
101
+ for (const task of tasks) {
102
+ if (task.parent) continue;
103
+ WorkDuringInteraction.recursivelyClipTasks(task, undefined, startTs, endTs);
104
+ }
105
+ }
106
+
107
+ /**
108
+ * @param {EventTimingEvent} interactionEvent
109
+ */
110
+ static getPhaseTimes(interactionEvent) {
111
+ const interactionData = interactionEvent.args.data;
112
+ const startTs = interactionEvent.ts;
113
+ const navStart = startTs - interactionData.timeStamp * 1000;
114
+ const processingStartTs = navStart + interactionData.processingStart * 1000;
115
+ const processingEndTs = navStart + interactionData.processingEnd * 1000;
116
+ const endTs = startTs + interactionData.duration * 1000;
117
+ return {
118
+ inputDelay: {startTs, endTs: processingStartTs},
119
+ processingDelay: {startTs: processingStartTs, endTs: processingEndTs},
120
+ presentationDelay: {startTs: processingEndTs, endTs},
121
+ };
122
+ }
123
+
124
+ /**
125
+ * @param {EventTimingEvent} interactionEvent
126
+ * @param {LH.Trace} trace
127
+ * @param {LH.Artifacts.ProcessedTrace} processedTrace
128
+ * @param {Array<LH.Artifacts.NetworkRequest>} networkRecords
129
+ * @return {{table: LH.Audit.Details.Table, phases: Record<string, {startTs: number, endTs: number}>}}
130
+ */
131
+ static getThreadBreakdownTable(interactionEvent, trace, processedTrace, networkRecords) {
132
+ // Limit to interactionEvent's thread.
133
+ // TODO(bckenny): limit to interactionEvent's navigation.
134
+ const threadEvents = TraceProcessor.filteredTraceSort(trace.traceEvents, evt => {
135
+ return evt.pid === interactionEvent.pid && evt.tid === interactionEvent.tid;
136
+ });
137
+ const traceEndTs = threadEvents.reduce((endTs, evt) => {
138
+ return Math.max(evt.ts + (evt.dur || 0), endTs);
139
+ }, 0);
140
+ // frames is only used for URL attribution, so can include all frames, even if OOPIF.
141
+ const {frames} = processedTrace;
142
+ const threadTasks = MainThreadTasks.getMainThreadTasks(threadEvents, frames, traceEndTs);
143
+
144
+ const phases = WorkDuringInteraction.getPhaseTimes(interactionEvent);
145
+
146
+ /** @type {LH.Audit.Details.TableItem[]} */
147
+ const items = [];
148
+ for (const [phaseName, phaseTimes] of Object.entries(phases)) {
149
+ // Clip tasks to start and end time.
150
+ WorkDuringInteraction.clipTasksByTs(threadTasks, phaseTimes.startTs, phaseTimes.endTs);
151
+ const executionTimings = getExecutionTimingsByURL(threadTasks, networkRecords);
152
+
153
+ const results = [];
154
+ for (const [url, timingByGroupId] of executionTimings) {
155
+ const totalExecutionTimeForURL = Object.values(timingByGroupId)
156
+ .reduce((total, timespanMs) => total + timespanMs);
157
+
158
+ const scriptingTotal = timingByGroupId[taskGroups.scriptEvaluation.id] || 0;
159
+ const layoutTotal = timingByGroupId[taskGroups.styleLayout.id] || 0;
160
+ const renderTotal = timingByGroupId[taskGroups.paintCompositeRender.id] || 0;
161
+
162
+ results.push({
163
+ url: url,
164
+ total: totalExecutionTimeForURL,
165
+ scripting: scriptingTotal,
166
+ layout: layoutTotal,
167
+ render: renderTotal,
168
+ });
169
+ }
170
+
171
+ const filteredResults = results
172
+ .filter(result => result.total > TASK_THRESHOLD)
173
+ .sort((a, b) => b.total - a.total);
174
+
175
+ items.push({
176
+ phase: str_(UIStrings[/** @type {keyof UIStrings} */ (phaseName)]),
177
+ total: (phaseTimes.endTs - phaseTimes.startTs) / 1000,
178
+ subItems: {
179
+ type: 'subitems',
180
+ items: filteredResults,
181
+ },
182
+ });
183
+ }
184
+
185
+ /** @type {LH.Audit.Details.Table['headings']} */
186
+ const headings = [
187
+ /* eslint-disable max-len */
188
+ {key: 'phase', itemType: 'text', subItemsHeading: {key: 'url', itemType: 'url'}, text: 'Phase'},
189
+ {key: 'total', itemType: 'ms', subItemsHeading: {key: 'total', granularity: 1, itemType: 'ms'}, granularity: 1, text: 'Total time'},
190
+ {key: null, itemType: 'ms', subItemsHeading: {key: 'scripting', granularity: 1, itemType: 'ms'}, text: 'Script evaluation'},
191
+ {key: null, itemType: 'ms', subItemsHeading: {key: 'layout', granularity: 1, itemType: 'ms'}, text: taskGroups.styleLayout.label},
192
+ {key: null, itemType: 'ms', subItemsHeading: {key: 'render', granularity: 1, itemType: 'ms'}, text: taskGroups.paintCompositeRender.label},
193
+ /* eslint-enable max-len */
194
+ ];
195
+
196
+ return {
197
+ table: Audit.makeTableDetails(headings, items),
198
+ phases,
199
+ };
200
+ }
201
+
202
+ /**
203
+ * @param {LH.Artifacts['TraceElements']} traceElements
204
+ * @return {LH.Audit.Details.Table | undefined}
205
+ */
206
+ static getTraceElementTable(traceElements) {
207
+ const responsivenessElement = traceElements.find(el => el.traceEventType === 'responsiveness');
208
+ if (!responsivenessElement) return;
209
+
210
+ /** @type {LH.Audit.Details.Table['headings']} */
211
+ const headings = [
212
+ {key: 'node', itemType: 'node', text: str_(UIStrings.eventTarget)},
213
+ ];
214
+ const elementItems = [{node: Audit.makeNodeItem(responsivenessElement.node)}];
215
+
216
+ return Audit.makeTableDetails(headings, elementItems);
217
+ }
218
+
219
+ /**
220
+ * @param {LH.Artifacts} artifacts
221
+ * @param {LH.Audit.Context} context
222
+ * @return {Promise<LH.Audit.Product>}
223
+ */
224
+ static async audit(artifacts, context) {
225
+ const {settings} = context;
226
+ // TODO: responsiveness isn't yet supported by lantern.
227
+ if (settings.throttlingMethod === 'simulate') {
228
+ return {score: null, notApplicable: true};
229
+ }
230
+
231
+ const trace = artifacts.traces[WorkDuringInteraction.DEFAULT_PASS];
232
+ const metricData = {trace, settings};
233
+ const interactionEvent = await ComputedResponsivenes.request(metricData, context);
234
+ // If no interaction, diagnostic audit is n/a.
235
+ if (interactionEvent === null) {
236
+ return {score: null, notApplicable: true};
237
+ }
238
+ // TODO: remove workaround once 103.0.5052.0 is sufficiently released.
239
+ if (interactionEvent.name === 'FallbackTiming') {
240
+ throw new LHError(
241
+ LHError.errors.UNSUPPORTED_OLD_CHROME,
242
+ {featureName: 'detailed EventTiming trace events'}
243
+ );
244
+ }
245
+
246
+ const auditDetailsItems = [];
247
+
248
+ const traceElementItem = WorkDuringInteraction.getTraceElementTable(artifacts.TraceElements);
249
+ if (traceElementItem) auditDetailsItems.push(traceElementItem);
250
+
251
+ const devtoolsLog = artifacts.devtoolsLogs[WorkDuringInteraction.DEFAULT_PASS];
252
+ // Network records will usually be empty for timespans.
253
+ const networkRecords = await NetworkRecords.request(devtoolsLog, context);
254
+ const processedTrace = await ProcessedTrace.request(trace, context);
255
+ const {table: breakdownTable, phases} = WorkDuringInteraction.getThreadBreakdownTable(
256
+ interactionEvent, trace, processedTrace, networkRecords);
257
+ auditDetailsItems.push(breakdownTable);
258
+
259
+ const interactionType = interactionEvent.args.data.type;
260
+ auditDetailsItems.push({
261
+ type: /** @type {const} */ ('debugdata'),
262
+ interactionType,
263
+ phases,
264
+ });
265
+
266
+ const duration = interactionEvent.args.data.duration;
267
+ const displayValue = str_(UIStrings.displayValue, {timeInMs: duration, interactionType});
268
+ return {
269
+ score: duration < inpThresholds.p10 ? 1 : 0,
270
+ displayValue,
271
+ details: {
272
+ type: 'list',
273
+ items: auditDetailsItems,
274
+ },
275
+ };
276
+ }
277
+ }
278
+
279
+ module.exports = WorkDuringInteraction;
280
+ module.exports.UIStrings = UIStrings;
@@ -12,10 +12,38 @@
12
12
  */
13
13
 
14
14
  /** @typedef {LH.Trace.CompleteEvent & {name: 'Responsiveness.Renderer.UserInteraction', args: {frame: string, data: {interactionType: 'drag'|'keyboard'|'tapOrClick', maxDuration: number}}}} ResponsivenessEvent */
15
+ /** @typedef {'keydown'|'keypress'|'keyup'|'mousedown'|'mouseup'|'pointerdown'|'pointerup'|'click'} EventTimingType */
16
+ /**
17
+ * @typedef EventTimingData
18
+ * @property {string} frame
19
+ * @property {number} timeStamp The time of user interaction (in ms from navStart).
20
+ * @property {number} processingStart The start of interaction handling (in ms from navStart).
21
+ * @property {number} processingEnd The end of interaction handling (in ms from navStart).
22
+ * @property {number} duration The time from user interaction to browser paint (in ms).
23
+ * @property {EventTimingType} type
24
+ * @property {number} nodeId
25
+ * @property {number} interactionId
26
+ */
27
+ /** @typedef {LH.Trace.AsyncEvent & {name: 'EventTiming', args: {data: EventTimingData}}} EventTimingEvent */
28
+ /**
29
+ * A fallback EventTiming placeholder, used if updated EventTiming events are not available.
30
+ * TODO: Remove once 103.0.5052.0 is sufficiently released.
31
+ * @typedef {{name: 'FallbackTiming', duration: number}} FallbackTimingEvent
32
+ */
15
33
 
16
34
  const makeComputedArtifact = require('../computed-artifact.js');
17
35
  const ProcessedTrace = require('../processed-trace.js');
18
36
 
37
+ const KEYBOARD_EVENTS = new Set(['keydown', 'keypress', 'keyup']);
38
+ const CLICK_TAP_DRAG_EVENTS = new Set([
39
+ 'mousedown', 'mouseup', 'pointerdown', 'pointerup', 'click']);
40
+ /** A map of Responsiveness `interactionType` to matching EventTiming `type`s. */
41
+ const interactionTypeToType = {
42
+ keyboard: KEYBOARD_EVENTS,
43
+ tapOrClick: CLICK_TAP_DRAG_EVENTS,
44
+ drag: CLICK_TAP_DRAG_EVENTS,
45
+ };
46
+
19
47
  class Responsiveness {
20
48
  /**
21
49
  * @param {LH.Artifacts.ProcessedTrace} processedTrace
@@ -42,20 +70,84 @@ class Responsiveness {
42
70
  return responsivenessEvents[index];
43
71
  }
44
72
 
73
+ /**
74
+ * Finds the interaction event that was probably the responsivenessEvent.maxDuration
75
+ * source.
76
+ * Note that (presumably due to rounding to ms), the interaction duration may not
77
+ * be the same value as `maxDuration`, just the closest value. Function will throw
78
+ * if the closest match is off by more than 4ms.
79
+ * TODO: this doesn't try to match inputs to interactions and break ties if more than
80
+ * one interaction had this duration by returning the first found.
81
+ * @param {ResponsivenessEvent} responsivenessEvent
82
+ * @param {LH.Trace} trace
83
+ * @return {EventTimingEvent|FallbackTimingEvent}
84
+ */
85
+ static findInteractionEvent(responsivenessEvent, {traceEvents}) {
86
+ const candidates = traceEvents.filter(/** @return {evt is EventTimingEvent} */ evt => {
87
+ // Examine only beginning/instant EventTiming events.
88
+ return evt.name === 'EventTiming' && evt.ph !== 'e';
89
+ });
90
+
91
+ if (candidates.length && !candidates.some(candidate => candidate.args.data?.frame)) {
92
+ // Full EventTiming data added in https://crrev.com/c/3632661
93
+ return {
94
+ name: 'FallbackTiming',
95
+ duration: responsivenessEvent.args.data.maxDuration,
96
+ };
97
+ }
98
+
99
+ const {maxDuration, interactionType} = responsivenessEvent.args.data;
100
+ let bestMatchEvent;
101
+ let minDurationDiff = Number.POSITIVE_INFINITY;
102
+ for (const candidate of candidates) {
103
+ // Must be from same frame.
104
+ if (candidate.args.data.frame !== responsivenessEvent.args.frame) continue;
105
+
106
+ // TODO(bckenny): must be in same navigation as well.
107
+
108
+ const {type, duration} = candidate.args.data;
109
+ // Discard if type is incompatible with responsiveness interactionType.
110
+ const matchingTypes = interactionTypeToType[interactionType];
111
+ if (!matchingTypes) {
112
+ throw new Error(`unexpected responsiveness interactionType '${interactionType}'`);
113
+ }
114
+ if (!matchingTypes.has(type)) continue;
115
+
116
+ const durationDiff = Math.abs(duration - maxDuration);
117
+ if (durationDiff < minDurationDiff) {
118
+ bestMatchEvent = candidate;
119
+ minDurationDiff = durationDiff;
120
+ }
121
+ }
122
+
123
+ if (!bestMatchEvent) {
124
+ throw new Error(`no interaction event found for responsiveness type '${interactionType}'`);
125
+ }
126
+ // TODO: seems to regularly happen up to 3ms and as high as 4. Allow for up to 5ms to be sure.
127
+ if (minDurationDiff > 5) {
128
+ throw new Error(`no interaction event found within 5ms of responsiveness maxDuration (max: ${maxDuration}, closest ${bestMatchEvent.args.data.duration})`); // eslint-disable-line max-len
129
+ }
130
+
131
+ return bestMatchEvent;
132
+ }
133
+
45
134
  /**
46
135
  * @param {{trace: LH.Trace, settings: Immutable<LH.Config.Settings>}} data
47
136
  * @param {LH.Artifacts.ComputedContext} context
48
- * @return {Promise<ResponsivenessEvent|null>}
137
+ * @return {Promise<EventTimingEvent|FallbackTimingEvent|null>}
49
138
  */
50
139
  static async compute_(data, context) {
51
- if (data.settings.throttlingMethod === 'simulate') {
140
+ const {settings, trace} = data;
141
+ if (settings.throttlingMethod === 'simulate') {
52
142
  throw new Error('Responsiveness currently unsupported by simulated throttling');
53
143
  }
54
144
 
55
- const processedTrace = await ProcessedTrace.request(data.trace, context);
56
- const event = Responsiveness.getHighPercentileResponsiveness(processedTrace);
145
+ const processedTrace = await ProcessedTrace.request(trace, context);
146
+ const responsivenessEvent = Responsiveness.getHighPercentileResponsiveness(processedTrace);
147
+ if (!responsivenessEvent) return null;
57
148
 
58
- return JSON.parse(JSON.stringify(event));
149
+ const interactionEvent = Responsiveness.findInteractionEvent(responsivenessEvent, trace);
150
+ return JSON.parse(JSON.stringify(interactionEvent));
59
151
  }
60
152
  }
61
153
 
@@ -48,9 +48,14 @@ const clsRelevantAudits = [
48
48
  // 'preload-fonts', // actually in BP, rather than perf
49
49
  ];
50
50
 
51
+ const inpRelevantAudits = [
52
+ 'work-during-interaction',
53
+ ];
54
+
51
55
  module.exports = {
52
56
  fcpRelevantAudits,
53
57
  lcpRelevantAudits,
54
58
  tbtRelevantAudits,
55
59
  clsRelevantAudits,
60
+ inpRelevantAudits,
56
61
  };
@@ -6,19 +6,23 @@
6
6
  'use strict';
7
7
 
8
8
  const legacyDefaultConfig = require('../../config/default-config.js');
9
+ const m2a = require('../../config/metrics-to-audits.js');
9
10
  const {deepClone} = require('../../config/config-helpers.js');
10
11
 
11
12
  /** @type {LH.Config.AuditJson[]} */
12
13
  const frAudits = [
13
14
  'byte-efficiency/uses-responsive-images-snapshot',
14
15
  'metrics/experimental-interaction-to-next-paint',
16
+ 'work-during-interaction',
15
17
  ];
16
18
 
17
19
  /** @type {Record<string, LH.Config.AuditRefJson[]>} */
18
20
  const frCategoryAuditRefExtensions = {
19
21
  'performance': [
20
22
  {id: 'uses-responsive-images-snapshot', weight: 0},
21
- {id: 'experimental-interaction-to-next-paint', weight: 0, group: 'metrics', acronym: 'INP'},
23
+ {id: 'experimental-interaction-to-next-paint', weight: 0, group: 'metrics', acronym: 'INP',
24
+ relevantAudits: m2a.inpRelevantAudits},
25
+ {id: 'work-during-interaction', weight: 0},
22
26
  ],
23
27
  };
24
28
 
@@ -100,7 +104,6 @@ const defaultConfig = {
100
104
  {id: artifacts.EmbeddedContent, gatherer: 'seo/embedded-content'},
101
105
  {id: artifacts.FontSize, gatherer: 'seo/font-size'},
102
106
  {id: artifacts.Inputs, gatherer: 'inputs'},
103
- {id: artifacts.FullPageScreenshot, gatherer: 'full-page-screenshot'},
104
107
  {id: artifacts.GlobalListeners, gatherer: 'global-listeners'},
105
108
  {id: artifacts.IFrameElements, gatherer: 'iframe-elements'},
106
109
  {id: artifacts.ImageElements, gatherer: 'image-elements'},
@@ -130,6 +133,9 @@ const defaultConfig = {
130
133
  // Artifact copies are renamed for compatibility with legacy artifacts.
131
134
  {id: artifacts.devtoolsLogs, gatherer: 'devtools-log-compat'},
132
135
  {id: artifacts.traces, gatherer: 'trace-compat'},
136
+
137
+ // FullPageScreenshot comes at the very end so all other node analysis is captured.
138
+ {id: artifacts.FullPageScreenshot, gatherer: 'full-page-screenshot'},
133
139
  ],
134
140
  navigations: [
135
141
  {
@@ -5,7 +5,9 @@
5
5
  */
6
6
  'use strict';
7
7
 
8
+ const log = require('lighthouse-logger');
8
9
  const FRGatherer = require('../../fraggle-rock/gather/base-gatherer.js');
10
+ const Sentry = require('../../lib/sentry.js');
9
11
 
10
12
  /**
11
13
  * @fileoverview Tracks unused CSS rules.
@@ -13,21 +15,16 @@ const FRGatherer = require('../../fraggle-rock/gather/base-gatherer.js');
13
15
  class CSSUsage extends FRGatherer {
14
16
  constructor() {
15
17
  super();
16
- /** @type {Array<LH.Crdp.CSS.StyleSheetAddedEvent>} */
17
- this._stylesheets = [];
18
- /** @param {LH.Crdp.CSS.StyleSheetAddedEvent} sheet */
19
- this._onStylesheetAdded = sheet => this._stylesheets.push(sheet);
20
- /** @param {LH.Crdp.CSS.StyleSheetRemovedEvent} sheet */
21
- this._onStylesheetRemoved = sheet => {
22
- // We can't fetch the content of removed stylesheets, so we ignore them completely.
23
- const styleSheetId = sheet.styleSheetId;
24
- this._stylesheets = this._stylesheets.filter(s => s.header.styleSheetId !== styleSheetId);
25
- };
18
+ /** @type {LH.Gatherer.FRProtocolSession|undefined} */
19
+ this._session = undefined;
20
+ /** @type {Map<string, Promise<LH.Artifacts.CSSStyleSheetInfo|Error>>} */
21
+ this._sheetPromises = new Map();
26
22
  /**
27
23
  * Initialize as undefined so we can assert results are fetched.
28
24
  * @type {LH.Crdp.CSS.RuleUsage[]|undefined}
29
25
  */
30
26
  this._ruleUsage = undefined;
27
+ this._onStylesheetAdded = this._onStylesheetAdded.bind(this);
31
28
  }
32
29
 
33
30
  /** @type {LH.Gatherer.GathererMeta} */
@@ -35,26 +32,49 @@ class CSSUsage extends FRGatherer {
35
32
  supportedModes: ['snapshot', 'timespan', 'navigation'],
36
33
  };
37
34
 
35
+ /**
36
+ * @param {LH.Crdp.CSS.StyleSheetAddedEvent} event
37
+ */
38
+ async _onStylesheetAdded(event) {
39
+ if (!this._session) throw new Error('Session not initialized');
40
+ const styleSheetId = event.header.styleSheetId;
41
+ const sheetPromise = this._session.sendCommand('CSS.getStyleSheetText', {styleSheetId})
42
+ .then(content => ({
43
+ header: event.header,
44
+ content: content.text,
45
+ }))
46
+ .catch(/** @param {Error} err */ (err) => {
47
+ log.warn(
48
+ 'CSSUsage',
49
+ `Error fetching content of stylesheet with URL "${event.header.sourceURL}"`
50
+ );
51
+ Sentry.captureException(err, {
52
+ tags: {
53
+ gatherer: this.name,
54
+ },
55
+ extra: {
56
+ url: event.header.sourceURL,
57
+ },
58
+ level: 'error',
59
+ });
60
+ return err;
61
+ });
62
+ this._sheetPromises.set(styleSheetId, sheetPromise);
63
+ }
64
+
38
65
  /**
39
66
  * @param {LH.Gatherer.FRTransitionalContext} context
40
67
  */
41
68
  async startCSSUsageTracking(context) {
42
69
  const session = context.driver.defaultSession;
70
+ this._session = session;
43
71
  session.on('CSS.styleSheetAdded', this._onStylesheetAdded);
44
- session.on('CSS.styleSheetRemoved', this._onStylesheetRemoved);
45
72
 
46
73
  await session.sendCommand('DOM.enable');
47
74
  await session.sendCommand('CSS.enable');
48
75
  await session.sendCommand('CSS.startRuleUsageTracking');
49
76
  }
50
77
 
51
- /**
52
- * @param {LH.Gatherer.FRTransitionalContext} context
53
- */
54
- async startInstrumentation(context) {
55
- if (context.gatherMode !== 'timespan') return;
56
- await this.startCSSUsageTracking(context);
57
- }
58
78
 
59
79
  /**
60
80
  * @param {LH.Gatherer.FRTransitionalContext} context
@@ -64,7 +84,14 @@ class CSSUsage extends FRGatherer {
64
84
  const coverageResponse = await session.sendCommand('CSS.stopRuleUsageTracking');
65
85
  this._ruleUsage = coverageResponse.ruleUsage;
66
86
  session.off('CSS.styleSheetAdded', this._onStylesheetAdded);
67
- session.off('CSS.styleSheetRemoved', this._onStylesheetRemoved);
87
+ }
88
+
89
+ /**
90
+ * @param {LH.Gatherer.FRTransitionalContext} context
91
+ */
92
+ async startInstrumentation(context) {
93
+ if (context.gatherMode !== 'timespan') return;
94
+ await this.startCSSUsageTracking(context);
68
95
  }
69
96
 
70
97
  /**
@@ -93,25 +120,23 @@ class CSSUsage extends FRGatherer {
93
120
  await this.stopCSSUsageTracking(context);
94
121
  }
95
122
 
96
- // Fetch style sheet content in parallel.
97
- const promises = this._stylesheets.map(sheet => {
98
- const styleSheetId = sheet.header.styleSheetId;
99
- return session.sendCommand('CSS.getStyleSheetText', {styleSheetId}).then(content => {
100
- return {
101
- header: sheet.header,
102
- content: content.text,
103
- };
104
- });
105
- });
106
- const styleSheetInfo = await Promise.all(promises);
123
+ /** @type {Map<string, LH.Artifacts.CSSStyleSheetInfo>} */
124
+ const dedupedStylesheets = new Map();
125
+ const sheets = await Promise.all(this._sheetPromises.values());
126
+
127
+ for (const sheet of sheets) {
128
+ // Erroneous sheets will be reported via sentry and the log.
129
+ // We can ignore them here without throwing a fatal error.
130
+ if (sheet instanceof Error) {
131
+ continue;
132
+ }
133
+
134
+ dedupedStylesheets.set(sheet.content, sheet);
135
+ }
107
136
 
108
137
  await session.sendCommand('CSS.disable');
109
138
  await session.sendCommand('DOM.disable');
110
139
 
111
- const dedupedStylesheets = new Map(styleSheetInfo.map(sheet => {
112
- return [sheet.content, sheet];
113
- }));
114
-
115
140
  if (!this._ruleUsage) throw new Error('Issue collecting rule usages');
116
141
 
117
142
  return {