-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
368 lines (327 loc) · 9.52 KB
/
index.js
File metadata and controls
368 lines (327 loc) · 9.52 KB
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
/**
* @file Main for rendering pages of a website as HTML via
* either sitemaps or lists of URLs. Arguments come in via
* environment variables, either set up in the CodeBuild
* project or passed in via an AWS CodeBuild API call via the
* environmentVariablesOverride parameter.
*/
const pptr = require('puppeteer');
const Sitemapper = require('sitemapper').default;
const sitemapper = new Sitemapper({});
const fs = require('fs');
const path = require('path');
const events = require('events');
const crypto = require('crypto');
const zlib = require('zlib');
const { promisify } = require('util');
const URL = require('url').URL;
const dotenv = require('dotenv');
const inliner = require('inline-css');
const version = JSON.parse(
fs.readFileSync(path.join(__dirname, 'package.json'), 'utf-8')
).version;
dotenv.config();
const startTime = new Date();
function debug(...args) {
if (process.env.DEBUG == 'true') {
console.log(...args);
}
}
function info(...args) {
console.log(...args);
}
info({ version });
const gzip = promisify(zlib.gzip);
const outDir = 'rendered';
const emitter = new events.EventEmitter();
const report = {
pagesRendered: 0,
secondsRequired: 0,
totalRequests: 0,
blockedRequests: 0,
cachedRequests: 0,
uncachedRequests: 0,
};
/**
* @param {number} ms
*/
async function wait(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
function computeInlineScriptHashes(html) {
const scripts = html.match(/<script>(.*?)<\/script>/gs);
if (!scripts) {
return [];
}
const hashes = [];
for (const script of scripts) {
const hash = crypto
.createHash('sha256')
.update(script.replace(/<\/?script>/g, ''), 'utf8')
.digest('base64');
hashes.push(hash);
}
return hashes;
}
/**
* @param {Parameters} params
* @param {string} url
* @param {string} html
*/
async function writeRenderedPage(params, url, html) {
if (!html) {
return emitter.emit('saved', { url });
}
let fullPath = path.join(
outDir,
params.outFolder,
url.replace(new URL(url).origin, '')
);
if (!fullPath.endsWith('.html')) {
fullPath = path.join(fullPath, 'index.html');
}
if (params.gzip) {
fullPath += '.gz';
}
if (process.env.INLINE_CSS == 'true') {
html = await inliner(html, {
url: new URL(url).origin,
removeLinkTags: false,
applyLinkTags: false,
applyStyleTags: true,
removeStyleTags: true,
preserveMediaQueries: true,
});
}
const dir = path.dirname(fullPath);
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(fullPath, params.gzip ? await gzip(html) : html);
if (params.computeScriptHashes) {
const metadataPath = fullPath.replace(/\.html(\.gz)?$/, '.json');
if (metadataPath.endsWith('json')) {
const hashes = computeInlineScriptHashes(html);
const metadataJson = JSON.stringify({ scriptHashes: hashes });
fs.writeFileSync(metadataPath, metadataJson);
}
}
emitter.emit('saved', { url });
}
/**
* @typedef {ReturnType<getParameters>} Parameters
* @returns {asserts somethingTruthy}
*/
function assert(somethingTruthy, messageIfFalse) {
if (!somethingTruthy) {
throw new Error(messageIfFalse);
}
}
function ensureSlashPrefix(path) {
return path.startsWith('/') ? path : `/${path}`;
}
function toCsv(string) {
return (string || '').split(/\s*,\s*/g).filter((x) => x);
}
function getParameters() {
// SITEMAP_PATH
const sitemapPath = process.env.SITEMAP_PATH;
// BLOCK_PATTERNS
const blockPatterns = toCsv(process.env.BLOCK_PATTERNS).map(
(p) => new RegExp(p)
);
// BLOCK_HOSTS
const blockHosts = toCsv(process.env.BLOCK_HOSTS);
// PATHS
const paths = toCsv(process.env.PATHS);
assert(
(sitemapPath && new URL(sitemapPath)) || paths.length,
'Sitemap path or paths list must be provided.'
);
// OUT_FOLDER
const outFolder = ensureSlashPrefix(process.env.OUT_FOLDER || '');
// HEADERS
const headers = (process.env.HEADERS || '')
.split(/\s*,\s*/g)
.filter((x) => x)
.reduce((head, current) => {
const [key, value] = current.split(/\s*:\s*/).map((s) => s.trim());
head[key] = value;
return head;
}, {});
return {
sitemapPath,
paths,
outFolder,
headers,
blockPatterns,
blockHosts,
computeScriptHashes: process.env.COMPUTE_SCRIPT_HASHES == 'true',
gzip: process.env.GZIP == 'true',
};
}
/**
* @param {Parameters} parameters
*/
async function getPaths(parameters) {
const urls = [...parameters.paths];
if (parameters.sitemapPath) {
// Download it!
const { sites } = await sitemapper.fetch(parameters.sitemapPath);
urls.push(...sites);
}
return urls;
}
const maxSynchronous = process.env.MAX_SYNCHRONOUS || 50;
/**
* @param {import('puppeteer').Browser} browser
* @param {Parameters} params
* @param {string} url
*/
async function fetchPage(browser, params, url) {
let html;
const page = await browser.newPage();
try {
const fullUrl = url;
// No reason to download images or fonts, since we just want the resulting HTML
await page.setExtraHTTPHeaders(params.headers);
await page.setRequestInterception(true, true);
page.on(
'request',
/** @param {pptr.HTTPRequest} request */
async (request) => {
const requestUrl = new URL(request.url());
report.totalRequests++;
debug('REQUESTED on', url, request.url());
try {
const typeAllowlist = [
'document',
'stylesheet',
'script',
'xhr',
'fetch',
];
const extensionAllowlist = ['js', 'css']; // are 'other' type if prefetch
const extensionBlocklist = ['woff2'];
const isAllowedMethod = ['get', 'head', 'options'].includes(
request.method().toLowerCase()
);
const isBlocked =
!isAllowedMethod ||
params.blockPatterns.some((p) => p.test(request.url())) ||
requestUrl.pathname.match(
new RegExp(`\\.(${extensionBlocklist.join('|')})$`)
) ||
params.blockHosts.includes(requestUrl.host);
const isAllowed =
!isBlocked &&
(typeAllowlist.includes(request.resourceType()) ||
requestUrl.pathname.match(
new RegExp(`\\.(${extensionAllowlist.join('|')})$`)
));
if (isAllowed && !isBlocked) {
await request.continue();
} else {
report.blockedRequests++;
if (isBlocked) {
debug('BLOCKED on', url, request.url());
}
await request.abort();
}
} catch (err) {
console.error('INTERCEPT ERROR', err);
}
}
);
page.on('requestfinished', (e) => {
if (e.response().fromCache()) {
report.cachedRequests++;
} else {
report.uncachedRequests++;
}
debug('CACHED?', e.response().fromCache(), e.url());
});
// Instead of potentially waiting forever, resolve once most requests
// are resolved and the wait another couple seconds
page.on('console', (msg) => {
if (msg?.text() == 'JSHandle@error') {
console.error('Error (console) on', url);
console.error(msg.args?.()?.[0]?._remoteObject?.description);
}
});
const response = await page.goto(fullUrl, { waitUntil: 'networkidle0' });
const selector = process.env.WAIT_FOR_SELECTOR;
const waitMs = Number(process.env.WAIT_MILLISECONDS);
if (selector) {
debug('Waiting for selector', selector);
await page.waitForSelector(selector);
}
if (waitMs) {
await wait(Number(waitMs));
}
if (response.status() < 300) {
html = await page.content();
info('Success', url);
} else {
console.error('WARN', url, 'returned status', response.status());
}
} catch (err) {
console.error('Error', url);
console.error(err);
}
await page.close();
return html;
}
async function prerenderPaths() {
const params = getParameters();
const urls = await getPaths(params);
if (process.env.MAX_PAGES) {
urls.splice(Number(process.env.MAX_PAGES));
}
const browser = await pptr.launch({ args: ['--no-sandbox'] });
const failOnUncaughtError = (err) => {
browser.close();
console.error(err);
process.exit(1);
};
process.on('unhandledRejection', failOnUncaughtError);
process.on('uncaughtException', failOnUncaughtError);
// Ensure there are ALWAYS maxSynchronous in queue
// (each time one ends another one is added).
let pathPointer = -1; // Index of the last URL being pre-rendered
const renderNextUrl = () => {
pathPointer++;
if (pathPointer >= urls.length) {
emitter.emit('done');
}
const url = urls[pathPointer];
return (
pathPointer >= urls.length ||
fetchPage(browser, params, url)
.then((html) => writeRenderedPage(params, url, html))
.then(renderNextUrl)
);
};
// Fully wait for the first page to ensure common resources
// get cached.
renderNextUrl();
emitter.once('saved', () => {
debug(
'First page fully loaded and saved; cache populated with universal content.'
);
for (let i = 1; i < maxSynchronous; i++) {
renderNextUrl();
}
});
const rendered = [];
emitter.on('saved', (savedPage) => {
report.pagesRendered++;
rendered.push(savedPage.url);
if (rendered.length == urls.length) {
browser.close();
report.secondsRequired = (Date.now() - startTime.getTime()) / 1000;
info(JSON.stringify(report, null, 2));
}
});
}
prerenderPaths();