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

new_audit: add script-treemap-data to experimental #11271

Merged
merged 30 commits into from
Oct 6, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
118e461
new_audit: add treemap-data to experimental
connorjclark Aug 15, 2020
c6bed57
remove execution time
connorjclark Aug 15, 2020
bc6c57c
comments
connorjclark Aug 15, 2020
32a5c37
rm script id
connorjclark Aug 15, 2020
4b60ca3
tweaks
connorjclark Aug 15, 2020
a2cfff5
Merge remote-tracking branch 'origin/master' into treemap-data
connorjclark Sep 25, 2020
e6b3eb6
first pass
connorjclark Sep 25, 2020
ac4e8a6
no scriptData
connorjclark Sep 25, 2020
b12967e
reverse ifs
connorjclark Sep 25, 2020
f811334
comments
connorjclark Sep 25, 2020
a39a444
fix case with no map or usage
connorjclark Sep 25, 2020
f28ef76
pr
connorjclark Sep 25, 2020
7008e55
load
connorjclark Sep 26, 2020
1eec2e5
minor test
connorjclark Sep 26, 2020
9c7e3a5
tests
connorjclark Sep 28, 2020
dca7c44
Merge remote-tracking branch 'origin/master' into treemap-data
connorjclark Oct 1, 2020
5d72ee9
pr
connorjclark Oct 1, 2020
8c05fc0
pr
connorjclark Oct 1, 2020
5976c3b
match object
connorjclark Oct 1, 2020
27137af
root node container
connorjclark Oct 1, 2020
1446910
rm resource summary
connorjclark Oct 1, 2020
97e548f
rename
connorjclark Oct 2, 2020
556aa87
update
connorjclark Oct 5, 2020
754ce53
update tests
connorjclark Oct 5, 2020
5e97161
deps: add @types/yargs-parser
connorjclark Oct 5, 2020
d878992
Merge branch 'deps-yargs-parser-types' into treemap-data
connorjclark Oct 5, 2020
bb028dd
Merge remote-tracking branch 'origin/master' into treemap-data
connorjclark Oct 5, 2020
c2d78f1
pr
connorjclark Oct 6, 2020
106e608
Merge remote-tracking branch 'origin/master' into treemap-data
connorjclark Oct 6, 2020
0eac4f6
fixtest
connorjclark Oct 6, 2020
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
264 changes: 264 additions & 0 deletions lighthouse-core/audits/script-treemap-data.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,264 @@
/**
* @license Copyright 2020 The Lighthouse Authors. All Rights Reserved.
* 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
* 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.
*/
'use strict';

/**
* @fileoverview
* Creates treemap data for treemap app.
*/

const Audit = require('./audit.js');
const JsBundles = require('../computed/js-bundles.js');
const UnusedJavaScriptSummary = require('../computed/unused-javascript-summary.js');
const ModuleDuplication = require('../computed/module-duplication.js');

/**
* @typedef {RootNodeContainer[]} TreemapData
*/

/**
* Ex: https://gist.github.com/connorjclark/0ef1099ae994c075e36d65fecb4d26a7
* @typedef RootNodeContainer
* @property {string} name Arbitrary name identifier. Usually a script url.
* @property {Node} node
*/

/**
* @typedef Node
* @property {string} name Arbitrary name identifier. Usually a path component from a source map.
* @property {number} resourceBytes
* @property {number=} unusedBytes
* @property {string=} duplicatedNormalizedModuleName If present, this module is a duplicate. String is normalized source path. See ModuleDuplication.normalizeSource
* @property {Node[]=} children
*/

/**
* @typedef {Omit<Node, 'name'|'children'>} SourceData
*/

