lighthouse 11.6.0-dev.20240304 → 11.6.0-dev.20240305

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.
@@ -4,7 +4,9 @@
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
6
 
7
- import * as Lantern from './lantern.js';
7
+ /** @template T @typedef {import('../../../types/internal/lantern.js').Lantern.NetworkRequest<T>} NetworkRequest */
8
+
9
+ import {NetworkRequestTypes} from './lantern.js';
8
10
  import {BaseNode} from './base-node.js';
9
11
  // TODO(15841): bring impl of isNonNetworkRequest inside lantern and remove this.
10
12
  import UrlUtils from '../url-utils.js';
@@ -15,7 +17,7 @@ import UrlUtils from '../url-utils.js';
15
17
  */
16
18
  class NetworkNode extends BaseNode {
17
19
  /**
18
- * @param {Lantern.NetworkRequest<T>} networkRequest
20
+ * @param {NetworkRequest<T>} networkRequest
19
21
  */
20
22
  constructor(networkRequest) {
21
23
  super(networkRequest.requestId);
@@ -49,7 +51,7 @@ class NetworkNode extends BaseNode {
49
51
  }
50
52
 
51
53
  /**
52
- * @return {Lantern.NetworkRequest<T>}
54
+ * @return {NetworkRequest<T>}
53
55
  */
54
56
  get request() {
55
57
  return this._request;
@@ -93,8 +95,8 @@ class NetworkNode extends BaseNode {
93
95
  */
94
96
  hasRenderBlockingPriority() {
95
97
  const priority = this._request.priority;
96
- const isScript = this._request.resourceType === Lantern.NetworkRequestTypes.Script;
97
- const isDocument = this._request.resourceType === Lantern.NetworkRequestTypes.Document;
98
+ const isScript = this._request.resourceType === NetworkRequestTypes.Script;
99
+ const isDocument = this._request.resourceType === NetworkRequestTypes.Document;
98
100
  const isBlockingScript = priority === 'High' && isScript;
99
101
  const isBlockingHtmlImport = priority === 'High' && isDocument;
100
102
  return priority === 'VeryHigh' || isBlockingScript || isBlockingHtmlImport;
@@ -0,0 +1,58 @@
1
+ export type NetworkRequest = import('../../../types/internal/lantern.js').Lantern.NetworkRequest;
2
+ export type Node = import('./base-node.js').Node;
3
+ export type URLArtifact = Omit<LH.Artifacts['URL'], 'finalDisplayedUrl'>;
4
+ export type NetworkNodeOutput = {
5
+ nodes: Array<NetworkNode>;
6
+ idToNodeMap: Map<string, NetworkNode>;
7
+ urlToNodeMap: Map<string, Array<NetworkNode>>;
8
+ frameIdToNodeMap: Map<string, NetworkNode | null>;
9
+ };
10
+ export class PageDependencyGraph {
11
+ /**
12
+ * @param {NetworkRequest} record
13
+ * @return {Array<string>}
14
+ */
15
+ static getNetworkInitiators(record: NetworkRequest): Array<string>;
16
+ /**
17
+ * @param {Array<NetworkRequest>} networkRecords
18
+ * @return {NetworkNodeOutput}
19
+ */
20
+ static getNetworkNodeOutput(networkRecords: Array<NetworkRequest>): NetworkNodeOutput;
21
+ /**
22
+ * @param {LH.Artifacts.ProcessedTrace} processedTrace
23
+ * @return {Array<CPUNode>}
24
+ */
25
+ static getCPUNodes({ mainThreadEvents }: LH.Artifacts.ProcessedTrace): Array<CPUNode>;
26
+ /**
27
+ * @param {NetworkNode} rootNode
28
+ * @param {NetworkNodeOutput} networkNodeOutput
29
+ */
30
+ static linkNetworkNodes(rootNode: NetworkNode, networkNodeOutput: NetworkNodeOutput): void;
31
+ /**
32
+ * @param {Node} rootNode
33
+ * @param {NetworkNodeOutput} networkNodeOutput
34
+ * @param {Array<CPUNode>} cpuNodes
35
+ */
36
+ static linkCPUNodes(rootNode: Node, networkNodeOutput: NetworkNodeOutput, cpuNodes: Array<CPUNode>): void;
37
+ /**
38
+ * Removes the given node from the graph, but retains all paths between its dependencies and
39
+ * dependents.
40
+ * @param {Node} node
41
+ */
42
+ static _pruneNode(node: Node): void;
43
+ /**
44
+ * @param {LH.Artifacts.ProcessedTrace} processedTrace
45
+ * @param {Array<NetworkRequest>} networkRecords
46
+ * @param {URLArtifact} URL
47
+ * @return {Node}
48
+ */
49
+ static createGraph(processedTrace: LH.Artifacts.ProcessedTrace, networkRecords: Array<NetworkRequest>, URL: URLArtifact): Node;
50
+ /**
51
+ *
52
+ * @param {Node} rootNode
53
+ */
54
+ static printGraph(rootNode: Node, widthInCharacters?: number): void;
55
+ }
56
+ import { NetworkNode } from './network-node.js';
57
+ import { CPUNode } from './cpu-node.js';
58
+ //# sourceMappingURL=page-dependency-graph.d.ts.map
@@ -0,0 +1,463 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2024 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import {NetworkRequestTypes} from './lantern.js';
8
+ import {NetworkNode} from './network-node.js';
9
+ import {CPUNode} from './cpu-node.js';
10
+ import {TraceProcessor} from '../tracehouse/trace-processor.js';
11
+ import {NetworkAnalyzer} from './simulator/network-analyzer.js';
12
+
13
+ /** @typedef {import('../../../types/internal/lantern.js').Lantern.NetworkRequest} NetworkRequest */
14
+ /** @typedef {import('./base-node.js').Node} Node */
15
+ /** @typedef {Omit<LH.Artifacts['URL'], 'finalDisplayedUrl'>} URLArtifact */
16
+
17
+ /**
18
+ * @typedef {Object} NetworkNodeOutput
19
+ * @property {Array<NetworkNode>} nodes
20
+ * @property {Map<string, NetworkNode>} idToNodeMap
21
+ * @property {Map<string, Array<NetworkNode>>} urlToNodeMap
22
+ * @property {Map<string, NetworkNode|null>} frameIdToNodeMap
23
+ */
24
+
25
+ // Shorter tasks have negligible impact on simulation results.
26
+ const SIGNIFICANT_DUR_THRESHOLD_MS = 10;
27
+
28
+ // TODO: video files tend to be enormous and throw off all graph traversals, move this ignore
29
+ // into estimation logic when we use the dependency graph for other purposes.
30
+ const IGNORED_MIME_TYPES_REGEX = /^video/;
31
+
32
+ class PageDependencyGraph {
33
+ /**
34
+ * @param {NetworkRequest} record
35
+ * @return {Array<string>}
36
+ */
37
+ static getNetworkInitiators(record) {
38
+ if (!record.initiator) return [];
39
+ if (record.initiator.url) return [record.initiator.url];
40
+ if (record.initiator.type === 'script') {
41
+ // Script initiators have the stack of callFrames from all functions that led to this request.
42
+ // If async stacks are enabled, then the stack will also have the parent functions that asynchronously
43
+ // led to this request chained in the `parent` property.
44
+ /** @type {Set<string>} */
45
+ const scriptURLs = new Set();
46
+ let stack = record.initiator.stack;
47
+ while (stack) {
48
+ const callFrames = stack.callFrames || [];
49
+ for (const frame of callFrames) {
50
+ if (frame.url) scriptURLs.add(frame.url);
51
+ }
52
+
53
+ stack = stack.parent;
54
+ }
55
+
56
+ return Array.from(scriptURLs);
57
+ }
58
+
59
+ return [];
60
+ }
61
+
62
+ /**
63
+ * @param {Array<NetworkRequest>} networkRecords
64
+ * @return {NetworkNodeOutput}
65
+ */
66
+ static getNetworkNodeOutput(networkRecords) {
67
+ /** @type {Array<NetworkNode>} */
68
+ const nodes = [];
69
+ /** @type {Map<string, NetworkNode>} */
70
+ const idToNodeMap = new Map();
71
+ /** @type {Map<string, Array<NetworkNode>>} */
72
+ const urlToNodeMap = new Map();
73
+ /** @type {Map<string, NetworkNode|null>} */
74
+ const frameIdToNodeMap = new Map();
75
+
76
+ networkRecords.forEach(record => {
77
+ if (IGNORED_MIME_TYPES_REGEX.test(record.mimeType)) return;
78
+ if (record.sessionTargetType === 'worker') return;
79
+
80
+ // Network record requestIds can be duplicated for an unknown reason
81
+ // Suffix all subsequent records with `:duplicate` until it's unique
82
+ // NOTE: This should never happen with modern NetworkRequest library, but old fixtures
83
+ // might still have this issue.
84
+ while (idToNodeMap.has(record.requestId)) {
85
+ record.requestId += ':duplicate';
86
+ }
87
+
88
+ const node = new NetworkNode(record);
89
+ nodes.push(node);
90
+
91
+ const urlList = urlToNodeMap.get(record.url) || [];
92
+ urlList.push(node);
93
+
94
+ idToNodeMap.set(record.requestId, node);
95
+ urlToNodeMap.set(record.url, urlList);
96
+
97
+ // If the request was for the root document of an iframe, save an entry in our
98
+ // map so we can link up the task `args.data.frame` dependencies later in graph creation.
99
+ if (record.frameId &&
100
+ record.resourceType === NetworkRequestTypes.Document &&
101
+ record.documentURL === record.url) {
102
+ // If there's ever any ambiguity, permanently set the value to `false` to avoid loops in the graph.
103
+ const value = frameIdToNodeMap.has(record.frameId) ? null : node;
104
+ frameIdToNodeMap.set(record.frameId, value);
105
+ }
106
+ });
107
+
108
+ return {nodes, idToNodeMap, urlToNodeMap, frameIdToNodeMap};
109
+ }
110
+
111
+ /**
112
+ * @param {LH.Artifacts.ProcessedTrace} processedTrace
113
+ * @return {Array<CPUNode>}
114
+ */
115
+ static getCPUNodes({mainThreadEvents}) {
116
+ /** @type {Array<CPUNode>} */
117
+ const nodes = [];
118
+ let i = 0;
119
+
120
+ TraceProcessor.assertHasToplevelEvents(mainThreadEvents);
121
+
122
+ while (i < mainThreadEvents.length) {
123
+ const evt = mainThreadEvents[i];
124
+ i++;
125
+
126
+ // Skip all trace events that aren't schedulable tasks with sizable duration
127
+ if (!TraceProcessor.isScheduleableTask(evt) || !evt.dur) {
128
+ continue;
129
+ }
130
+
131
+ // Capture all events that occurred within the task
132
+ /** @type {Array<LH.TraceEvent>} */
133
+ const children = [];
134
+ for (
135
+ const endTime = evt.ts + evt.dur;
136
+ i < mainThreadEvents.length && mainThreadEvents[i].ts < endTime;
137
+ i++
138
+ ) {
139
+ children.push(mainThreadEvents[i]);
140
+ }
141
+
142
+ nodes.push(new CPUNode(evt, children));
143
+ }
144
+
145
+ return nodes;
146
+ }
147
+
148
+ /**
149
+ * @param {NetworkNode} rootNode
150
+ * @param {NetworkNodeOutput} networkNodeOutput
151
+ */
152
+ static linkNetworkNodes(rootNode, networkNodeOutput) {
153
+ networkNodeOutput.nodes.forEach(node => {
154
+ const directInitiatorRequest = node.request.initiatorRequest || rootNode.request;
155
+ const directInitiatorNode =
156
+ networkNodeOutput.idToNodeMap.get(directInitiatorRequest.requestId) || rootNode;
157
+ const canDependOnInitiator =
158
+ !directInitiatorNode.isDependentOn(node) &&
159
+ node.canDependOn(directInitiatorNode);
160
+ const initiators = PageDependencyGraph.getNetworkInitiators(node.request);
161
+ if (initiators.length) {
162
+ initiators.forEach(initiator => {
163
+ const parentCandidates = networkNodeOutput.urlToNodeMap.get(initiator) || [];
164
+ // Only add the edge if the parent is unambiguous with valid timing and isn't circular.
165
+ if (parentCandidates.length === 1 &&
166
+ parentCandidates[0].startTime <= node.startTime &&
167
+ !parentCandidates[0].isDependentOn(node)) {
168
+ node.addDependency(parentCandidates[0]);
169
+ } else if (canDependOnInitiator) {
170
+ directInitiatorNode.addDependent(node);
171
+ }
172
+ });
173
+ } else if (canDependOnInitiator) {
174
+ directInitiatorNode.addDependent(node);
175
+ }
176
+
177
+ // Make sure the nodes are attached to the graph if the initiator information was invalid.
178
+ if (node !== rootNode && node.getDependencies().length === 0 && node.canDependOn(rootNode)) {
179
+ node.addDependency(rootNode);
180
+ }
181
+
182
+ if (!node.request.redirects) return;
183
+
184
+ const redirects = [...node.request.redirects, node.request];
185
+ for (let i = 1; i < redirects.length; i++) {
186
+ const redirectNode = networkNodeOutput.idToNodeMap.get(redirects[i - 1].requestId);
187
+ const actualNode = networkNodeOutput.idToNodeMap.get(redirects[i].requestId);
188
+ if (actualNode && redirectNode) {
189
+ actualNode.addDependency(redirectNode);
190
+ }
191
+ }
192
+ });
193
+ }
194
+
195
+ /**
196
+ * @param {Node} rootNode
197
+ * @param {NetworkNodeOutput} networkNodeOutput
198
+ * @param {Array<CPUNode>} cpuNodes
199
+ */
200
+ static linkCPUNodes(rootNode, networkNodeOutput, cpuNodes) {
201
+ /** @type {Set<LH.Crdp.Network.ResourceType|undefined>} */
202
+ const linkableResourceTypes = new Set([
203
+ NetworkRequestTypes.XHR, NetworkRequestTypes.Fetch, NetworkRequestTypes.Script,
204
+ ]);
205
+
206
+ /** @param {CPUNode} cpuNode @param {string} reqId */
207
+ function addDependentNetworkRequest(cpuNode, reqId) {
208
+ const networkNode = networkNodeOutput.idToNodeMap.get(reqId);
209
+ if (!networkNode ||
210
+ // Ignore all network nodes that started before this CPU task started
211
+ // A network request that started earlier could not possibly have been started by this task
212
+ networkNode.startTime <= cpuNode.startTime) return;
213
+ const {request} = networkNode;
214
+ const resourceType = request.resourceType ||
215
+ request.redirectDestination?.resourceType;
216
+ if (!linkableResourceTypes.has(resourceType)) {
217
+ // We only link some resources to CPU nodes because we observe LCP simulation
218
+ // regressions when including images, etc.
219
+ return;
220
+ }
221
+ cpuNode.addDependent(networkNode);
222
+ }
223
+
224
+ /**
225
+ * If the node has an associated frameId, then create a dependency on the root document request
226
+ * for the frame. The task obviously couldn't have started before the frame was even downloaded.
227
+ *
228
+ * @param {CPUNode} cpuNode
229
+ * @param {string|undefined} frameId
230
+ */
231
+ function addDependencyOnFrame(cpuNode, frameId) {
232
+ if (!frameId) return;
233
+ const networkNode = networkNodeOutput.frameIdToNodeMap.get(frameId);
234
+ if (!networkNode) return;
235
+ // Ignore all network nodes that started after this CPU task started
236
+ // A network request that started after could not possibly be required this task
237
+ if (networkNode.startTime >= cpuNode.startTime) return;
238
+ cpuNode.addDependency(networkNode);
239
+ }
240
+
241
+ /** @param {CPUNode} cpuNode @param {string} url */
242
+ function addDependencyOnUrl(cpuNode, url) {
243
+ if (!url) return;
244
+ // Allow network requests that end up to 100ms before the task started
245
+ // Some script evaluations can start before the script finishes downloading
246
+ const minimumAllowableTimeSinceNetworkNodeEnd = -100 * 1000;
247
+ const candidates = networkNodeOutput.urlToNodeMap.get(url) || [];
248
+
249
+ let minCandidate = null;
250
+ let minDistance = Infinity;
251
+ // Find the closest request that finished before this CPU task started
252
+ for (const candidate of candidates) {
253
+ // Explicitly ignore all requests that started after this CPU node
254
+ // A network request that started after this task started cannot possibly be a dependency
255
+ if (cpuNode.startTime <= candidate.startTime) return;
256
+
257
+ const distance = cpuNode.startTime - candidate.endTime;
258
+ if (distance >= minimumAllowableTimeSinceNetworkNodeEnd && distance < minDistance) {
259
+ minCandidate = candidate;
260
+ minDistance = distance;
261
+ }
262
+ }
263
+
264
+ if (!minCandidate) return;
265
+ cpuNode.addDependency(minCandidate);
266
+ }
267
+
268
+ /** @type {Map<string, CPUNode>} */
269
+ const timers = new Map();
270
+ for (const node of cpuNodes) {
271
+ for (const evt of node.childEvents) {
272
+ if (!evt.args.data) continue;
273
+
274
+ const argsUrl = evt.args.data.url;
275
+ const stackTraceUrls = (evt.args.data.stackTrace || []).map(l => l.url).filter(Boolean);
276
+
277
+ switch (evt.name) {
278
+ case 'TimerInstall':
279
+ // @ts-expect-error - 'TimerInstall' event means timerId exists.
280
+ timers.set(evt.args.data.timerId, node);
281
+ stackTraceUrls.forEach(url => addDependencyOnUrl(node, url));
282
+ break;
283
+ case 'TimerFire': {
284
+ // @ts-expect-error - 'TimerFire' event means timerId exists.
285
+ const installer = timers.get(evt.args.data.timerId);
286
+ if (!installer || installer.endTime > node.startTime) break;
287
+ installer.addDependent(node);
288
+ break;
289
+ }
290
+
291
+ case 'InvalidateLayout':
292
+ case 'ScheduleStyleRecalculation':
293
+ addDependencyOnFrame(node, evt.args.data.frame);
294
+ stackTraceUrls.forEach(url => addDependencyOnUrl(node, url));
295
+ break;
296
+
297
+ case 'EvaluateScript':
298
+ addDependencyOnFrame(node, evt.args.data.frame);
299
+ // @ts-expect-error - 'EvaluateScript' event means argsUrl is defined.
300
+ addDependencyOnUrl(node, argsUrl);
301
+ stackTraceUrls.forEach(url => addDependencyOnUrl(node, url));
302
+ break;
303
+
304
+ case 'XHRReadyStateChange':
305
+ // Only create the dependency if the request was completed
306
+ // 'XHRReadyStateChange' event means readyState is defined.
307
+ if (evt.args.data.readyState !== 4) break;
308
+
309
+ // @ts-expect-error - 'XHRReadyStateChange' event means argsUrl is defined.
310
+ addDependencyOnUrl(node, argsUrl);
311
+ stackTraceUrls.forEach(url => addDependencyOnUrl(node, url));
312
+ break;
313
+
314
+ case 'FunctionCall':
315
+ case 'v8.compile':
316
+ addDependencyOnFrame(node, evt.args.data.frame);
317
+ // @ts-expect-error - events mean argsUrl is defined.
318
+ addDependencyOnUrl(node, argsUrl);
319
+ break;
320
+
321
+ case 'ParseAuthorStyleSheet':
322
+ addDependencyOnFrame(node, evt.args.data.frame);
323
+ // @ts-expect-error - 'ParseAuthorStyleSheet' event means styleSheetUrl is defined.
324
+ addDependencyOnUrl(node, evt.args.data.styleSheetUrl);
325
+ break;
326
+
327
+ case 'ResourceSendRequest':
328
+ addDependencyOnFrame(node, evt.args.data.frame);
329
+ // @ts-expect-error - 'ResourceSendRequest' event means requestId is defined.
330
+ addDependentNetworkRequest(node, evt.args.data.requestId);
331
+ stackTraceUrls.forEach(url => addDependencyOnUrl(node, url));
332
+ break;
333
+ }
334
+ }
335
+
336
+ // Nodes starting before the root node cannot depend on it.
337
+ if (node.getNumberOfDependencies() === 0 && node.canDependOn(rootNode)) {
338
+ node.addDependency(rootNode);
339
+ }
340
+ }
341
+
342
+ // Second pass to prune the graph of short tasks.
343
+ const minimumEvtDur = SIGNIFICANT_DUR_THRESHOLD_MS * 1000;
344
+ let foundFirstLayout = false;
345
+ let foundFirstPaint = false;
346
+ let foundFirstParse = false;
347
+
348
+ for (const node of cpuNodes) {
349
+ // Don't prune if event is the first ParseHTML/Layout/Paint.
350
+ // See https://github.com/GoogleChrome/lighthouse/issues/9627#issuecomment-526699524 for more.
351
+ let isFirst = false;
352
+ if (!foundFirstLayout && node.childEvents.some(evt => evt.name === 'Layout')) {
353
+ isFirst = foundFirstLayout = true;
354
+ }
355
+ if (!foundFirstPaint && node.childEvents.some(evt => evt.name === 'Paint')) {
356
+ isFirst = foundFirstPaint = true;
357
+ }
358
+ if (!foundFirstParse && node.childEvents.some(evt => evt.name === 'ParseHTML')) {
359
+ isFirst = foundFirstParse = true;
360
+ }
361
+
362
+ if (isFirst || node.event.dur >= minimumEvtDur) {
363
+ // Don't prune this node. The task is long / important so it will impact simulation.
364
+ continue;
365
+ }
366
+
367
+ // Prune the node if it isn't highly connected to minimize graph size. Rewiring the graph
368
+ // here replaces O(M + N) edges with (M * N) edges, which is fine if either M or N is at
369
+ // most 1.
370
+ if (node.getNumberOfDependencies() === 1 || node.getNumberOfDependents() <= 1) {
371
+ PageDependencyGraph._pruneNode(node);
372
+ }
373
+ }
374
+ }
375
+
376
+ /**
377
+ * Removes the given node from the graph, but retains all paths between its dependencies and
378
+ * dependents.
379
+ * @param {Node} node
380
+ */
381
+ static _pruneNode(node) {
382
+ const dependencies = node.getDependencies();
383
+ const dependents = node.getDependents();
384
+ for (const dependency of dependencies) {
385
+ node.removeDependency(dependency);
386
+ for (const dependent of dependents) {
387
+ dependency.addDependent(dependent);
388
+ }
389
+ }
390
+ for (const dependent of dependents) {
391
+ node.removeDependent(dependent);
392
+ }
393
+ }
394
+
395
+ /**
396
+ * @param {LH.Artifacts.ProcessedTrace} processedTrace
397
+ * @param {Array<NetworkRequest>} networkRecords
398
+ * @param {URLArtifact} URL
399
+ * @return {Node}
400
+ */
401
+ static createGraph(processedTrace, networkRecords, URL) {
402
+ const networkNodeOutput = PageDependencyGraph.getNetworkNodeOutput(networkRecords);
403
+ const cpuNodes = PageDependencyGraph.getCPUNodes(processedTrace);
404
+ const {requestedUrl, mainDocumentUrl} = URL;
405
+ if (!requestedUrl) throw new Error('requestedUrl is required to get the root request');
406
+ if (!mainDocumentUrl) throw new Error('mainDocumentUrl is required to get the main resource');
407
+
408
+ const rootRequest = NetworkAnalyzer.findResourceForUrl(networkRecords, requestedUrl);
409
+ if (!rootRequest) throw new Error('rootRequest not found');
410
+ const rootNode = networkNodeOutput.idToNodeMap.get(rootRequest.requestId);
411
+ if (!rootNode) throw new Error('rootNode not found');
412
+
413
+ const mainDocumentRequest =
414
+ NetworkAnalyzer.findLastDocumentForUrl(networkRecords, mainDocumentUrl);
415
+ if (!mainDocumentRequest) throw new Error('mainDocumentRequest not found');
416
+ const mainDocumentNode = networkNodeOutput.idToNodeMap.get(mainDocumentRequest.requestId);
417
+ if (!mainDocumentNode) throw new Error('mainDocumentNode not found');
418
+
419
+ PageDependencyGraph.linkNetworkNodes(rootNode, networkNodeOutput);
420
+ PageDependencyGraph.linkCPUNodes(rootNode, networkNodeOutput, cpuNodes);
421
+ mainDocumentNode.setIsMainDocument(true);
422
+
423
+ if (NetworkNode.hasCycle(rootNode)) {
424
+ throw new Error('Invalid dependency graph created, cycle detected');
425
+ }
426
+
427
+ return rootNode;
428
+ }
429
+
430
+ /**
431
+ *
432
+ * @param {Node} rootNode
433
+ */
434
+ static printGraph(rootNode, widthInCharacters = 100) {
435
+ /** @param {string} str @param {number} target */
436
+ function padRight(str, target, padChar = ' ') {
437
+ return str + padChar.repeat(Math.max(target - str.length, 0));
438
+ }
439
+
440
+ /** @type {Array<Node>} */
441
+ const nodes = [];
442
+ rootNode.traverse(node => nodes.push(node));
443
+ nodes.sort((a, b) => a.startTime - b.startTime);
444
+
445
+ const min = nodes[0].startTime;
446
+ const max = nodes.reduce((max, node) => Math.max(max, node.endTime), 0);
447
+
448
+ const totalTime = max - min;
449
+ const timePerCharacter = totalTime / widthInCharacters;
450
+ nodes.forEach(node => {
451
+ const offset = Math.round((node.startTime - min) / timePerCharacter);
452
+ const length = Math.ceil((node.endTime - node.startTime) / timePerCharacter);
453
+ const bar = padRight('', offset) + padRight('', length, '=');
454
+
455
+ // @ts-expect-error -- disambiguate displayName from across possible Node types.
456
+ const displayName = node.request ? node.request.url : node.type;
457
+ // eslint-disable-next-line
458
+ console.log(padRight(bar, widthInCharacters), `| ${displayName.slice(0, 30)}`);
459
+ });
460
+ }
461
+ }
462
+
463
+ export {PageDependencyGraph};
@@ -1,15 +1,15 @@
1
1
  export class ConnectionPool {
2
2
  /**
3
- * @param {Lantern.NetworkRequest[]} records
4
- * @param {Required<LH.Gatherer.Simulation.Options>} options
3
+ * @param {NetworkRequest[]} records
4
+ * @param {Required<SimulationOptions>} options
5
5
  */
6
- constructor(records: import("../../../../types/internal/lantern.js").NetworkRequest<any>[], options: Required<LH.Gatherer.Simulation.Options>);
7
- _options: Required<LH.Gatherer.Simulation.Options>;
8
- _records: import("../../../../types/internal/lantern.js").NetworkRequest<any>[];
6
+ constructor(records: NetworkRequest[], options: Required<SimulationOptions>);
7
+ _options: Required<import("../../../../types/internal/lantern.js").Lantern.Simulation.Options>;
8
+ _records: import("../../../../types/internal/lantern.js").Lantern.NetworkRequest<any>[];
9
9
  /** @type {Map<string, TcpConnection[]>} */
10
10
  _connectionsByOrigin: Map<string, TcpConnection[]>;
11
- /** @type {Map<Lantern.NetworkRequest, TcpConnection>} */
12
- _connectionsByRecord: Map<import("../../../../types/internal/lantern.js").NetworkRequest<any>, TcpConnection>;
11
+ /** @type {Map<NetworkRequest, TcpConnection>} */
12
+ _connectionsByRecord: Map<NetworkRequest, TcpConnection>;
13
13
  _connectionsInUse: Set<any>;
14
14
  _connectionReusedByRequestId: Map<string, boolean>;
15
15
  /**
@@ -33,26 +33,27 @@ export class ConnectionPool {
33
33
  * If ignoreConnectionReused is true, acquire will consider all connections not in use as available.
34
34
  * Otherwise, only connections that have matching "warmth" are considered available.
35
35
  *
36
- * @param {Lantern.NetworkRequest} record
36
+ * @param {NetworkRequest} record
37
37
  * @param {{ignoreConnectionReused?: boolean}} options
38
38
  * @return {?TcpConnection}
39
39
  */
40
- acquire(record: import("../../../../types/internal/lantern.js").NetworkRequest<any>, options?: {
40
+ acquire(record: NetworkRequest, options?: {
41
41
  ignoreConnectionReused?: boolean;
42
42
  }): TcpConnection | null;
43
43
  /**
44
44
  * Return the connection currently being used to fetch a record. If no connection
45
45
  * currently being used for this record, an error will be thrown.
46
46
  *
47
- * @param {Lantern.NetworkRequest} record
47
+ * @param {NetworkRequest} record
48
48
  * @return {TcpConnection}
49
49
  */
50
- acquireActiveConnectionFromRecord(record: import("../../../../types/internal/lantern.js").NetworkRequest<any>): TcpConnection;
50
+ acquireActiveConnectionFromRecord(record: NetworkRequest): TcpConnection;
51
51
  /**
52
- * @param {Lantern.NetworkRequest} record
52
+ * @param {NetworkRequest} record
53
53
  */
54
- release(record: import("../../../../types/internal/lantern.js").NetworkRequest<any>): void;
54
+ release(record: NetworkRequest): void;
55
55
  }
56
- import * as LH from '../../../../types/lh.js';
56
+ export type NetworkRequest = import('../../../../types/internal/lantern.js').Lantern.NetworkRequest;
57
+ export type SimulationOptions = import('../../../../types/internal/lantern.js').Lantern.Simulation.Options;
57
58
  import { TcpConnection } from './tcp-connection.js';
58
59
  //# sourceMappingURL=connection-pool.d.ts.map
@@ -4,8 +4,9 @@
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
6
 
7
- import * as LH from '../../../../types/lh.js';
8
- import * as Lantern from '../lantern.js';
7
+ /** @typedef {import('../../../../types/internal/lantern.js').Lantern.NetworkRequest} NetworkRequest */
8
+ /** @typedef {import('../../../../types/internal/lantern.js').Lantern.Simulation.Options} SimulationOptions */
9
+
9
10
  import {NetworkAnalyzer} from './network-analyzer.js';
10
11
  import {TcpConnection} from './tcp-connection.js';
11
12
 
@@ -18,8 +19,8 @@ const CONNECTIONS_PER_ORIGIN = 6;
18
19
 
19
20
  export class ConnectionPool {
20
21
  /**
21
- * @param {Lantern.NetworkRequest[]} records
22
- * @param {Required<LH.Gatherer.Simulation.Options>} options
22
+ * @param {NetworkRequest[]} records
23
+ * @param {Required<SimulationOptions>} options
23
24
  */
24
25
  constructor(records, options) {
25
26
  this._options = options;
@@ -27,7 +28,7 @@ export class ConnectionPool {
27
28
  this._records = records;
28
29
  /** @type {Map<string, TcpConnection[]>} */
29
30
  this._connectionsByOrigin = new Map();
30
- /** @type {Map<Lantern.NetworkRequest, TcpConnection>} */
31
+ /** @type {Map<NetworkRequest, TcpConnection>} */
31
32
  this._connectionsByRecord = new Map();
32
33
  this._connectionsInUse = new Set();
33
34
  this._connectionReusedByRequestId = NetworkAnalyzer.estimateIfConnectionWasReused(records, {
@@ -125,7 +126,7 @@ export class ConnectionPool {
125
126
  * If ignoreConnectionReused is true, acquire will consider all connections not in use as available.
126
127
  * Otherwise, only connections that have matching "warmth" are considered available.
127
128
  *
128
- * @param {Lantern.NetworkRequest} record
129
+ * @param {NetworkRequest} record
129
130
  * @param {{ignoreConnectionReused?: boolean}} options
130
131
  * @return {?TcpConnection}
131
132
  */
@@ -151,7 +152,7 @@ export class ConnectionPool {
151
152
  * Return the connection currently being used to fetch a record. If no connection
152
153
  * currently being used for this record, an error will be thrown.
153
154
  *
154
- * @param {Lantern.NetworkRequest} record
155
+ * @param {NetworkRequest} record
155
156
  * @return {TcpConnection}
156
157
  */
157
158
  acquireActiveConnectionFromRecord(record) {
@@ -162,7 +163,7 @@ export class ConnectionPool {
162
163
  }
163
164
 
164
165
  /**
165
- * @param {Lantern.NetworkRequest} record
166
+ * @param {NetworkRequest} record
166
167
  */
167
168
  release(record) {
168
169
  const connection = this._connectionsByRecord.get(record);