Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : agentilab-web8 * File : scripts/audit-links.mjs9 * Module : Scripts10 * Repository : https://git.spboucher.ai/agentilab-web11 * Project Website : Not specified12 * Created : 2026-12-0513 * Last Modified : 2026-12-0514 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : Proprietary34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243// Audit des liens : parcourt toutes les pages du sitemap et vérifie chaque lien,44// interne (contre le serveur visé) et externe (sur Internet).45// Usage : node scripts/audit-links.mjs [baseUrl] [--user u --password p] [--json fichier]46import { writeFile } from 'node:fs/promises';4748const args = process.argv.slice(2);49const opt = (name) => (args.includes(name) ? args[args.indexOf(name) + 1] : undefined);50const base = (args[0] && !args[0].startsWith('--') ? args[0] : 'http://localhost:8190').replace(/\/$/, '');51const CANONICAL = 'https://www.agentilab.ai';52const auth = opt('--user') ? { Authorization: `Basic ${Buffer.from(`${opt('--user')}:${opt('--password')}`).toString('base64')}` } : {};53// Certains sites (App Store) refusent les clients sans agent utilisateur de navigateur.54const UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15';5556const sitemap = await (await fetch(`${base}/sitemap.xml`, { headers: auth })).text();57const pages = [...sitemap.matchAll(/<loc>([^<]+)<\/loc>/g)].map((m) => m[1].replace(CANONICAL, '') || '/');58if (pages.length === 0) throw new Error('Sitemap vide ou inaccessible.');5960const links = new Map(); // url → pages qui la citent61for (const page of pages) {62 const html = await (await fetch(base + page, { headers: auth })).text();63 for (const match of html.matchAll(/<a\b[^>]*\bhref="([^"]+)"/g)) {64 const raw = match[1].replace(/&/g, '&');65 if (raw.startsWith('#') || raw.startsWith('mailto:')) continue;66 const url = raw.startsWith('/') ? base + raw.split('#')[0] : raw.split('#')[0];67 if (!links.has(url)) links.set(url, new Set());68 links.get(url).add(page);69 }70}7172async function check(url) {73 const internal = url.startsWith(base);74 for (let attempt = 0; attempt < 2; attempt++) {75 try {76 const res = await fetch(url, { headers: internal ? auth : { 'User-Agent': UA, 'Accept-Language': 'fr-CA,fr;q=0.9,en;q=0.8' }, redirect: 'follow', signal: AbortSignal.timeout(25000) });77 if (res.ok) return { url, status: res.status, final: res.url !== url ? res.url : undefined };78 if (attempt === 1) return { url, status: res.status };79 } catch (error) {80 if (attempt === 1) return { url, status: 0, error: String(error.cause?.code ?? error.message) };81 }82 }83}8485const results = [];86const queue = [...links.keys()];87await Promise.all(Array.from({ length: 6 }, async () => {88 while (queue.length) results.push(await check(queue.shift()));89}));90results.sort((a, b) => a.url.localeCompare(b.url));91const dead = results.filter((r) => r.status < 200 || r.status >= 300);92const external = results.filter((r) => !r.url.startsWith(base));9394console.log(`${pages.length} pages, ${results.length} liens distincts (${external.length} externes).`);95for (const r of external) console.log(` ${r.status} ${r.url}`);96if (opt('--json')) await writeFile(opt('--json'), JSON.stringify({ checkedAt: new Date().toISOString(), base, pages: pages.length, results }, null, 2) + '\n');97if (dead.length) {98 console.error(`\n${dead.length} lien(s) mort(s) :`);99 for (const r of dead) console.error(` ✗ ${r.status} ${r.url} ${r.error ?? ''} ← ${[...links.get(r.url)].join(', ')}`);100 process.exit(1);101}102console.log('\nAucun lien mort.');103