Repository navigation
Expand file tree
/
Copy pathverify-links.cjs
More file actions
112 lines (104 loc) · 4.45 KB
/
Copy pathverify-links.cjs
File metadata and controls
112 lines (104 loc) · 4.45 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
const fs = require('node:fs');
const path = require('node:path');
const {parseArgs} = require('node:util');
const {load} = require('cheerio');
const SITE = path.join(__dirname, '..');
const SITE_URL = 'https://docs.phcode.dev';
const REFERENCES = [
['a[href], area[href], link[href]', 'href'],
['img[src], script[src], iframe[src], audio[src], video[src], source[src], track[src], embed[src]', 'src'],
['video[poster]', 'poster'],
['object[data]', 'data'],
];
function listFiles(directory, root = directory) {
return fs.readdirSync(directory, {withFileTypes: true}).flatMap(entry => {
const file = path.join(directory, entry.name);
if (entry.isDirectory()) return listFiles(file, root);
return entry.isFile() ? [path.relative(root, file).split(path.sep).join('/')] : [];
});
}
// Check the finished artifact, including the absolute production URLs that
// Docusaurus treats as external links. Never request the live website: new pages
// do not exist there yet, and an outage must not make a valid build fail.
function verify(buildDir, siteUrl = SITE_URL) {
const build = path.resolve(buildDir);
const origin = new URL(siteUrl);
const files = new Set(listFiles(build));
if (!files.has('index.html')) throw new Error('Missing index.html in ' + build + '; build the website first.');
const htmlFiles = [...files].filter(file => file.endsWith('.html')).sort();
const missing = new Set();
const targets = new Map();
let checked = 0;
function check(href, base, source) {
if (!href?.trim()) return;
let url;
try {
url = new URL(href, base);
} catch {
missing.add(source + ' -> ' + href + ' (invalid URL)');
return;
}
if (!['http:', 'https:'].includes(url.protocol) || url.host !== origin.host) return;
checked++;
if (!targets.has(url.pathname)) {
let exists = false;
try {
const name = decodeURIComponent(url.pathname).slice(1);
// GitHub Pages serves clean URLs from .html files, or directory indexes.
// A trailing slash needs its own index (including client redirects).
const candidates = name === '' ? ['index.html'] : name.endsWith('/')
? [name + 'index.html']
: [name, name + '.html', name + '/index.html'];
exists = candidates.some(candidate => files.has(candidate));
} catch {
// Malformed percent escapes must fail instead of skipping validation.
}
targets.set(url.pathname, exists);
}
if (!targets.get(url.pathname)) missing.add(source + ' -> ' + href);
}
for (const file of htmlFiles) {
const document = load(fs.readFileSync(path.join(build, file), 'utf8'));
const pageUrl = new URL('/' + file.split('/').map(encodeURIComponent).join('/'), origin);
const baseHref = document('base[href]').first().attr('href');
let base = pageUrl;
if (baseHref) {
try {
base = new URL(baseHref, pageUrl);
} catch {
missing.add(file + ' -> ' + baseHref + ' (invalid base URL)');
}
}
for (const [selector, attribute] of REFERENCES) {
document(selector).each((_, element) => check(document(element).attr(attribute), base, file));
}
// Client redirects also need a real destination, even without an <a> tag.
document('meta[http-equiv]').each((_, element) => {
if (document(element).attr('http-equiv').toLowerCase() !== 'refresh') return;
const content = document(element).attr('content') || '';
const match = /^\s*[\d.]+\s*;\s*url\s*=\s*(.*?)\s*$/i.exec(content);
if (match) check(match[1].replace(/^(['"])(.*)\1$/, '$2'), base, file);
});
}
if (missing.size) {
throw new Error('Found ' + missing.size + ' broken local reference(s):\n' +
[...missing].sort().map(item => ' ' + item).join('\n') +
'\nFix the source link or add a redirect to an existing page, then rebuild.');
}
return 'PASS: ' + htmlFiles.length + ' HTML files and ' + checked + ' local references; all destinations exist.';
}
if (require.main === module) {
try {
const {values} = parseArgs({options: {
'build-dir': {type: 'string', default: path.join(SITE, 'build')},
'site-url': {type: 'string', default: SITE_URL},
help: {type: 'boolean', short: 'h'},
}});
console.log(values.help ? 'Usage: npm run verify:links -- [--build-dir PATH] [--site-url URL]' :
verify(values['build-dir'], values['site-url']));
} catch (error) {
console.error('FAIL: ' + error.message);
process.exitCode = 1;
}
}
module.exports = {verify};