-
Notifications
You must be signed in to change notification settings - Fork 10
/
generate-h2-push.js
executable file
·85 lines (71 loc) · 2.2 KB
/
generate-h2-push.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
#!/usr/bin/env node
const puppeteer = require('puppeteer');
const fs = require('fs');
const args = process.argv.slice(2);
const host = args[0] || 'http://127.0.0.1:8080';
const indexMatches = [
'.gz',
'.map',
'3rdpartylicenses.txt',
'ngsw-manifest.json',
'ngsw.json',
'worker-basic.min.js',
'ngsw-worker.js',
'favicon',
'index.html',
'manifest.webmanifest',
'.svg'
];
let results = '';
async function main() {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page._client.send('ServiceWorker.disable')
page.on('console', msg => console.log(msg.text()));
console.log('Page: loaded');
await page.goto(host);
const allRequests = new Map();
page.on('request', req => {
allRequests.set(req.url(), req);
});
await page.reload({ waitUntil: 'networkidle2' });
Array.from(allRequests.values()).forEach(req => {
const url = req.url();
// filter out urls that match these extensions
for (const exlude of indexMatches) {
if (url.indexOf(exlude) != -1) return false;
}
// if external, dont worry about it for now
//
const origin = new URL(host);
if (url.indexOf(origin.origin) === -1) return false;
// Format the url to remove the host
const formatted = url.replace(`${origin.origin}/`, '');
if (origin.pathname.includes(formatted)) return false;
// if it's an empty string, just ignore it
if (!formatted) return false;
let type = url.substr(-3) == 'css' ? 'style' : 'script';
results += `</${formatted}>;rel=preload;as=${type},`;
});
await browser.close();
updateWith(results);
}
function updateWith(result) {
fs.readFile('firebase.json', 'utf8', function(err, data) {
if (err) {
return console.log(err);
}
let re = /("headers":\s*\[\s*{\s*"key":\s*"Link",\s*"value":\s*")(.*)("\s*}\s*\])/gm;
if (re.exec(data)) {
let newConfig = data.replace(re, `$1${result}$3`);
fs.writeFile('firebase.json', newConfig, 'utf8', function(err) {
if (err) return console.log(err);
console.log('firebase.json updated successfully.');
});
} else {
console.log("Couldn't find a valid firebase config to update.");
return;
}
});
}
main();