-
Notifications
You must be signed in to change notification settings - Fork 33
/
usus.js
315 lines (237 loc) · 7.75 KB
/
usus.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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
// @flow
import {
launch
} from 'chrome-launcher';
import CDP from 'chrome-remote-interface';
import createDebug from 'debug';
import surgeon from 'surgeon';
import {
delay
} from 'bluefeather';
import createConfiguration from './factories/createConfiguration';
import type {
UserConfigurationType
} from './types';
const debug = createDebug('usus');
export const launchChrome = () => {
return launch({
chromeFlags: [
'--disable-gpu',
'--headless'
]
});
};
const inlineStyles = async (DOM: *, Runtime: *, rootNodeId: number, styles: string) => {
// @todo I am sure there is a better way to do this,
// but I cannot find it documented in the https://chromedevtools.github.io/devtools-protocol/tot/DOM/
// e.g. How to create a new node using CDP DOM API?
await Runtime.evaluate({
expression: `
{
const styleElement = document.createElement('div');
styleElement.setAttribute('id', 'usus-inline-styles');
document.head.appendChild(styleElement);
}
`
});
const nodeId = (await DOM.querySelector({
nodeId: rootNodeId,
selector: '#usus-inline-styles'
})).nodeId;
debug('#usus-inline-styles nodeId %d', nodeId);
const stylesheet = `<style>${styles}</style>`;
await DOM.setOuterHTML({
nodeId,
outerHTML: stylesheet
});
};
const inlineImports = async (DOM: *, Runtime: *, rootNodeId: number, styleImports: $ReadOnlyArray<string>) => {
// @todo See note in inlineStyles.
await Runtime.evaluate({
expression: `
{
const scriptElement = document.createElement('div');
scriptElement.setAttribute('id', 'usus-style-import');
document.body.appendChild(scriptElement);
}
`
});
const nodeId = (await DOM.querySelector({
nodeId: rootNodeId,
selector: '#usus-style-import'
})).nodeId;
debug('#usus-style-import nodeId %d', nodeId);
await DOM.setOuterHTML({
nodeId,
outerHTML: styleImports.join('\n')
});
};
const inlineStylePreload = async (DOM: *, Runtime: *, rootNodeId: number, styleImports: $ReadOnlyArray<string>) => {
// @todo See note in inlineStyles.
await Runtime.evaluate({
expression: `
{
const scriptElement = document.createElement('div');
scriptElement.setAttribute('id', 'usus-style-preload');
document.head.appendChild(scriptElement);
}
`
});
const nodeId = (await DOM.querySelector({
nodeId: rootNodeId,
selector: '#usus-style-preload'
})).nodeId;
debug('#usus-style-preload nodeId %d', nodeId);
const x = surgeon();
const styleUrls = x('select link {0,} | read attribute href', styleImports.join(''));
const stylePreloadLinks = styleUrls
.map((styleUrl) => {
return `<link rel="preload" href="${styleUrl}" as="style">`;
});
await DOM.setOuterHTML({
nodeId,
outerHTML: stylePreloadLinks.join('\n')
});
};
export const render = async (url: string, userConfiguration: UserConfigurationType = {}): Promise<string> => {
const configuration = createConfiguration(userConfiguration);
debug('rendering URL %s', JSON.stringify(configuration));
let chrome;
let chromePort;
if (configuration.chromePort) {
debug('attempting to use the user provided instance of Chrome (port %d)', configuration.chromePort);
chromePort = configuration.chromePort;
} else {
chrome = await launchChrome();
chromePort = chrome.port;
}
const protocol = await CDP({
port: chromePort
});
const end = async (): Promise<void> => {
await protocol.close();
if (!chrome) {
return;
}
await chrome.kill();
};
const {
CSS,
DOM,
Emulation,
Page,
Runtime,
Network
} = protocol;
await DOM.enable();
await CSS.enable();
await Page.enable();
await Runtime.enable();
Emulation.setDeviceMetricsOverride(configuration.deviceMetricsOverride);
for (const cookie of configuration.cookies) {
Network.setCookie({
name: cookie.name,
url,
value: cookie.value
});
}
const inlineStylesheetIndex = [];
const alienFrameStylesheetIndex = [];
CSS.styleSheetAdded(({header}) => {
// eslint-disable-next-line no-use-before-define
const mainFrameId = frameId;
if (!mainFrameId) {
throw new Error('Stylesheet has been added before frameId has been established.');
}
if (header.frameId !== mainFrameId) {
alienFrameStylesheetIndex.push(header.styleSheetId);
}
if (header.isInline) {
inlineStylesheetIndex.push(header.styleSheetId);
}
});
await CSS.startRuleUsageTracking();
const frame = await Page.navigate({
url
});
const frameId = frame.frameId;
let usedStyles;
usedStyles = await new Promise((resolve) => {
Page.loadEventFired(async () => {
debug('"load" event received; waiting %d milliseconds before capturing the CSS coverage report', configuration.delay);
await delay(configuration.delay);
debug('alien stylesheets', inlineStylesheetIndex);
debug('inline stylesheets', inlineStylesheetIndex);
const rules = await CSS.takeCoverageDelta();
const usedRules = rules.coverage
.filter((rule) => {
return rule.used;
});
const slices = [];
for (const usedRule of usedRules) {
if (alienFrameStylesheetIndex.includes(usedRule.styleSheetId)) {
debug('skipping alien stylesheet %d', usedRule.styleSheetId);
// eslint-disable-next-line no-continue
continue;
}
if (inlineStylesheetIndex.includes(usedRule.styleSheetId)) {
debug('skipping inline stylesheet %d', usedRule.styleSheetId);
// eslint-disable-next-line no-continue
continue;
}
const stylesheet = await CSS.getStyleSheetText({
styleSheetId: usedRule.styleSheetId
});
slices.push(stylesheet.text.slice(usedRule.startOffset, usedRule.endOffset));
}
resolve(slices.join(''));
});
});
await CSS.stopRuleUsageTracking();
if (configuration.formatStyles) {
usedStyles = await configuration.formatStyles(usedStyles);
}
const rootDocument = await DOM.getDocument();
if (configuration.inlineStyles) {
const styleImportNodeIds = (await DOM.querySelectorAll({
nodeId: rootDocument.root.nodeId,
selector: 'head link[rel="stylesheet"]'
})).nodeIds;
debug('found %d style imports contained in the <head> element', styleImportNodeIds.length);
const styleImportLinks = [];
for (const styleImportNodeId of styleImportNodeIds) {
const styleImportNodeHtml = await DOM.getOuterHTML({
nodeId: styleImportNodeId
});
// @todo Add ability to conditionally allow certain nodes.
debug('found CSS import; removing import from the <head> element', styleImportNodeHtml);
await DOM.removeNode({
nodeId: styleImportNodeId
});
styleImportLinks.push(styleImportNodeHtml.outerHTML);
}
if (configuration.preloadStyles) {
await inlineStylePreload(DOM, Runtime, rootDocument.root.nodeId, styleImportLinks);
}
if (usedStyles) {
await inlineStyles(DOM, Runtime, rootDocument.root.nodeId, usedStyles);
}
await inlineImports(DOM, Runtime, rootDocument.root.nodeId, styleImportLinks);
const rootOuterHTMLWithInlinedStyles = (await DOM.getOuterHTML({
nodeId: rootDocument.root.nodeId
})).outerHTML;
await end();
return rootOuterHTMLWithInlinedStyles;
}
if (configuration.extractStyles) {
await end();
// @todo Document that `extractStyles` does not return the inline stylesheets.
// @todo Document that `extractStyles` does not return the alien stylesheets.
return usedStyles;
}
const rootOuterHTML = (await DOM.getOuterHTML({
nodeId: rootDocument.root.nodeId
})).outerHTML;
await end();
return rootOuterHTML;
};