-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdiscover.js
73 lines (57 loc) · 2.04 KB
/
discover.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
const fs = require("fs");
const path = require("path");
const util = require("util");
const open = util.promisify(fs.open);
const readFile = util.promisify(fs.readFile);
const pushTypes = [".html", ".js", ".css"];
const htmlLinkRegex = /<link[^>]+href="([^"]*)"[\s/]*[^>]*>/g;
const htmlScriptRegex = /<script[^>]*src="([^"]*)"[^>]*>[\s]*<\/script>/g;
const jsImportRegex = /(?:import|export)[^'"]*from[\s]+['"]([^'"]*)['"]/g;
const jsImportNoFromRegex = /import[\s]+['"]([^'"]*)['"]/g;
const jsWorkerRegex = /new\s+Worker\s*\(\s*['"]([^'"]*)['"]/g;
const jsImportScriptsRegex = /importScripts\s*\(\s*['"]([^'"]*)['"]/g;
const cssImportRegex = /url\("([^"]*)"\)/g;
const gatherMatches = (regex, content) => {
const results = [];
while ((result = regex.exec(content)) !== null) {
results.push(result[1]);
}
return results;
};
const findPushFiles = async requestPath => {
const filePath = path.join(__dirname, "public", requestPath);
const ext = path.extname(filePath);
// console.log("find", requestPath);
if (!pushTypes.includes(ext)) {
return [];
}
const content = await readFile(filePath);
let pushes = [];
if (ext === ".html") {
pushes.push(...gatherMatches(htmlLinkRegex, content));
pushes.push(...gatherMatches(htmlScriptRegex, content));
pushes.push(...gatherMatches(jsImportRegex, content));
}
if (ext === ".js") {
pushes.push(...gatherMatches(jsImportRegex, content));
pushes.push(...gatherMatches(jsImportNoFromRegex, content));
// pushes.push(...gatherMatches(jsWorkerRegex, content));
pushes.push(...gatherMatches(jsImportScriptsRegex, content));
}
if (ext === ".css") {
pushes.push(...gatherMatches(cssImportRegex, content));
}
pushes = pushes.map(
childPath =>
childPath.startsWith(".")
? path.resolve(path.dirname(requestPath), childPath)
: path.resolve("/", childPath)
);
await Promise.all(
pushes.map(async filePath => {
pushes.push(...(await findPushFiles(filePath)));
})
);
return pushes;
};
exports.findPushFiles = findPushFiles;