class ScriptTreemapDataAudit extends Audit {
/**
* @return {LH.Audit.Meta}
*/
static get meta() {
return {
id: 'script-treemap-data',
scoreDisplayMode: Audit.SCORING_MODES.INFORMATIVE,
title: 'Script Treemap Data',
description: 'Used for treemap app',
requiredArtifacts:
['traces', 'devtoolsLogs', 'SourceMaps', 'ScriptElements', 'JsUsage', 'URL'],
};
}

/**
* Returns a tree data structure where leaf nodes are sources (ie. real files from source tree)
* from a source map, and non-leaf nodes are directories. Leaf nodes have data
* for bytes, coverage, etc., when available, and non-leaf nodes have the
* same data as the sum of all descendant leaf nodes.
* @param {string} sourceRoot
* @param {Record<string, SourceData>} sourcesData
* @return {Node}
*/
static prepareTreemapNodes(sourceRoot, sourcesData) {
/**
* @param {string} name
* @return {Node}
*/
function newNode(name) {
return {
name,
resourceBytes: 0,
};
}

const topNode = newNode(sourceRoot);

/**
* Given a slash-delimited path, traverse the Node structure and increment
* the data provided for each node in the chain. Creates nodes as needed.
* Ex: path/to/file.js will find or create "path" on `node`, increment the data fields,
* and continue with "to", and so on.
* @param {string} source
* @param {SourceData} data
*/
function addAllNodesInSourcePath(source, data) {
let node = topNode;

// Apply the data to the topNode.
topNode.resourceBytes += data.resourceBytes;
if (data.unusedBytes) topNode.unusedBytes = (topNode.unusedBytes || 0) + data.unusedBytes;

// Strip off the shared root.
const sourcePathSegments = source.replace(sourceRoot, '').split(/\/+/);
sourcePathSegments.forEach((sourcePathSegment, i) => {
const isLeaf = i === sourcePathSegments.length - 1;

let child = node.children && node.children.find(child => child.name === sourcePathSegment);
if (!child) {
child = newNode(sourcePathSegment);
node.children = node.children || [];
node.children.push(child);
}
node = child;

// Now that we've found or created the next node in the path, apply the data.
node.resourceBytes += data.resourceBytes;
if (data.unusedBytes) node.unusedBytes = (node.unusedBytes || 0) + data.unusedBytes;

// Only leaf nodes might have duplication data.
if (isLeaf && data.duplicatedNormalizedModuleName !== undefined) {
node.duplicatedNormalizedModuleName = data.duplicatedNormalizedModuleName;
}
});
}

// For every source file, apply the data to all components
// of the source path, creating nodes as necessary.
for (const [source, data] of Object.entries(sourcesData)) {
addAllNodesInSourcePath(source, data);
}

/**
* Collapse nodes that have only one child.
* @param {Node} node
*/
function collapseAll(node) {
while (node.children && node.children.length === 1) {
node.name += '/' + node.children[0].name;
node.children = node.children[0].children;
}

if (node.children) {
for (const child of node.children) {
collapseAll(child);
}
}
}
collapseAll(topNode);

return topNode;
}

/**
* Returns root node containers where the first level of nodes are script URLs.
* If a script has a source map, that node will be set by prepareTreemapNodes.
* @param {LH.Artifacts} artifacts
* @param {LH.Audit.Context} context
* @return {Promise<TreemapData>}
*/
static async makeRootNodes(artifacts, context) {
/** @type {RootNodeContainer[]} */
const rootNodeContainers = [];

let inlineScriptLength = 0;
for (const scriptElement of artifacts.ScriptElements) {
// No src means script is inline.
// Combine these ScriptElements so that inline scripts show up as a single root node.
if (!scriptElement.src) {
inlineScriptLength += (scriptElement.content || '').length;
}
}
if (inlineScriptLength) {
const name = artifacts.URL.finalUrl;
rootNodeContainers.push({
name,
node: {
name,
resourceBytes: inlineScriptLength,
},
});
}

const bundles = await JsBundles.request(artifacts, context);
const duplicationByPath = await ModuleDuplication.request(artifacts, context);

for (const scriptElement of artifacts.ScriptElements) {
if (!scriptElement.src) continue;

const name = scriptElement.src;
const bundle = bundles.find(bundle => scriptElement.src === bundle.script.src);
const scriptCoverages = artifacts.JsUsage[scriptElement.src];
if (!bundle || !scriptCoverages) {
connorjclark marked this conversation as resolved.
Show resolved Hide resolved
// No bundle or coverage information, so simply make a single node
// detailing how big the script is.

rootNodeContainers.push({
name,
node: {
name,
resourceBytes: scriptElement.src.length,
},
});
continue;
}

const unusedJavascriptSummary = await UnusedJavaScriptSummary.request(
{url: scriptElement.src, scriptCoverages, bundle}, context);

/** @type {Node} */
Copy link
Member

Choose a reason for hiding this comment

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

nit: don't need this, tsc's got your back :)

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

This can change what line an error is reported on, and makes the error message less complex. You can see the difference by commenting out the name property and seeing how the error changes.

let node;
if (unusedJavascriptSummary.sourcesWastedBytes && !('errorMessage' in bundle.sizes)) {
// Create nodes for each module in a bundle.

/** @type {Record<string, SourceData>} */
const sourcesData = {};
for (const source of Object.keys(bundle.sizes.files)) {
/** @type {SourceData} */
const sourceData = {
resourceBytes: bundle.sizes.files[source],
unusedBytes: unusedJavascriptSummary.sourcesWastedBytes[source],
};

const key = ModuleDuplication.normalizeSource(source);
if (duplicationByPath.has(key)) sourceData.duplicatedNormalizedModuleName = key;

sourcesData[source] = sourceData;
}

node = this.prepareTreemapNodes(bundle.rawMap.sourceRoot || '', sourcesData);
} else {
// There was no source map for this script, so we can only produce a single node.

node = {
name,
resourceBytes: unusedJavascriptSummary.totalBytes,
unusedBytes: unusedJavascriptSummary.wastedBytes,
};
}

rootNodeContainers.push({
name,
node,
});
}

return rootNodeContainers;
}

