forked from GoogleChrome/lighthouse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript-elements.js
161 lines (145 loc) · 5.65 KB
/
script-elements.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
/**
* @license Copyright 2017 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';
const FRGatherer = require('../../fraggle-rock/gather/base-gatherer.js');
const NetworkRecords = require('../../computed/network-records.js');
const NetworkAnalyzer = require('../../lib/dependency-graph/simulator/network-analyzer.js');
const NetworkRequest = require('../../lib/network-request.js');
const pageFunctions = require('../../lib/page-functions.js');
const {fetchResponseBodyFromCache} = require('../driver/network.js');
const DevtoolsLog = require('./devtools-log.js');
const HostFormFactor = require('./host-form-factor.js');
/* global getNodeDetails */
/**
* @return {LH.Artifacts['ScriptElements']}
*/
/* c8 ignore start */
function collectAllScriptElements() {
/** @type {HTMLScriptElement[]} */
// @ts-expect-error - getElementsInDocument put into scope via stringification
const scripts = getElementsInDocument('script'); // eslint-disable-line no-undef
return scripts.map(script => {
return {
type: script.type || null,
src: script.src || null,
id: script.id || null,
async: script.async,
defer: script.defer,
source: script.closest('head') ? 'head' : 'body',
content: script.src ? null : script.text,
requestId: null,
// @ts-expect-error - getNodeDetails put into scope via stringification
node: getNodeDetails(script),
};
});
}
/* c8 ignore stop */
/**
* @template T, U
* @param {Array<T>} values
* @param {(value: T) => Promise<U>} promiseMapper
* @param {boolean} runInSeries
* @return {Promise<Array<U>>}
*/
async function runInSeriesOrParallel(values, promiseMapper, runInSeries) {
if (runInSeries) {
const results = [];
for (const value of values) {
const result = await promiseMapper(value);
results.push(result);
}
return results;
} else {
const promises = values.map(promiseMapper);
return await Promise.all(promises);
}
}
/**
* @fileoverview Gets JavaScript file contents.
*/
class ScriptElements extends FRGatherer {
/** @type {LH.Gatherer.GathererMeta<'DevtoolsLog'|'HostFormFactor'>} */
meta = {
supportedModes: ['timespan', 'navigation'],
dependencies: {DevtoolsLog: DevtoolsLog.symbol, HostFormFactor: HostFormFactor.symbol},
}
/**
* @param {LH.Gatherer.FRTransitionalContext} context
* @param {LH.Artifacts.NetworkRequest[]} networkRecords
* @param {LH.Artifacts['HostFormFactor']} formFactor
* @return {Promise<LH.Artifacts['ScriptElements']>}
*/
async _getArtifact(context, networkRecords, formFactor) {
const session = context.driver.defaultSession;
const executionContext = context.driver.executionContext;
const mainResource = NetworkAnalyzer.findMainDocument(networkRecords, context.url);
const scripts = await executionContext.evaluate(collectAllScriptElements, {
args: [],
useIsolation: true,
deps: [
pageFunctions.getNodeDetailsString,
pageFunctions.getElementsInDocument,
],
});
for (const script of scripts) {
if (script.content) script.requestId = mainResource.requestId;
}
const scriptRecords = networkRecords
// Ignore records from OOPIFs
.filter(record => !record.sessionId)
// Only get the content of script requests
.filter(record => record.resourceType === NetworkRequest.TYPES.Script);
// If run on a mobile device, be sensitive to memory limitations and only request one
// record at a time.
const scriptRecordContents = await runInSeriesOrParallel(
scriptRecords,
record => fetchResponseBodyFromCache(session, record.requestId).catch(() => ''),
formFactor === 'mobile' /* runInSeries */
);
for (let i = 0; i < scriptRecords.length; i++) {
const record = scriptRecords[i];
const content = scriptRecordContents[i];
if (!content) continue;
const matchedScriptElement = scripts.find(script => script.src === record.url);
if (matchedScriptElement) {
matchedScriptElement.requestId = record.requestId;
matchedScriptElement.content = content;
} else {
scripts.push({
type: null,
src: record.url,
id: null,
async: false,
defer: false,
source: 'network',
requestId: record.requestId,
content,
node: null,
});
}
}
return scripts;
}
/**
* @param {LH.Gatherer.FRTransitionalContext<'DevtoolsLog'|'HostFormFactor'>} context
*/
async getArtifact(context) {
const devtoolsLog = context.dependencies.DevtoolsLog;
const formFactor = context.dependencies.HostFormFactor;
const networkRecords = await NetworkRecords.request(devtoolsLog, context);
return this._getArtifact(context, networkRecords, formFactor);
}
/**
* @param {LH.Gatherer.PassContext} passContext
* @param {LH.Gatherer.LoadData} loadData
*/
async afterPass(passContext, loadData) {
const networkRecords = loadData.networkRecords;
const formFactor = passContext.baseArtifacts.HostFormFactor;
return this._getArtifact({...passContext, dependencies: {}}, networkRecords, formFactor);
}
}
module.exports = ScriptElements;