#!/usr/bin/env node /** * Test de l'indexation (B23) : canonique, robots, redirections, robots.txt, sitemap. * B28 : 301 de la copie aep.…/evenements/* vers event. ; B29 : utils/evenements.ts lit utils/seo.ts. * Charge le VRAI fichier utils/seo.ts via jiti (même patron que test-echelles-nav.mjs). * Usage : node scripts/test-seo.mjs * node scripts/test-seo.mjs http://localhost:3000 (+ contrôles HTTP sur un serveur lancé) */ import { createJiti } from 'jiti' import { fileURLToPath } from 'node:url' import { dirname, join } from 'node:path' const __dirname = dirname(fileURLToPath(import.meta.url)) const jiti = createJiti(import.meta.url) const seo = await jiti.import(join(__dirname, '..', 'utils', 'seo.ts')) const { canonique, robots, redirection, robotsTxt, cheminsSitemap, sitemapXml, dateSitemap, entreesFichesSitemap, estHoteLocal, sousPrefixe, cheminEvent } = seo const evt = await jiti.import(join(__dirname, '..', 'utils', 'evenements.ts')) let echecs = 0 function egal(nom, obtenu, attendu) { const ok = JSON.stringify(obtenu) === JSON.stringify(attendu) if (!ok) echecs++ console.log(`${ok ? 'ok ' : 'ÉCHEC'} ${nom}${ok ? '' : `\n obtenu ${JSON.stringify(obtenu)}\n attendu ${JSON.stringify(attendu)}`}`) } const AEP = 'aep.trans-former.fr' const EVT = 'event.trans-former.fr' const A = 'https://aep.trans-former.fr' const E = 'https://event.trans-former.fr' // ── Canonique ─────────────────────────────────────────────────── const canoniques = [ [AEP, '/', {}, `${A}/`], [AEP, '/', { fiche: '108' }, `${A}/fiche/108`], [AEP, '/', { fiche: '108', vue: 'fiches', q: 'bois' }, `${A}/fiche/108`], [AEP, '/', { vue: 'fiches', tags: 'eau', echelle: 'M' }, `${A}/`], [AEP, '/agences', { fiche: 'f1-rotor', mode: 'carte' }, `${A}/agences`], [AEP, '/media', { tab: 'projets', q: 'x' }, `${A}/media?tab=projets`], [AEP, '/outils', { tab: 'simulateurs', random: '1' }, `${A}/outils?tab=simulateurs`], [AEP, '/outils/', {}, `${A}/outils`], [AEP, '/entree', { porte: 'S' }, `${A}/entree`], [AEP, '/fiche/108', { territoire: 'idf' }, `${A}/fiche/108`], [AEP, '/evenements/ruetz', {}, `${E}/ruetz`], [AEP, '/evenements', {}, `${E}/`], [EVT, '/ruetz', { utm: 'deck' }, `${E}/ruetz`], [EVT, '/', {}, `${E}/`], [EVT, '/evenements/ruetz', {}, `${E}/ruetz`], // B29 : sur event., tout chemin est un chemin d'événement (app/router.options.ts) ; /agences y répond 404, // la canonique d'une 404 n'est lue par personne : on vérifie seulement qu'elle reste sur event. [EVT, '/agences', {}, `${E}/agences`], ['localhost:3000', '/media', { tab: 'projets' }, `${A}/media?tab=projets`], ] for (const [h, p, q, att] of canoniques) egal(`canonique ${h}${p} ${JSON.stringify(q)}`, canonique(h, p, q), att) // ── Robots (balise) ───────────────────────────────────────────── const NI = 'noindex, follow' const robotsCas = [ [AEP, '/', null], [AEP, '/agences', null], [AEP, '/fiche/12', null], [AEP, '/entree', null], [AEP, '/signaler', NI], [AEP, '/ajouter', NI], [AEP, '/proposer', NI], [AEP, '/dev/fiche-mini-card', NI], [AEP, '/codev', null], [AEP, '/codev/acces', NI], [AEP, '/codev/fiche', NI], [AEP, '/codev/demo', NI], [AEP, '/codevelopper', null], [AEP, '/evenements/ruetz', NI], [EVT, '/ruetz', null], [EVT, '/evenements/ruetz', null], ] for (const [h, p, att] of robotsCas) egal(`robots ${h}${p}`, robots(h, p), att) // ── Hôte local (B28) ──────────────────────────────────────────── const locaux = [ ['localhost', true], ['localhost:3000', true], ['127.0.0.1', true], ['127.0.0.1:3128', true], ['::1', true], ['[::1]', true], ['[::1]:3000', true], ['event.localhost:3000', true], ['LOCALHOST:3000', true], [AEP, false], [EVT, false], ['localhost.trans-former.fr', false], ['monlocalhost', false], ['', false], [undefined, false], ] for (const [h, att] of locaux) egal(`hôte local ${JSON.stringify(h)}`, estHoteLocal(h), att) // ── Redirections ──────────────────────────────────────────────── // B28 : la copie des pages d'événement part vers event., hors event. et hors local const redirsEvt = [ [AEP, '/evenements/ruetz/foret', `${E}/ruetz/foret`], [AEP, '/evenements', `${E}/`], [AEP, '/evenements/', `${E}/`], [AEP, '/evenements/ruetz/', `${E}/ruetz`], [EVT, '/ruetz/foret', null], [EVT, '/evenements/ruetz', null], // sur event., ce chemin n'est pas une route : 404 naturel, pas de 301 ['localhost:3000', '/evenements/ruetz', null], ['127.0.0.1:3128', '/evenements/ruetz', null], ['event.localhost:3000', '/ruetz', null], [AEP, '/evenementsX', null], // frontière de préfixe ['203.0.113.7:3333', '/evenements/ruetz', `${E}/ruetz`], // hôte inconnu (IP nue) : 301 aussi ] for (const [h, p, att] of redirsEvt) egal(`301 ${h}${p}`, redirection(h, p), att) egal('301 garde la requête', redirection(AEP, '/evenements/ruetz/foret', '?a=1&utm_source=mail'), `${E}/ruetz/foret?a=1&utm_source=mail`) egal('301 requête sans « ? » : un seul « ? »', redirection(AEP, '/evenements/ruetz', 'a=1'), `${E}/ruetz?a=1`) egal('301 requête vide : pas de « ? »', [redirection(AEP, '/evenements/ruetz', ''), redirection(AEP, '/evenements/ruetz', '?')], [`${E}/ruetz`, `${E}/ruetz`]) // URL mortes (B23), hôte AEP : relatives, requête retirée comme avant const redirs = [ ['/pratiques-regeneratives', '/agences'], ['/pratiques-regeneratives/', '/agences'], ['/proposer-pratique', '/proposer'], ['/pratique/42', '/agences'], ['/proposer', null], ['/chatbot-v2', null], ['/agences', null], ] for (const [p, att] of redirs) egal(`301 ${AEP}${p}`, redirection(AEP, p), att) egal('301 URL morte : requête non recopiée', redirection(AEP, '/pratique/42', '?x=1'), '/agences') // ── robots.txt ────────────────────────────────────────────────── const txt = robotsTxt(AEP) egal('robots.txt interdit /api/', txt.includes('Disallow: /api/'), true) egal('robots.txt laisse /_nuxt/ assets', /Disallow: \/_nuxt\/\n/.test(txt), false) egal('robots.txt sitemap aep', txt.includes(`Sitemap: ${A}/sitemap.xml`), true) egal('robots.txt sitemap event', robotsTxt(EVT).includes(`Sitemap: ${E}/sitemap.xml`), true) // ── Sitemap ───────────────────────────────────────────────────── const routes = ['/', '/a-propos', '/agences', '/ajouter', '/codev', '/codev/carto', '/codev/demo', '/contribuer', '/dev/fiche-mini-card', '/entree', '/fiche/:id()', '/manifeste', '/media', '/outils', '/proposer', '/rag', '/signaler', '/trouver-du-taf', '/evenements', '/evenements/ruetz', '/evenements/:slug()'] egal('sitemap aep', cheminsSitemap(routes, AEP), ['/', '/a-propos', '/agences', '/codev', '/entree', '/manifeste', '/media', '/outils', '/trouver-du-taf']) egal('sitemap event', cheminsSitemap(routes, EVT), ['/', '/ruetz']) const xml = sitemapXml([{ loc: `${A}/` }, { loc: `${A}/fiche/1?a=1&b=2`, lastmod: '2026-10-01' }]) egal('sitemap XML échappé', xml.includes('fiche/1?a=1&b=2'), true) egal('sitemap XML en-tête', xml.startsWith('\n'), true) egal('dateSitemap', [dateSitemap('2026-10-13 08:12:00+00:00'), dateSitemap(''), dateSitemap('n/a')], ['2026-10-13', undefined, undefined]) // Fiches du sitemap : jamais le repli seed, au moins une /fiche/ quand NocoDB répond, Id nul ignoré (checkpoint 22/10) const fiches = [{ Id: 108, UpdatedAt: '2026-10-01 10:00:00+00:00' }, { Id: null }, { Id: 7 }] egal('fiches sitemap : repli seed → aucune', entreesFichesSitemap({ source: 'seed', list: fiches }), []) egal('fiches sitemap : nocodb → les fiches avec Id', entreesFichesSitemap({ source: 'nocodb', list: fiches }, A), [{ loc: `${A}/fiche/108`, lastmod: '2026-10-01' }, { loc: `${A}/fiche/7`, lastmod: undefined }]) egal('fiches sitemap : réponse absente → aucune', [entreesFichesSitemap(null), entreesFichesSitemap({ source: 'nocodb' })], [[], []]) // ── B29 : une seule source (utils/evenements.ts lit utils/seo.ts) ─── for (const c of ['/', '/ruetz', '/ruetz/codev', '/ruetz/foret']) { egal(`canoniqueEvenement(${c}) = canonique(event., ${c})`, evt.canoniqueEvenement(c), canonique(EVT, c)) } egal('estHoteEvenement est estHoteEvent (alias, pas une copie)', evt.estHoteEvenement === seo.estHoteEvent, true) egal('plus de cheminPublic ni de sousPrefixe dans utils/evenements.ts', ['cheminPublic', 'sousPrefixe'].filter(n => n in evt), []) egal('sousPrefixe(path, prefixe)', [sousPrefixe('/evenements', '/evenements'), sousPrefixe('/evenements/r', '/evenements'), sousPrefixe('/evenementsX', '/evenements')], [true, true, false]) egal('cheminEvent', [cheminEvent('/evenements/ruetz'), cheminEvent('/evenements'), cheminEvent('/ruetz')], ['/ruetz', '/', '/ruetz']) // ── HTTP (optionnel, serveur lancé) ───────────────────────────── const base = process.argv[2] if (base) { const get = (p, opt = {}) => fetch(base + p, { redirect: 'manual', ...opt }) const r1 = await get('/robots.txt') egal('HTTP robots.txt 200 text/plain', [r1.status, r1.headers.get('content-type')?.startsWith('text/plain')], [200, true]) const r2 = await get('/sitemap.xml') const corps = await r2.text() egal('HTTP sitemap 200 xml', [r2.status, r2.headers.get('content-type')?.startsWith('application/xml')], [200, true]) const locs = [...corps.matchAll(/([^<]+)<\/loc>/g)].map(m => m[1]) egal('HTTP sitemap : ni /rag, ni /signaler, ni /contribuer', locs.filter(l => /\/(rag|signaler|contribuer)$/.test(l)), []) egal('HTTP sitemap aep : aucune URL /evenements', locs.filter(l => l.includes('/evenements')), []) console.log(` (${locs.length} URL, dont ${locs.filter(l => l.includes('/fiche/')).length} fiches)`) for (const [p, cible] of [['/pratiques-regeneratives', '/agences'], ['/proposer-pratique', '/proposer'], ['/pratique/3', '/agences']]) { const r = await get(p) egal(`HTTP 301 ${p}`, [r.status, new URL(r.headers.get('location') || '', base).pathname], [301, cible]) } const page = async (p, host) => (await get(p, host ? { headers: { 'x-forwarded-host': host } } : {})).text() const canon = html => html.match(/]*rel="canonical"[^>]*>/)?.[0].match(/href="([^"]+)"/)?.[1] ?? null const rob = html => html.match(/]*name="robots"[^>]*content="([^"]+)"/)?.[1] ?? null const hAcc = await page('/') egal('HTTP / : canonique, pas de robots', [canon(hAcc), rob(hAcc)], [`${A}/`, null]) const hFiche = await page('/?fiche=108&vue=fiches') egal('HTTP /?fiche=108 → /fiche/108', canon(hFiche), `${A}/fiche/108`) for (const p of ['/signaler', '/ajouter', '/proposer', '/codev/acces']) egal(`HTTP ${p} noindex`, rob(await page(p)), NI) egal('HTTP /codev : indexable (recette publique, lot Y)', rob(await page('/codev')), null) const rApi = await get('/api/stats') egal('HTTP /api/stats X-Robots-Tag', rApi.headers.get('x-robots-tag'), 'noindex') // B28 : la copie part en 301 vers event. node:http plutôt que fetch : fetch ignore l'en-tête Host. const { request } = await import('node:http') const brut = (path, headers = {}) => new Promise((resolve, reject) => { const u = new URL(base + path) const req = request({ hostname: u.hostname, port: u.port, path: u.pathname + u.search, headers }, (res) => { res.resume() res.on('end', () => resolve({ status: res.statusCode, location: res.headers.location ?? null })) }) req.on('error', reject) req.end() }) const hAep = { Host: AEP } egal('HTTP Host aep /evenements/ruetz/foret → 301 event.', await brut('/evenements/ruetz/foret', hAep), { status: 301, location: `${E}/ruetz/foret` }) egal('HTTP Host aep, ?a=1 suit la 301', await brut('/evenements/ruetz/foret?a=1', hAep), { status: 301, location: `${E}/ruetz/foret?a=1` }) egal('HTTP Host aep /evenements → 301 racine event.', await brut('/evenements', hAep), { status: 301, location: `${E}/` }) egal('HTTP X-Forwarded-Host aep (Caddy) → 301 event.', (await get('/evenements/ruetz', { headers: { 'x-forwarded-host': AEP } })).headers.get('location'), `${E}/ruetz`) egal('HTTP sans Host (local) : la copie reste servie', (await brut('/evenements/ruetz/foret')).status, 200) egal('HTTP Host event. /ruetz/foret : 200, pas de 301', await brut('/ruetz/foret', { Host: 'event.localhost:3000' }), { status: 200, location: null }) egal('HTTP Host aep : URL morte toujours relative', await brut('/pratique/3', hAep), { status: 301, location: '/agences' }) } console.log(echecs ? `\n${echecs} échec(s)` : '\nTout est vert.') process.exit(echecs ? 1 : 0)