/**
* @param {LH.Artifacts} artifacts
* @param {LH.Audit.Context} context
* @return {Promise<LH.Audit.Product>}
*/
static async audit(artifacts, context) {
const treemapData = await ScriptTreemapDataAudit.makeRootNodes(artifacts, context);

// TODO: when out of experimental should make a new detail type.
/** @type {LH.Audit.Details.DebugData} */
const details = {
type: 'debugdata',
treemapData,
};

return {
score: 1,
details,
};
}
}

module.exports = ScriptTreemapDataAudit;
4 changes: 2 additions & 2 deletions lighthouse-core/computed/module-duplication.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class ModuleDuplication {
/**
* @param {string} source
*/
static _normalizeSource(source) {
static normalizeSource(source) {
// Trim trailing question mark - b/c webpack.
source = source.replace(/\?$/, '');

Expand Down Expand Up @@ -103,7 +103,7 @@ class ModuleDuplication {
const sourceKey = (rawMap.sourceRoot || '') + rawMap.sources[i];
const sourceSize = sizes.files[sourceKey];
sourceDataArray.push({
source: ModuleDuplication._normalizeSource(rawMap.sources[i]),
source: ModuleDuplication.normalizeSource(rawMap.sources[i]),
resourceSize: sourceSize,
});
}
Expand Down
1 change: 1 addition & 0 deletions lighthouse-core/computed/resource-summary.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ class ResourceSummary {
* @return {Record<LH.Budget.ResourceType, ResourceEntry>}
*/
static summarize(networkRecords, mainResourceURL, context) {
/** @type {Record<LH.Budget.ResourceType, ResourceEntry>} */
const resourceSummary = {
'stylesheet': {count: 0, resourceSize: 0, transferSize: 0},
'image': {count: 0, resourceSize: 0, transferSize: 0},
Expand Down
1 change: 1 addition & 0 deletions lighthouse-core/config/experimental-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const config = {
'autocomplete',
'full-page-screenshot',
'large-javascript-libraries',
'script-treemap-data',
],
passes: [{
passName: 'defaultPass',
Expand Down
Loading