Repository navigation
Expand file tree
/
Copy pathtest-redirects.mjs
More file actions
62 lines (48 loc) 路 1.88 KB
/
Copy pathtest-redirects.mjs
File metadata and controls
62 lines (48 loc) 路 1.88 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
// Test all redirects under `/static/_redirects` are reachable
import fs from 'node:fs/promises';
const content = await fs.readFile('./static/_redirects', 'utf8');
const baseUrl = 'http://localhost:3000';
const entries = new Map();
for (const line of content.split('\n')) {
const trimmed = line.trim();
if (trimmed === '' || trimmed.startsWith('#')) {
continue;
}
const [from, to] = line.split(' ');
if (to.includes(':')) {
console.warn(`Ignoring ${to} because it has a placeholder`);
continue;
}
entries.set(from, to);
// eslint-disable-next-line no-await-in-loop
const response = await fetch(new URL(to, baseUrl));
if (response.status === 200) {
console.log(`Target ${to} is reachable`);
} else {
console.error(`Failed to reach ${to}`);
console.error(`Status: ${response.status}`);
throw new Error(`Failed to reach ${to}`);
}
}
console.log('=== All redirects are reachable ===');
for (const [from, to] of entries) {
if (from === '/' || from.endsWith('*')) {
console.log(`Skipping ${from} because it's a catch-all redirect`);
continue;
}
// Support "from" entries that include a hash fragment by toggling the trailing
// slash on the path portion only, then re-attaching the original fragment.
const hashIndex = from.indexOf('#');
const baseFrom = hashIndex >= 0 ? from.slice(0, hashIndex) : from;
const fragment = hashIndex >= 0 ? from.slice(hashIndex) : '';
const toggledBase = baseFrom.endsWith('/') ? baseFrom.slice(0, -1) : baseFrom + '/';
const mappedFrom = `${toggledBase}${fragment}`;
const mappedTo = entries.get(mappedFrom);
if (!mappedTo) {
throw new Error(`Missing mapped redirect for ${from}. Expected ${mappedFrom}.`);
}
if (mappedTo !== to) {
throw new Error(`Mismatched redirect for ${from}. Expected ${to} but got ${mappedTo}.`);
}
}
console.log('=== All redirects are mapped correctly ===');