| 1 | import { readdirSync, readFileSync, statSync, writeFileSync, mkdirSync } from "node:fs"; |
| 2 | import { dirname, join } from "node:path"; |
| 3 | |
| 4 | const out = process.argv[2]; |
| 5 | if (!out) { |
| 6 | console.error("usage: link-report.mjs <output.json>"); |
| 7 | process.exit(2); |
| 8 | } |
| 9 | |
| 10 | const roots = ["web/lib/content", "web/lib/i18n/dictionaries/en"]; |
| 11 | const urlPattern = /https?:\/\/[^\s"'`<>)\\]+/g; |
| 12 | const found = new Map(); |
| 13 | |
| 14 | const walk = (dir) => { |
| 15 | for (const name of readdirSync(dir)) { |
| 16 | const path = join(dir, name); |
| 17 | if (statSync(path).isDirectory()) walk(path); |
| 18 | else if (/\.(ts|tsx)$/.test(name) && !/\.(test|generated)\./.test(name)) { |
| 19 | for (const match of readFileSync(path, "utf8").matchAll(urlPattern)) { |
| 20 | const url = match[0].replace(/[.,;:]+$/, ""); |
| 21 | if (!found.has(url)) found.set(url, new Set()); |
| 22 | found.get(url).add(path); |
| 23 | } |
| 24 | } |
| 25 | } |
| 26 | }; |
| 27 | for (const root of roots) walk(root); |
| 28 | |
| 29 | const urls = [...found.keys()].filter((url) => !/[{$]/.test(url)).slice(0, 400); |
| 30 | const results = []; |
| 31 | let next = 0; |
| 32 | |
| 33 | const probe = async (url) => { |
| 34 | for (const method of ["HEAD", "GET"]) { |
| 35 | try { |
| 36 | const res = await fetch(url, { |
| 37 | method, |
| 38 | redirect: "follow", |
| 39 | signal: AbortSignal.timeout(12_000), |
| 40 | headers: { "user-agent": "codewhale-web-maintainer-link-check" }, |
| 41 | }); |
| 42 | if (res.status < 400) return { ok: true, status: res.status, finalUrl: res.url }; |
| 43 | if (method === "GET" || res.status === 404 || res.status === 410) return { ok: false, status: res.status, finalUrl: res.url }; |
| 44 | } catch (error) { |
| 45 | if (method === "GET") return { ok: false, status: 0, error: error instanceof Error ? error.name : "error" }; |
| 46 | } |
| 47 | } |
| 48 | return { ok: false, status: 0 }; |
| 49 | }; |
| 50 | |
| 51 | await Promise.all( |
| 52 | Array.from({ length: 8 }, async () => { |
| 53 | while (next < urls.length) { |
| 54 | const url = urls[next++]; |
| 55 | const result = await probe(url); |
| 56 | const moved = result.ok && result.finalUrl && result.finalUrl.replace(/\/$/, "") !== url.replace(/\/$/, ""); |
| 57 | if (!result.ok || moved) results.push({ url, ...result, files: [...found.get(url)].sort() }); |
| 58 | } |
| 59 | }), |
| 60 | ); |
| 61 | |
| 62 | results.sort((a, b) => a.url.localeCompare(b.url)); |
| 63 | mkdirSync(dirname(out), { recursive: true }); |
| 64 | writeFileSync(out, JSON.stringify({ checked: urls.length, flagged: results }, null, 2) + "\n"); |
| 65 | console.log(`link-report: ${urls.length} checked, ${results.length} flagged`); |
| 66 |