Files
nav-carte/scripts/test-bibliotheque.mjs
T

203 lines
16 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env node
/**
* Tests de la bibliothèque navigable (lot B9) : l'export du registre (liste blanche), les 119
* socles (comptes par motif, réglage de service), l'arborescence (adaptateur du graphe), les
* adresses, et le test qui tient le lot : aucune trace du champ d'édition dans ce que la branche
* ajoute au dépôt. Charge les vrais utils/bibliotheque/*.ts via jiti, comme test-connaissances.
* Aucun accès réseau, aucune lecture du vault ni de ~/rag.
* Usage : node scripts/test-bibliotheque.mjs [http://localhost:PORT] (sans adresse : pas de test HTTP)
*/
import { createJiti } from 'jiti'
import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, join, relative } from 'node:path'
const racine = join(dirname(fileURLToPath(import.meta.url)), '..')
const jiti = createJiti(import.meta.url)
const charger = async (...p) => (existsSync(join(racine, ...p)) ? jiti.import(join(racine, ...p)) : null)
let n = 0
let echecs = 0
function ok(cond, libelle, detail = '') {
n++
if (!cond) echecs++
console.log(`${cond ? 'OK ' : 'FAIL'} ${libelle}${!cond && detail ? ` → ${detail}` : ''}`)
}
const lire = (...p) => readFileSync(join(racine, ...p), 'utf8')
// ── Le test qui tient le lot : le champ d'édition ne sort par aucun chemin ──
// Motifs assemblés par morceaux : ce fichier est lui-même dans le périmètre scanné.
const MOTIFS = [
['edi' + 'tion (ASCII)', new RegExp('edi' + 'tion', 'i')],
['édi' + 'tion lue', new RegExp('édi' + 'tions? ' + 'lues?', 'i')],
['ann' + 'as', new RegExp('ann' + 'as', 'i')],
['Ann' + 'a’s Archive', new RegExp('ann' + 'a.?s +arch' + 'ive', 'i')],
['arch' + 'ive.gl', new RegExp('arch' + 'ive\\.gl', 'i')],
]
/** Ce que la branche ajoute au dépôt (tout ce qui est neuf vit sous ces chemins). */
const PERIMETRE = [
'scripts/bibliotheque', 'scripts/test-bibliotheque.mjs', 'content/bibliotheque', 'data/bibliotheque',
'utils/bibliotheque', 'modules/bibliotheque.ts', 'server/api/bibliotheque', 'pages/bibliotheque', 'components/bibliotheque',
]
function fichiers(p) {
const abs = join(racine, p)
if (!existsSync(abs)) return []
if (statSync(abs).isFile()) return [abs]
return readdirSync(abs).flatMap((x) => (x === '__pycache__' ? [] : fichiers(join(p, x))))
}
/**
* Trois exceptions, nommées et comptées : des mots de l'analyse M6b sur le texte lui-même, pas le champ
* d'édition du registre. Starhawk : le titre d'une préface du livre. Rimbaud : l'édition Vanier de 1895
* (domaine public), dite par l'analyse. Debord (socle rejeté, non servi) : « OCR dégradé » du fichier lu. Le socle se régénère depuis les couches : une
* retouche à la main se perdrait ; le checkpoint tranche.
*/
const EXCEPTIONS = [
['content/bibliotheque/starhawk-rever-obscur.md', 'Fifteenth Anniversary Edi' + 'tion'],
['content/bibliotheque/rimbaud-poesies.md', 'l\'édi' + 'tion lue est celle de 1895'],
['content/bibliotheque/debord-potlatch.md', 'dans l\'édi' + 'tion lue'],
]
const scannes = PERIMETRE.flatMap(fichiers)
const traces = []
let exceptionsVues = 0
for (const f of scannes) {
let t = readFileSync(f, 'utf8')
for (const [chemin, texte] of EXCEPTIONS) {
if (relative(racine, f) !== chemin) continue
exceptionsVues += t.split(texte).length - 1
t = t.split(texte).join(' ')
}
for (const [nom, re] of MOTIFS) if (re.test(t)) traces.push(`${relative(racine, f)} : ${nom}`)
}
ok(exceptionsVues === EXCEPTIONS.length, `édition : les ${EXCEPTIONS.length} exceptions nommées, une fois chacune (${exceptionsVues})`)
ok(scannes.length >= 125, `périmètre ajouté scanné : ${scannes.length} fichiers (export, 119 socles, scripts, page…)`, String(scannes.length))
ok(traces.length === 0, `édition : 0 occurrence dans les ${scannes.length} fichiers ajoutés`, traces.slice(0, 8).join(' | '))
// ── L'export du registre : liste blanche ──
const CHAMPS_OEUVRE = ['id', 'titre', 'auteurs', 'annee', 'epoque', 'courants', 'regime', 'dans_corpus', 'fiche', 'couche']
const fExport = join(racine, 'data', 'bibliotheque', 'oeuvres-registre.json')
const ex = existsSync(fExport) ? JSON.parse(readFileSync(fExport, 'utf8')) : null
ok(!!ex, 'export : data/bibliotheque/oeuvres-registre.json existe (commité, hors public/)')
ok(!existsSync(join(racine, 'public', 'data', 'oeuvres-registre.json')), 'export : rien sous public/ (le build sert une copie filtrée par le réglage)')
if (ex) {
const O = ex.oeuvres ?? []
ok(JSON.stringify(Object.keys(ex)) === JSON.stringify(['version', 'source', 'champs', 'personnes', 'epoques', 'courants', 'oeuvres']), 'export : clés de tête attendues, rien d’autre', Object.keys(ex).join(','))
ok(O.length === 631, `export : 631 œuvres (le registre du 24/10 ; le brief disait 646)`, String(O.length))
const horsListe = [...new Set(O.flatMap((o) => Object.keys(o)).filter((k) => !CHAMPS_OEUVRE.includes(k)))]
ok(horsListe.length === 0 && JSON.stringify(ex.champs) === JSON.stringify(CHAMPS_OEUVRE), 'export : aucun champ hors liste blanche', horsListe.join(','))
ok(O.every((o) => typeof o.titre === 'string' && o.titre.trim()), 'export : chaque œuvre a un titre')
ok(O.every((o) => o.auteurs.every((a) => typeof ex.personnes[a] === 'string')), 'export : chaque auteur est résolu (nom dans la table)')
ok(O.filter((o) => !o.auteurs.length).length === 48, `export : 48 œuvres sans auteur au registre (dites « auteur inconnu au registre » par la page)`, String(O.filter((o) => !o.auteurs.length).length))
ok(O.filter((o) => o.fiche).length === 119 && O.filter((o) => o.regime).length === 119, 'export : les 119 œuvres lues ont une fiche et un régime')
ok(O.every((o) => o.epoque == null || ex.epoques.some((e) => e.id === o.epoque)) && O.every((o) => o.courants.every((c) => ex.courants.some((x) => x.id === c))), 'export : époques et courants pris dans leurs tables')
ok(ex.courants.length === 16 && ex.epoques.length === 12, `export : 16 courants thématiques (dont un contre-point), 12 époques`, `${ex.courants.length}, ${ex.epoques.length}`)
ok(O.every((o) => o.couche === 'ancienne'), 'export : couche ancienne partout')
const socles = existsSync(join(racine, 'content', 'bibliotheque')) ? readdirSync(join(racine, 'content', 'bibliotheque')).filter((x) => x.endsWith('.md') && x !== 'README.md') : []
ok(O.filter((o) => o.fiche).every((o) => socles.includes(`${o.fiche}.md`)), 'export : chaque fiche nommée a son socle dans content/bibliotheque/')
}
// ── Les socles : 119, comptes par motif, réglage de service ──
const S = await charger('utils', 'bibliotheque', 'socles.ts')
const SV = await charger('utils', 'bibliotheque', 'service.ts')
ok(!!S && !!SV, 'utils/bibliotheque : socles.ts et service.ts existent')
if (S && SV) {
const dossier = join(racine, 'content', 'bibliotheque')
const brut = readdirSync(dossier).filter((x) => x.endsWith('.md') && x !== 'README.md').map((nom) => ({ nom, contenu: readFileSync(join(dossier, nom), 'utf8') }))
const lus = brut.map((f) => S.lireSocle(f))
ok(lus.length === 119, `socles : 119 fichiers`, String(lus.length))
ok(lus.every((s) => !s.erreurs.length), 'socles : frontmatter complet et lisible partout', lus.filter((s) => s.erreurs.length).map((s) => `${s.nom}: ${s.erreurs.join(';')}`).slice(0, 3).join(' | '))
const comptes = SV.compterMotifs(lus)
ok(comptes.servis + comptes.rejetes + comptes.gloses + comptes.omises === 119, `socles : 119 = ${comptes.servis} conformes + ${comptes.rejetes} rejetés + ${comptes.gloses} gloses + ${comptes.omises} citations omises`, JSON.stringify(comptes))
ok(comptes.controle_ok >= 107, `contrôleur : ${comptes.controle_ok} sur 119 (107 avant)`, String(comptes.controle_ok))
ok(SV.SERVICE === 'conformes', 'réglage livré : conformes')
const servis = (r) => lus.filter((s) => SV.estServi(s, r)).length
ok(servis('aucun') === 0 && servis('conformes') === comptes.servis && servis('tous') === 119, `réglage : aucun 0, conformes ${comptes.servis}, tous 119`)
ok(SV.reglageEffectif('aucun') === 'aucun' && SV.reglageEffectif('tous') === SV.SERVICE && SV.reglageEffectif('n’importe quoi') === SV.SERVICE && SV.reglageEffectif(undefined) === SV.SERVICE, 'réglage : la variable de build ne peut que fermer')
ok(lus.every((s) => !SV.estServi(s, 'conformes') || (s.fm.controle === 'ok' && !s.fm.gloses_a_ecrire && !s.fm.citations_omises)), 'conformes : servi = contrôleur passé, aucune glose à écrire, aucune citation omise')
ok(lus.every((s) => s.fm.relecture_humaine == null), 'socles : aucune relecture humaine (le bandeau est sur toutes)')
const html = lus.filter((s) => SV.estServi(s, 'conformes')).map((s) => S.rendreSocle(s, new Set(lus.map((x) => x.fm.id))))
ok(html.length > 0 && html.every((h) => h.sommaire.length >= 5 && !/<script|<iframe|onerror=/i.test(h.html)), 'rendu : sommaire de chaque fiche servie, aucun HTML actif')
ok(html.every((h) => !/Langue et é/.test(h.html) && /Langue lue/.test(h.html)), 'rendu : le cartouche dit « Langue lue », plus l’ancienne ligne de langue')
// Une suite de trois unités consécutives d'un même parent ne s'écrit plus en entier (« LIVRE I · CHAPITRE I ; LIVRE I · CHAPITRE II ; … »)
const nonCompresse = /((?:[A-ZÉ]+ [IVXLC0-9]+ · )?[A-ZÉ]+) ([IVXLC]+|\d+) ; \1 [IVXLC0-9]+ ; \1 [IVXLC0-9]+/
ok(html.every((h) => !nonCompresse.test(h.html)), 'rendu : plages de réf: compressées', html.filter((h) => nonCompresse.test(h.html)).map((h) => h.html.match(nonCompresse)[0]).slice(0, 2).join(' | '))
}
// ── L'arborescence ──
const A = await charger('utils', 'bibliotheque', 'arbre.ts')
const G = await jiti.import(join(racine, 'utils', 'connaissances', 'graphe.ts'))
ok(!!A, 'utils/bibliotheque/arbre.ts existe')
ok(typeof G.amorcer === 'function', 'graphe.ts : amorcer (une disposition calculée entre au cache)')
if (typeof G.amorcer === 'function') {
const nd = [{ id: 'a', libelle: 'A', kind: 'axe' }, { id: 'b', libelle: 'B', kind: 'reference' }]
const ln = [{ de: 'b', vers: 'a', type: 't', provenance: 'source' }]
const p = new Map([['a', { x: 0.3, y: 0.1 }], ['b', { x: -0.2, y: 0.4 }]])
G.amorcer(nd, ln, new Set(['axe', 'fiche']), p)
ok(G.disposerEnCache(nd, ln, new Set(['axe', 'fiche'])) === p && G.disposerEnCache(nd, ln, new Set(['concept'])) !== p, 'graphe.ts : la disposition amorcée est rendue telle quelle, pour la même signature seulement')
}
if (A && ex) {
const arbre = A.arbreServi(ex, new Set(ex.oeuvres.filter((o) => o.fiche).slice(0, 3).map((o) => o.fiche)))
ok(arbre.oeuvres.filter((o) => o.fiche).length === 3, 'arbre servi : une fiche seulement si son socle est servi')
const fiches = A.fichesBibliotheque(arbre)
ok(fiches.length === 631 && fiches.every((f) => f.etiquettes.statut.length === 1), 'arbre : 631 fiches de la vue, chacune un statut (fiche · référence seulement)')
for (const axe of ['theme', 'epoque', 'auteur']) {
const g = A.grapheAxe(arbre, axe, [])
ok(g.noeuds.every((x) => x.kind === 'axe') && g.noeuds.length >= 12, `graphe ${axe} : sans focus, les catégories seules (${g.noeuds.length})`)
const cat = A.lireIdCategorie(g.noeuds[0].id)
const g2 = A.grapheAxe(arbre, axe, [cat.valeur])
const oe = g2.noeuds.filter((x) => x.kind !== 'axe')
ok(oe.length > 0 && oe.length <= A.MAX_OEUVRES && g2.liens.every((l) => l.vers.startsWith('axe:')), `graphe ${axe} : une catégorie ouverte montre ses œuvres (${oe.length}, ${g2.masquees} dans la liste seulement)`)
const derniere = A.categories(arbre, axe).find((c) => c.valeur === cat.valeur).oeuvres.at(-1)
const g3 = A.grapheAxe(arbre, axe, [cat.valeur], null, derniere.id)
ok(g3.noeuds.some((x) => x.id === derniere.id), `graphe ${axe} : l'œuvre ouverte est toujours dans le graphe, même au-delà de ${A.MAX_OEUVRES}`)
const pos = A.disposerArbre(g2.noeuds, g2.liens)
const c0 = pos.get(g.noeuds[0].id)
const dist = oe.map((x) => Math.hypot(pos.get(x.id).x - c0.x, pos.get(x.id).y - c0.y))
ok(g2.noeuds.every((x) => Number.isFinite(pos.get(x.id)?.x)) && dist.every((d) => d > 0.1 && d < 0.25), `graphe ${axe} : les œuvres en anneaux autour de la catégorie ouverte (distance ${Math.min(...dist).toFixed(2)} à ${Math.max(...dist).toFixed(2)})`)
}
}
// ── Adresses et SEO ──
ok(/navigateTo\('\/bibliotheque', \{ redirectCode: 301 \}\)/.test(lire('pages', 'rag.vue')), '/rag : 301 vers /bibliotheque')
ok(/<NuxtLink to="\/bibliotheque" class="modes__lien">Bibliothèque<\/NuxtLink>/.test(lire('components', 'carte', 'CommutateurMode.vue')), 'commutateur : « Bibliothèque » mène à /bibliotheque')
ok(existsSync(join(racine, 'pages', 'bibliotheque', 'index.vue')) && existsSync(join(racine, 'pages', 'bibliotheque', 'fiche', '[slug].vue')), 'pages : /bibliotheque et /bibliotheque/fiche/[slug]')
ok(/navigateTo|<template>/.test(lire('pages', 'media.vue')) && !/bibliotheque/.test(lire('pages', 'media.vue')), '/media : non touché')
// ── Rendu servi : node scripts/test-bibliotheque.mjs http://localhost:PORT ──
const base = process.argv[2]
if (base && S && SV && ex) {
const get = async (p, opts) => { const r = await fetch(`${base}${p}`, { redirect: 'manual', ...opts }); return { status: r.status, h: r.headers, texte: await r.text() } }
const dossier = join(racine, 'content', 'bibliotheque')
const lus = readdirSync(dossier).filter((x) => x.endsWith('.md') && x !== 'README.md').map((nom) => S.lireSocle({ nom, contenu: readFileSync(join(dossier, nom), 'utf8') }))
const servis = lus.filter((s) => SV.estServi(s, SV.SERVICE))
const fermes = lus.filter((s) => !SV.estServi(s, SV.SERVICE))
const p = await get('/bibliotheque')
ok(p.status === 200 && p.texte.includes('Bibliothèque'), `HTTP /bibliotheque : 200`, String(p.status))
// Aucune fiche dans la page : ni un titre de section propre au socle, ni une phrase de son corps
const phrase = (s) => (s.corps.split('\n').find((l) => l.length > 120 && !l.startsWith('-') && !l.startsWith('#') && !l.startsWith('>') && !l.startsWith('*')) ?? '').slice(10, 70)
ok(!p.texte.includes('Signature syntaxique') && !p.texte.includes('Geste d’ouverture') && !p.texte.includes("Geste d'ouverture"), 'HTTP /bibliotheque : aucun texte de fiche avant un clic (titres de section absents)')
const premier = servis[0]
if (premier) {
const api = await get(`/api/bibliotheque/fiche/${premier.fm.slug}`)
ok(api.status === 200 && JSON.parse(api.texte).html.length > 1000, `HTTP /api/bibliotheque/fiche/${premier.fm.slug} : 200, le HTML de la fiche`)
const page = await get(`/bibliotheque/fiche/${premier.fm.slug}`)
const iBandeau = page.texte.indexOf('Page composée depuis nos notes de lecture')
ok(page.status === 200 && iBandeau > 0 && iBandeau < page.texte.indexOf('Cartouche', iBandeau), 'HTTP page de la fiche : 200, bandeau avant le texte')
ok(/<meta name="robots" content="noindex/.test(page.texte), 'HTTP page de la fiche : noindex')
}
let fuite = ''
for (const s of fermes) {
const a = await get(`/api/bibliotheque/fiche/${s.fm.slug}`)
const pg = await get(`/bibliotheque/fiche/${s.fm.slug}`)
const ph = phrase(s)
if (a.status !== 404 || pg.status !== 404 || (ph && (pg.texte.includes(ph) || p.texte.includes(ph)))) fuite ||= `${s.fm.slug} (${a.status}, ${pg.status})`
}
ok(!fuite, `HTTP : les ${fermes.length} socles non servis répondent 404, rien de leur texte ne sort`, fuite)
const sm = await get('/sitemap.xml')
ok(sm.status === 200 && /\/bibliotheque</.test(sm.texte) && !/bibliotheque\/fiche/.test(sm.texte), 'HTTP sitemap : /bibliotheque oui, aucune fiche')
const rag = await get('/rag')
ok([301, 302].includes(rag.status) && /\/bibliotheque$/.test(rag.h.get('location') ?? ''), `HTTP /rag : ${rag.status} vers /bibliotheque`, rag.h.get('location') ?? '')
}
console.log(`\n${n - echecs}/${n} OK${echecs ? ` · ${echecs} ÉCHEC(S)` : ''}`)
process.exit(echecs ? 1 : 0)