#!/usr/bin/env node
/**
* Controlli di conformità sul sito compilato (brief §11.5). Ogni errore indica COSA non va e
* DOVE (file di dist/). Richiede `npm run build`. Uscita con codice 1 se c'è almeno un errore.
*
* I dati attesi (abilitazioni, servizi, P.IVA, professionisti) sono letti dalle stesse fonti
* del sito: src/data/studio.ts e src/content/servizi/*.md.
*/
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { DomUtils, parseDocument } from 'htmlparser2';
import { fileToPath, listHtmlFiles, readSitemapPaths } from './lib/pages.mjs';
import { root } from './lib/preview-server.mjs';
const dist = resolve(root, 'dist');
const { abilitazioni, professionisti, studio, contactForm } = await import(
resolve(root, 'src/data/studio.ts')
);
const SITE = (process.env.SITE_URL || 'https://www.grassoezio.it').replace(/\/+$/, '');
const PIVA = `P.IVA ${studio.partitaIva}`;
const LEGAL_PAGES = ['/privacy-policy/', '/cookie-policy/', '/note-legali/', '/accessibilita/'];
const NOINDEX_PAGES = ['/404.html', '/contatti/grazie/'];
const BUDGET_HTML_CSS = 120 * 1024;
const BUDGET_JS = 15 * 1024;
const BUDGET_FONTS = 110 * 1024;
const errors = [];
const fail = (where, what) => errors.push(`${where}: ${what}`);
let checks = 0;
const check = (ok, where, what) => {
checks++;
if (!ok) fail(where, what);
return ok;
};
/* ------------------------------------------------------------------ utilità DOM */
const { findAll, findOne, getAttributeValue: attr, textContent, getParent } = DomUtils;
const isTag = (n) => n.type === 'tag' || n.type === 'script' || n.type === 'style';
const all = (doc, pred) => findAll((n) => isTag(n) && pred(n), doc.children);
const byTag = (doc, name) => all(doc, (n) => n.name === name);
const normalize = (s) => s.replace(/\s+/g, ' ').replace(/[’‘]/g, "'").trim();
/** Testo visibile (esclusi script, style, noscript, template). */
function visibleText(node) {
if (node.type === 'text') return node.data;
if (!isTag(node) && node.type !== 'root') return '';
if (['script', 'style', 'noscript', 'template'].includes(node.name)) return '';
return (node.children ?? []).map(visibleText).join(' ');
}
const BLOCKS = new Set([
'p',
'li',
'dd',
'dt',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'td',
'th',
'address',
'figcaption',
'blockquote',
'label',
'button',
'a',
'title',
]);
/** Tutti i nodi di testo del documento (DomUtils.findAll restituisce solo elementi). */
function textNodes(node, out = []) {
for (const child of node.children ?? []) {
if (child.type === 'text') out.push(child);
else textNodes(child, out);
}
return out;
}
/** Divide in frasi senza spezzare abbreviazioni come «Dott.», «Dott.ssa», «n.», «sez.». */
function sentences(text) {
const protectedText = text.replace(
/\b(Dott|Dott\.ssa|Avv|Rag|Sig|n|nn|sez|art|artt|co|lett|par|D\.Lgs|D\.L|L|Reg|ecc|es|tel|p)\./gi,
(m) => m.replace(/\./g, '\u2024'),
);
return protectedText.split(/(?<=[.!?;])\s+/).map((s) => s.replace(/\u2024/g, '.'));
}
function closestBlock(node) {
let n = getParent(node);
while (n && !(isTag(n) && BLOCKS.has(n.name))) n = getParent(n);
return n;
}
function ancestorWithAttr(node, name, value) {
for (let n = getParent(node); n; n = getParent(n)) {
if (isTag(n) && attr(n, name) === value) return n;
}
return null;
}
/* ------------------------------------------------------------------ pagine */
check(existsSync(dist), 'dist/', 'cartella assente: esegui prima `npm run build`');
const htmlFiles = listHtmlFiles(dist);
const pages = htmlFiles.map((file) => {
const html = readFileSync(join(dist, file), 'utf8');
return { file: `dist/${file}`, path: fileToPath(file), html, doc: parseDocument(html) };
});
const byPath = new Map(pages.map((p) => [p.path, p]));
check(pages.length >= 18, 'dist/', `attese almeno 18 pagine HTML, trovate ${pages.length}`);
/* ------------------------------------------------------------------ file obbligatori */
for (const f of [
'.htaccess',
'404.html',
'robots.txt',
'sitemap-index.xml',
'favicon.svg',
'favicon.ico',
]) {
check(existsSync(join(dist, f)), `dist/${f}`, 'file obbligatorio mancante');
}
for (const p of LEGAL_PAGES) {
const page = byPath.get(p);
if (check(Boolean(page), `pagina ${p}`, 'pagina legale mancante')) {
check(byTag(page.doc, 'h1').length === 1, page.file, 'la pagina legale deve avere un
');
}
}
/* ------------------------------------------------------------------ robots e sitemap */
const robots = existsSync(join(dist, 'robots.txt'))
? readFileSync(join(dist, 'robots.txt'), 'utf8')
: '';
check(
robots.includes(`Sitemap: ${SITE}/sitemap-index.xml`),
'dist/robots.txt',
`manca la riga «Sitemap: ${SITE}/sitemap-index.xml»`,
);
check(
/User-agent:\s*\*/i.test(robots) && /Allow:\s*\//i.test(robots),
'dist/robots.txt',
'mancano User-agent/Allow',
);
const sitemapPaths = readSitemapPaths(dist);
const expectedInSitemap = pages
.map((p) => p.path)
.filter((p) => !NOINDEX_PAGES.includes(p))
.sort();
for (const p of expectedInSitemap)
check(sitemapPaths.includes(p), 'sitemap', `manca la pagina ${p}`);
for (const p of sitemapPaths) {
check(expectedInSitemap.includes(p), 'sitemap', `contiene ${p}, che non esiste o è noindex`);
}
for (const p of NOINDEX_PAGES) {
const page = byPath.get(p);
if (check(Boolean(page), `pagina ${p}`, 'pagina mancante')) {
const robotsMeta = findOne(
(n) => n.name === 'meta' && attr(n, 'name') === 'robots',
page.doc.children,
);
check(
/noindex/.test(attr(robotsMeta ?? {}, 'content') ?? ''),
page.file,
'manca ',
);
}
}
/* ------------------------------------------------------------------ controlli per pagina */
const PLACEHOLDERS = [
/\bTODO\b/,
/lorem/i,
/XXX/,
/\[da\b/i,
/\{\{|\}\}/,
/\bundefined\b/,
/\bnull\b/,
/NaN/,
];
const FORBIDDEN_REFS = [
/fonts\.googleapis\.com/i,
/gstatic/i,
/analytics/i,
/gtag/i,
/\bcdn\./i,
/googletagmanager/i,
];
const COMMERCIALISTA_OK =
/giulia|odcec|(ordine|consiglio nazionale) dei dottori commercialisti|\bocc\b|organismo di composizione della crisi/i;
const titles = new Map();
const descriptions = new Map();
const year = String(new Date().getFullYear());
for (const page of pages) {
const { doc, file, path, html } = page;
const where = `${file} (${path})`;
// lingua, viewport, titolo, descrizione, canonical
const htmlEl = byTag(doc, 'html')[0];
check(attr(htmlEl ?? {}, 'lang') === 'it', where, 'manca lang="it" su ');
const viewport = findOne(
(n) => n.name === 'meta' && attr(n, 'name') === 'viewport',
doc.children,
);
const vp = attr(viewport ?? {}, 'content') ?? '';
check(Boolean(viewport), where, 'manca il meta viewport');
check(
!/user-scalable\s*=\s*(no|0)|maximum-scale/i.test(vp),
where,
`meta viewport che blocca lo zoom: «${vp}»`,
);
const title = normalize(textContent(byTag(doc, 'title')[0] ?? { children: [] }));
check(
title.length > 0 && title.length <= 65,
where,
`titolo vuoto o oltre 65 caratteri: «${title}»`,
);
if (titles.has(title)) fail(where, `titolo duplicato di ${titles.get(title)}: «${title}»`);
titles.set(title, path);
const descEl = findOne(
(n) => n.name === 'meta' && attr(n, 'name') === 'description',
doc.children,
);
const desc = normalize(attr(descEl ?? {}, 'content') ?? '');
check(
desc.length >= 120 && desc.length <= 155,
where,
`descrizione di ${desc.length} caratteri (attesi 120–155)`,
);
if (descriptions.has(desc)) fail(where, `descrizione duplicata di ${descriptions.get(desc)}`);
descriptions.set(desc, path);
if (path !== '/404.html') {
const canonical = findOne(
(n) => n.name === 'link' && attr(n, 'rel') === 'canonical',
doc.children,
);
check(
attr(canonical ?? {}, 'href') === `${SITE}${path}`,
where,
`canonical atteso ${SITE}${path}, trovato ${attr(canonical ?? {}, 'href')}`,
);
}
// un solo h1
check(
byTag(doc, 'h1').length === 1,
where,
`attesa una sola intestazione , trovate ${byTag(doc, 'h1').length}`,
);
// footer: P.IVA, anno, link legali
const footer = byTag(doc, 'footer')[0];
const footerText = footer ? normalize(visibleText(footer)) : '';
check(footerText.includes(PIVA), where, `il footer non contiene «${PIVA}»`);
check(
footerText.includes(`© ${year}`),
where,
`il footer non contiene «© ${year}» (anno di build)`,
);
for (const legal of ['/privacy-policy/', '/cookie-policy/', '/note-legali/', '/accessibilita/']) {
const found = all(doc, (n) => n.name === 'a' && attr(n, 'href') === legal).length > 0;
check(found, where, `manca il link a ${legal}`);
}
// risorse: niente http://, niente domini vietati, niente iframe statici
for (const el of all(doc, () => true)) {
for (const name of ['src', 'href', 'srcset', 'action', 'data-map-src', 'poster']) {
const v = attr(el, name);
if (v && /^\s*http:\/\//i.test(v))
fail(where, `risorsa o link non sicuro (http://) in <${el.name} ${name}="${v}">`);
}
for (const [name, value] of Object.entries(el.attribs ?? {})) {
if (/^on[a-z]+$/i.test(name))
fail(where, `gestore di evento inline vietato dalla CSP: <${el.name} ${name}="${value}">`);
}
}
for (const re of FORBIDDEN_REFS)
check(!re.test(html), where, `riferimento vietato a ${re.source.replace(/\\/g, '')}`);
check(
byTag(doc, 'iframe').length === 0,
where,
"