forked from 18F/handbook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
check-links.js
158 lines (127 loc) · 3.95 KB
/
check-links.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
const cheerio = require("cheerio");
const fs = require("fs/promises");
const path = require("path");
const SITE_ROOT = path.join(__dirname, "_site");
const exists = async (path) => {
try {
await fs.access(path);
return true;
} catch (e) {
return false;
}
};
const getFiles = async (root) => {
const fsChildren = await fs.readdir(root);
const files = [];
for await (const child of fsChildren) {
const full = path.join(root, child);
const stat = await fs.lstat(full);
if (stat.isFile()) {
files.push(full);
} else if (stat.isDirectory()) {
files.push(...(await getFiles(full)));
}
}
return files.filter((file) => file.endsWith(".html"));
};
const getDom = async (file) => {
const html = await fs.readFile(file, { encoding: "utf-8" });
const dom = cheerio.load(html);
const redirect = dom('meta[http-equiv="refresh"]').get().pop();
if (redirect) {
const [, realFile] = dom(redirect)
.attr("content")
.match(/url=(\S+)/i);
const realFilePath = path.join(
SITE_ROOT,
realFile.replace(process.env.BASEURL, ""),
path.basename(file)
);
const redirectedHtml = await fs.readFile(realFilePath, {
encoding: "utf-8",
});
return cheerio.load(redirectedHtml);
}
return dom;
};
const run = async () => {
const files = await getFiles(SITE_ROOT);
const pagesMap = new Map();
for await (const file of files) {
const dom = await getDom(file);
const ids = dom("[id]")
.map(function () {
return dom(this).attr("id");
})
.get();
const links = dom("img[src], a[href], iframe[src], link[href], script[src]")
.map(function () {
return dom(this).attr("src") ?? dom(this).attr("href");
})
.get()
.filter((url) => /^[#\/]/.test(url))
// The /admin/ page is populated dynamically by Netlify, so those links
// are never "there" at build time. Don't test for them.
.filter((url) => !/\/admin\//i.test(url));
pagesMap.set(file, { ids, links });
}
console.log(`Checking ${pagesMap.size} pages...`);
const errors = new Map();
for (const [page, { ids, links }] of pagesMap) {
errors.set(page, []);
for (const link of links) {
if (link.startsWith("/")) {
const url = new URL(link, "https://18f.gov");
const pathComponents = [SITE_ROOT];
// if(/^\/(images|))
pathComponents.push(url.pathname.replace(process.env.BASEURL, ""));
// If the link does not include a file path, append index.html
if (!/\.[a-z]+/i.test(url.pathname)) {
pathComponents.push("index.html");
}
const filePath = path.join(...pathComponents);
const targetFileExists = await exists(filePath);
if (targetFileExists) {
if (url.hash) {
const targetId = url.hash.replace(/^#/, "");
const targetHashExists = pagesMap
.get(filePath)
.ids.includes(targetId);
if (!targetHashExists) {
errors
.get(page)
.push(`link to ${link} - target hash does not exist`);
}
}
} else {
errors.get(page).push(`link to ${link}: target file does not exist`);
}
} else {
const targetId = link.replace(/^#/, "");
const targetHashExists = ids.includes(targetId.toLowerCase());
if (!targetHashExists) {
errors.get(page).push(`link to ${link} - target hash does not exist`);
}
}
}
}
const errorMessages = [];
for (const [page, pageErrors] of errors) {
if (pageErrors.length) {
if (errorMessages.length) {
errorMessages.push("");
}
errorMessages.push(`${page}`);
for (const error of pageErrors) {
errorMessages.push(` ${error}`);
}
}
}
if (errorMessages.length) {
console.log(errorMessages.join("\n"));
process.exit(1);
} else {
console.log("No errors!");
}
};
run();