fix: CI adattata a Forgejo, revisione completa del codice e avvio in debug
Le run della CI restavano «in attesa» perché l'unico runner dell'istanza («Ferrari») non si è mai collegato: il runner resta da configurare. La revisione completa del codice ha trovato anche difetti che avrebbero fatto fallire la CI con il runner online, oltre ad altri problemi del sito, dei controlli e della documentazione. CI e rilascio: - continue-on-error sullo step dei link esterni: Forgejo lo ignora sul job, e un sito esterno irraggiungibile avrebbe reso rossa la CI; - artifact con i file nascosti (report Lighthouse e .htaccess non venivano mai caricati); - token personale RELEASE_TOKEN: FORGEJO_TOKEN è riservato ed è sempre il token automatico; - dominio in un solo punto (site.config.mjs) e variabile del repository SITE_URL; - ripiego REST: release in bozza, file, poi pubblicazione; tag verificato sul server; sostituzione dei file senza mai lasciarli mancanti; - tar.gz identico su Windows, macOS e Linux (byte del sistema operativo nell'header gzip). Sito: CSS compatibile con Safari/iOS 15 (media query classiche, backdrop-filter), anello di focus con contrasto di almeno 3:1, bersagli touch di 44 px dove servono, intestazione desktop senza voci o logo a capo, HTML valido in /servizi/, colore delle chip, stampa senza mappe, giorni di apertura, ricerca e titolo delle mappe e numero breve ricavati dai dati. Modulo di contatto e contact.php: stesse regole nel browser e sul server (spazi, e-mail, a capo, lunghezze), tempo minimo misurato con un solo orologio (ts_invio), corpo in quoted-printable e oggetto RFC 2047, funzionamento con PHP a 32 bit, costante MODALITA_PREDEFINITA per attivarlo. Controlli e test: valori letti dai dati del sito, i sei servizi del brief con le ancore, «commercialista» anche in meta, attributi e dati strutturati, .htaccess su righe attive, HSTS attivabile con una scelta esplicita, contrasto del focus misurato nei test. Esempi di pubblicazione: nginx con gli header di sicurezza in un solo punto (HSTS compreso), deploy automatico che parte alla pubblicazione e sincronizza solo una cartella confermata, procedura nginx che toglie i file delle versioni precedenti. Debug: .vscode/launch.json e tasks.json, F5 avvia il server Astro e apre il browser con il debugger collegato. Documentazione aggiornata (README, DEPLOY, CONTENUTI, CONFORMITA, TODO-STUDIO, CHANGELOG) e decisioni D-045…D-055. Verificato: npm run verify su Windows e nel container della CI (Playwright 1.56.1, root); job dei link esterni in node:24; contact.php con PHP 7.4 e 8.3, a 64 e 32 bit; nginx in Docker; release-upload.sh e deploy di esempio contro API e shell simulate. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5aea990dc2
commit
3befe7e266
50 files changed
+1309
-338
No files matched your search
+208
-27
@@ -3,13 +3,16 @@
|
||||
* 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.
|
||||
* I dati attesi (abilitazioni, servizi, P.IVA, professionisti, orari e giorni di apertura,
|
||||
* dominio) sono letti dalle stesse fonti del sito: src/data/studio.ts,
|
||||
* src/content/servizi/*.md e site.config.mjs. Così una modifica dei contenuti fatta come indica
|
||||
* docs/CONTENUTI.md non fa fallire i controlli.
|
||||
*/
|
||||
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
||||
import { join, resolve } from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { DomUtils, parseDocument } from 'htmlparser2';
|
||||
import { siteUrl } from '../site.config.mjs';
|
||||
import { fileToPath, listHtmlFiles, readSitemapPaths } from './lib/pages.mjs';
|
||||
import { root } from './lib/preview-server.mjs';
|
||||
|
||||
@@ -21,7 +24,7 @@ const { abilitazioni, professionisti, studio, contactForm } = await importSrc('s
|
||||
// stesso anno del footer: SOURCE_DATE_EPOCH, se impostata, altrimenti l'anno corrente
|
||||
const { buildYear } = await importSrc('src/lib/build.ts');
|
||||
|
||||
const SITE = (process.env.SITE_URL || 'https://www.grassoezio.it').replace(/\/+$/, '');
|
||||
const SITE = siteUrl();
|
||||
const PIVA = `P.IVA ${studio.partitaIva}`;
|
||||
const LEGAL_PAGES = ['/privacy-policy/', '/cookie-policy/', '/note-legali/', '/accessibilita/'];
|
||||
const NOINDEX_PAGES = ['/404.html', '/contatti/grazie/'];
|
||||
@@ -100,6 +103,24 @@ function closestBlock(node) {
|
||||
return n;
|
||||
}
|
||||
|
||||
/** Problemi di compatibilità nel CSS generato (pagina HTML o file .css). */
|
||||
function cssIssues(css) {
|
||||
checks++;
|
||||
const issues = [];
|
||||
const range = css.match(/@media[^{]*\(\s*(?:width|height)\s*[<>]/);
|
||||
if (range) {
|
||||
issues.push(
|
||||
`media query in sintassi a intervallo «${range[0]}…»: controllare vite.build.cssTarget in astro.config.mjs`,
|
||||
);
|
||||
}
|
||||
for (const block of css.match(/\{[^{}]*-webkit-backdrop-filter:[^{}]*\}/g) ?? []) {
|
||||
if (!/[{;]\s*backdrop-filter:/.test(block)) {
|
||||
issues.push(`-webkit-backdrop-filter senza backdrop-filter: «${block.slice(0, 80)}…»`);
|
||||
}
|
||||
}
|
||||
return issues;
|
||||
}
|
||||
|
||||
function ancestorWithAttr(node, name, value) {
|
||||
for (let n = getParent(node); n; n = getParent(n)) {
|
||||
if (isTag(n) && attr(n, name) === value) return n;
|
||||
@@ -201,10 +222,68 @@ const FORBIDDEN_REFS = [
|
||||
];
|
||||
const COMMERCIALISTA_OK =
|
||||
/giulia|odcec|(ordine|consiglio nazionale) dei dottori commercialisti|\bocc\b|organismo di composizione della crisi/i;
|
||||
const DICITURE_VIETATE = [
|
||||
'studio commercialista',
|
||||
'studio di commercialisti',
|
||||
'studio di commercialista',
|
||||
'commercialista ezio',
|
||||
'ezio grasso, commercialista',
|
||||
'ezio grasso commercialista',
|
||||
];
|
||||
const giulia = professionisti.find((p) => p.id === 'giulia-grasso');
|
||||
|
||||
/**
|
||||
* Testi non visibili che finiscono nei risultati di ricerca, nelle anteprime o agli screen
|
||||
* reader: meta (description, Open Graph, Twitter), attributi alt/title/aria-label e stringhe del
|
||||
* JSON-LD, esclusa la scheda della Dott.ssa Giulia Grasso. Coppie [provenienza, testo].
|
||||
*/
|
||||
function hiddenTexts(doc, ldNodes) {
|
||||
const out = [];
|
||||
for (const el of all(doc, (n) => n.name === 'meta')) {
|
||||
const key = attr(el, 'name') ?? attr(el, 'property') ?? '';
|
||||
if (/^(description$|og:|twitter:)/.test(key))
|
||||
out.push([`meta ${key}`, attr(el, 'content') ?? '']);
|
||||
}
|
||||
for (const el of all(doc, () => true)) {
|
||||
for (const n of ['alt', 'title', 'aria-label', 'data-map-title']) {
|
||||
const v = attr(el, n);
|
||||
if (v) out.push([`attributo ${n} di <${el.name}>`, v]);
|
||||
}
|
||||
}
|
||||
const walk = (value, path) => {
|
||||
if (typeof value === 'string') out.push([`JSON-LD ${path}`, value]);
|
||||
else if (Array.isArray(value)) value.forEach((v, i) => walk(v, `${path}[${i}]`));
|
||||
else if (value && typeof value === 'object') {
|
||||
if (value['@type'] === 'Person' && value.name === giulia?.nomeSenzaTitolo) return;
|
||||
for (const [k, v] of Object.entries(value)) walk(v, `${path}.${k}`);
|
||||
}
|
||||
};
|
||||
for (const n of ldNodes) walk(n, String(n['@type'] ?? 'nodo'));
|
||||
return out;
|
||||
}
|
||||
const titles = new Map();
|
||||
const descriptions = new Map();
|
||||
const year = String(buildYear);
|
||||
|
||||
// orari e giorni di apertura: formato dei dati in studio.ts e valore atteso nel JSON-LD
|
||||
const HHMM = /^([01]\d|2[0-3]):[0-5]\d$/;
|
||||
for (const f of studio.orari.fasce) {
|
||||
check(
|
||||
HHMM.test(f.apertura) && HHMM.test(f.chiusura) && f.apertura < f.chiusura,
|
||||
'src/data/studio.ts',
|
||||
`fascia oraria non valida «${f.apertura}–${f.chiusura}» (formato HH:MM, apertura prima della chiusura)`,
|
||||
);
|
||||
}
|
||||
check(
|
||||
studio.orari.giorniSettimana.length > 0,
|
||||
'src/data/studio.ts',
|
||||
'orari.giorniSettimana vuoto: indicare i giorni di apertura',
|
||||
);
|
||||
const EXPECTED_HOURS = studio.orari.fasce
|
||||
.map((f) => `${f.apertura}-${f.chiusura}`)
|
||||
.sort()
|
||||
.join(',');
|
||||
|
||||
for (const page of pages) {
|
||||
const { doc, file, path, html } = page;
|
||||
const where = `${file} (${path})`;
|
||||
@@ -383,14 +462,7 @@ for (const page of pages) {
|
||||
}
|
||||
}
|
||||
const lower = normalize(text).toLowerCase();
|
||||
for (const bad of [
|
||||
'studio commercialista',
|
||||
'studio di commercialisti',
|
||||
'studio di commercialista',
|
||||
'commercialista ezio',
|
||||
'ezio grasso, commercialista',
|
||||
'ezio grasso commercialista',
|
||||
]) {
|
||||
for (const bad of DICITURE_VIETATE) {
|
||||
check(!lower.includes(bad), where, `dicitura vietata «${bad}»`);
|
||||
}
|
||||
|
||||
@@ -414,6 +486,24 @@ for (const page of pages) {
|
||||
fail(where, `JSON-LD non valido: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// «commercialista» anche nei testi non visibili (meta, attributi, JSON-LD): ogni stringa è
|
||||
// controllata da sola, con le stesse regole del testo visibile
|
||||
for (const [origin, value] of hiddenTexts(doc, nodes)) {
|
||||
const t = normalize(value);
|
||||
if (!/commercialist/i.test(t)) continue;
|
||||
for (const s of sentences(t).filter((x) => /commercialist/i.test(x))) {
|
||||
check(
|
||||
COMMERCIALISTA_OK.test(s),
|
||||
where,
|
||||
`«commercialista» usato fuori contesto in ${origin} (ammesso solo per la Dott.ssa Giulia Grasso, ODCEC, OCC): «${s}»`,
|
||||
);
|
||||
}
|
||||
for (const bad of DICITURE_VIETATE) {
|
||||
check(!t.toLowerCase().includes(bad), where, `dicitura vietata «${bad}» in ${origin}`);
|
||||
}
|
||||
}
|
||||
|
||||
const org = nodes.find((n) => n['@type'] === 'AccountingService');
|
||||
if (check(Boolean(org), where, 'JSON-LD: manca AccountingService')) {
|
||||
for (const k of [
|
||||
@@ -461,10 +551,17 @@ for (const page of pages) {
|
||||
.sort()
|
||||
.join(',');
|
||||
check(
|
||||
hours === '09:00-12:30,15:00-18:30',
|
||||
hours === EXPECTED_HOURS,
|
||||
where,
|
||||
`JSON-LD: orari attesi 09:00-12:30 e 15:00-18:30, trovati ${hours}`,
|
||||
`JSON-LD: orari attesi ${EXPECTED_HOURS} (studio.orari.fasce), trovati ${hours}`,
|
||||
);
|
||||
for (const h of org.openingHoursSpecification ?? []) {
|
||||
check(
|
||||
JSON.stringify(h.dayOfWeek) === JSON.stringify(studio.orari.giorniSettimana),
|
||||
where,
|
||||
`JSON-LD: giorni di apertura ${JSON.stringify(h.dayOfWeek)} diversi da studio.orari.giorniSettimana`,
|
||||
);
|
||||
}
|
||||
const people = (org.employee ?? org.founder ?? []).filter((p) => p['@type'] === 'Person');
|
||||
check(people.length === professionisti.length, where, 'JSON-LD: professionisti mancanti');
|
||||
for (const p of professionisti) {
|
||||
@@ -491,6 +588,14 @@ for (const page of pages) {
|
||||
}
|
||||
}
|
||||
|
||||
// CSS compatibile con i browser di vite.build.cssTarget (astro.config.mjs): media query con
|
||||
// min-/max-width (la sintassi a intervallo non funziona su Safari/iOS < 16.4) e
|
||||
// backdrop-filter anche senza prefisso (Chrome, Edge e Firefox ignorano -webkit-)
|
||||
for (const issue of cssIssues(html)) fail(where, issue);
|
||||
|
||||
// nulla dopo </html> (es. uno <script> scritto fuori dal layout: errore di parsing HTML)
|
||||
check(/<\/html>\s*$/i.test(html), where, 'contenuto dopo </html>: spostarlo dentro il layout');
|
||||
|
||||
// budget HTML + CSS (il CSS è incluso nella pagina)
|
||||
const size = statSync(join(dist, file.replace(/^dist\//, ''))).size;
|
||||
check(
|
||||
@@ -523,7 +628,36 @@ function servicesFromCollection() {
|
||||
}
|
||||
|
||||
const servizi = servicesFromCollection();
|
||||
check(servizi.length === 6, 'src/content/servizi', `attesi 6 servizi, trovati ${servizi.length}`);
|
||||
// almeno i 6 servizi del brief (§4.5): se ne possono aggiungere altri (docs/CONTENUTI.md)
|
||||
check(
|
||||
servizi.length >= 6,
|
||||
'src/content/servizi',
|
||||
`attesi almeno i 6 servizi del brief, trovati ${servizi.length}`,
|
||||
);
|
||||
// i sei servizi del brief (§4.5) con l'ancora del vecchio sito (§5.3): requisiti, non contenuti
|
||||
const SERVIZI_BRIEF = [
|
||||
['consulenza-fiscale-tributaria-e-societaria', 'consulenza-fiscale-tributaria-e-societaria-1'],
|
||||
['contabilita-fiscale', 'contabilita-fiscale-2'],
|
||||
['contenzioso-tributario', 'contenzioso-tributario-3'],
|
||||
['centro-autorizzato-caf', 'centro-autorizzato-caf-4'],
|
||||
['servizi-imprese-dipendenti-pensionati', 'servizi-alle-imprese-dipendenti-e-pensionati-5'],
|
||||
['certificazione-atti-firma-digitale', 'certificazione-atti-mediante-firma-digitale-6'],
|
||||
];
|
||||
for (const [slug, anchor] of SERVIZI_BRIEF) {
|
||||
check(
|
||||
servizi.some((s) => s.slug === slug && s.anchor === anchor),
|
||||
'src/content/servizi',
|
||||
`manca il servizio del brief /servizi/${slug}/ con anchorLegacy «${anchor}» (link del vecchio sito)`,
|
||||
);
|
||||
}
|
||||
for (const [key, label] of [
|
||||
['slug', 'slug'],
|
||||
['anchor', 'anchorLegacy'],
|
||||
]) {
|
||||
const values = servizi.map((s) => s[key]);
|
||||
const repeated = [...new Set(values.filter((v, i) => values.indexOf(v) !== i))];
|
||||
check(repeated.length === 0, 'src/content/servizi', `${label} ripetuti: ${repeated.join(', ')}`);
|
||||
}
|
||||
const hub = byPath.get('/servizi/');
|
||||
const home = byPath.get('/');
|
||||
for (const s of servizi) {
|
||||
@@ -619,11 +753,13 @@ if (contatti) {
|
||||
contatti.file,
|
||||
'campo honeypot assente o raggiungibile da tastiera',
|
||||
);
|
||||
check(
|
||||
all(contatti.doc, (n) => n.name === 'input' && attr(n, 'name') === 'ts').length === 1,
|
||||
contatti.file,
|
||||
'campo ts assente',
|
||||
);
|
||||
for (const name of ['ts', 'ts_invio']) {
|
||||
check(
|
||||
all(contatti.doc, (n) => n.name === 'input' && attr(n, 'name') === name).length === 1,
|
||||
contatti.file,
|
||||
`campo ${name} assente`,
|
||||
);
|
||||
}
|
||||
const privacy = all(
|
||||
contatti.doc,
|
||||
(n) =>
|
||||
@@ -633,6 +769,22 @@ if (contatti) {
|
||||
}
|
||||
}
|
||||
|
||||
// gestore PHP del modulo: nel sito solo con contactForm.mode = 'php' (docs/DEPLOY.md, sezione 6)
|
||||
const phpHandler = existsSync(join(dist, 'contact.php'));
|
||||
if (contactForm.mode === 'php') {
|
||||
check(
|
||||
phpHandler,
|
||||
'dist/contact.php',
|
||||
'contactForm.mode = "php" ma contact.php manca: copiare deploy/optional-php-form/contact.php in public/',
|
||||
);
|
||||
} else {
|
||||
check(
|
||||
!phpHandler,
|
||||
'dist/contact.php',
|
||||
`contact.php pubblicato con contactForm.mode = "${contactForm.mode}": toglierlo da public/ (la privacy policy non lo descrive)`,
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ asset */
|
||||
|
||||
const astroDir = join(dist, '_astro');
|
||||
@@ -647,6 +799,7 @@ check(
|
||||
);
|
||||
for (const f of assets.filter((x) => /\.(js|css)$/.test(x))) {
|
||||
const src = readFileSync(join(astroDir, f), 'utf8');
|
||||
if (f.endsWith('.css')) for (const issue of cssIssues(src)) fail(`dist/_astro/${f}`, issue);
|
||||
for (const re of FORBIDDEN_REFS)
|
||||
check(
|
||||
!re.test(src),
|
||||
@@ -692,22 +845,50 @@ check(
|
||||
const htaccess = existsSync(join(dist, '.htaccess'))
|
||||
? readFileSync(join(dist, '.htaccess'), 'utf8')
|
||||
: '';
|
||||
// direttive cercate solo su righe attive (non commentate)
|
||||
for (const [re, what] of [
|
||||
[/ErrorDocument 404 \/404\.html/, 'ErrorDocument 404 /404.html'],
|
||||
[/^\s*ErrorDocument 404 \/404\.html\s*$/m, 'ErrorDocument 404 /404.html'],
|
||||
[
|
||||
/RedirectMatch 301 \^\/privacy\/\?\$ \/privacy-policy\//,
|
||||
/^\s*RedirectMatch 301 \^\/privacy\/\?\$ \/privacy-policy\/\s*$/m,
|
||||
'redirect /privacy → /privacy-policy/',
|
||||
],
|
||||
[/X-Content-Type-Options "nosniff"/, 'X-Content-Type-Options'],
|
||||
[/Referrer-Policy "strict-origin-when-cross-origin"/, 'Referrer-Policy'],
|
||||
[/Permissions-Policy/, 'Permissions-Policy'],
|
||||
[/X-Frame-Options "SAMEORIGIN"/, 'X-Frame-Options'],
|
||||
[/#\s*Header always set Strict-Transport-Security/, 'HSTS presente ma commentato'],
|
||||
[/\\\.map\$/, 'blocco dei file .map'],
|
||||
[/^\s*Header always set X-Content-Type-Options "nosniff"\s*$/m, 'X-Content-Type-Options'],
|
||||
[
|
||||
/^\s*Header always set Referrer-Policy "strict-origin-when-cross-origin"\s*$/m,
|
||||
'Referrer-Policy',
|
||||
],
|
||||
[/^\s*Header always set Permissions-Policy "[^"]+"\s*$/m, 'Permissions-Policy'],
|
||||
[/^\s*Header always set X-Frame-Options "SAMEORIGIN"\s*$/m, 'X-Frame-Options'],
|
||||
[/^\s*<FilesMatch "[^"]*\\\.map\$[^"]*">/m, 'blocco dei file .map'],
|
||||
]) {
|
||||
check(re.test(htaccess), 'dist/.htaccess', `manca: ${what}`);
|
||||
}
|
||||
|
||||
// HSTS: commentato finché HTTPS non è verificato su tutto il dominio. Per attivarlo decommentare
|
||||
// la riga in public/.htaccess E impostare qui HSTS_ATTIVO = true (docs/DEPLOY.md, sezione 2).
|
||||
const HSTS_ATTIVO = false;
|
||||
const hsts = /^\s*Header always set Strict-Transport-Security "max-age=(\d+)[^"]*"\s*$/m.exec(
|
||||
htaccess,
|
||||
);
|
||||
if (HSTS_ATTIVO) {
|
||||
check(
|
||||
Boolean(hsts) && Number(hsts[1]) >= 31536000,
|
||||
'dist/.htaccess',
|
||||
'HSTS_ATTIVO = true ma Strict-Transport-Security non è attivo (max-age di almeno un anno)',
|
||||
);
|
||||
} else {
|
||||
check(
|
||||
/^\s*#\s*Header always set Strict-Transport-Security/m.test(htaccess),
|
||||
'dist/.htaccess',
|
||||
'manca la riga di HSTS (commentata)',
|
||||
);
|
||||
check(
|
||||
!/^\s*Header always set Strict-Transport-Security/m.test(htaccess),
|
||||
'dist/.htaccess',
|
||||
'HSTS attivo: se HTTPS è verificato su tutto il dominio impostare HSTS_ATTIVO = true in scripts/check-compliance.mjs',
|
||||
);
|
||||
}
|
||||
|
||||
// Content-Security-Policy di §9.4, confrontata per direttive. Con il modulo esterno
|
||||
// (`contactForm.mode = 'endpoint'`) form-action deve ammettere anche l'origine del fornitore.
|
||||
const EXPECTED_CSP = {
|
||||
|
||||
@@ -10,13 +10,14 @@
|
||||
*/
|
||||
import { resolve } from 'node:path';
|
||||
import { LinkChecker, LinkState } from 'linkinator';
|
||||
import { siteUrl } from '../site.config.mjs';
|
||||
import { EXTRA_PAGES, readSitemapPaths } from './lib/pages.mjs';
|
||||
import { root, startPreview } from './lib/preview-server.mjs';
|
||||
|
||||
const external = process.argv.includes('--external');
|
||||
// URL assoluti del sito (canonical, og:url, og:image, JSON-LD): controllati sulla build locale,
|
||||
// non sul dominio di produzione, che prima della pubblicazione ospita ancora il vecchio sito.
|
||||
const SITE = (process.env.SITE_URL || 'https://www.grassoezio.it').replace(/\/+$/, '');
|
||||
const SITE = siteUrl();
|
||||
const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const dist = resolve(root, 'dist');
|
||||
const seeds = [...readSitemapPaths(dist), ...EXTRA_PAGES];
|
||||
|
||||
+21
-3
@@ -8,17 +8,19 @@
|
||||
* BUILD-INFO.txt versione, commit, data, Node, Astro
|
||||
*
|
||||
* Il contenuto di dist/ è alla radice degli archivi (nessuna cartella di primo livello), con
|
||||
* `.htaccess`. Voci ordinate e date fisse: a parità di dist/ gli archivi sono identici.
|
||||
* `.htaccess`. Voci ordinate, date fisse e header gzip senza il sistema operativo: a parità di
|
||||
* dist/ (e di versione di Node.js) gli archivi sono identici anche tra Windows, macOS e Linux.
|
||||
* Versione: variabile RELEASE_VERSION (tag vX.Y.Z) oppure package.json.
|
||||
*/
|
||||
process.env.TZ = 'UTC';
|
||||
|
||||
import { createHash } from 'node:crypto';
|
||||
import { createReadStream, createWriteStream, existsSync, readFileSync, statSync } from 'node:fs';
|
||||
import { mkdir, rm, writeFile } from 'node:fs/promises';
|
||||
import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
||||
import { join, resolve } from 'node:path';
|
||||
import { pipeline } from 'node:stream/promises';
|
||||
import { TarArchive, ZipArchive } from 'archiver';
|
||||
import { siteUrl } from '../site.config.mjs';
|
||||
import {
|
||||
archiveEpoch,
|
||||
archiveNames,
|
||||
@@ -63,8 +65,24 @@ async function build(archive, target) {
|
||||
await done;
|
||||
}
|
||||
|
||||
/**
|
||||
* Il byte 9 dell'header gzip indica il sistema operativo (zlib scrive 10 su Windows, 19 su
|
||||
* macOS, 3 altrove): lo si fissa a 3 (Unix) così il tar.gz non dipende dalla piattaforma.
|
||||
* Il byte non è coperto da alcun CRC (flag FHCRC assente; il CRC finale riguarda i dati).
|
||||
*/
|
||||
async function normalizeGzipOs(file) {
|
||||
const buf = await readFile(file);
|
||||
const isGzip = buf[0] === 0x1f && buf[1] === 0x8b && buf[2] === 8;
|
||||
if (!isGzip || (buf[3] & 0x02) !== 0) throw new Error(`${file}: header gzip inatteso`);
|
||||
if (buf[9] !== 3) {
|
||||
buf[9] = 3;
|
||||
await writeFile(file, buf);
|
||||
}
|
||||
}
|
||||
|
||||
await build(new ZipArchive({ zlib: { level: 9 } }), join(releaseDir, names.zip));
|
||||
await build(new TarArchive({ gzip: true, gzipOptions: { level: 9 } }), join(releaseDir, names.tgz));
|
||||
await normalizeGzipOs(join(releaseDir, names.tgz));
|
||||
|
||||
const sha256 = (file) =>
|
||||
new Promise((ok, ko) => {
|
||||
@@ -85,7 +103,7 @@ const info = [
|
||||
`Data dei file negli archivi: ${date.toISOString()}`,
|
||||
`Node.js: ${process.version}`,
|
||||
`Astro: ${astroVersion}`,
|
||||
`SITE_URL: ${process.env.SITE_URL || 'https://www.grassoezio.it'}`,
|
||||
`SITE_URL: ${siteUrl()}`,
|
||||
`File: ${files.length}`,
|
||||
'',
|
||||
'Pubblicazione: estrarre il contenuto dell’archivio nella cartella pubblica del sito',
|
||||
|
||||
+61
-20
@@ -9,9 +9,14 @@
|
||||
# FORGEJO_TOKEN=<token con permesso write:repository> \
|
||||
# scripts/release-upload.sh v1.0.0 [cartella] # cartella predefinita: release
|
||||
#
|
||||
# Prima eseguire `npm run package` con RELEASE_VERSION=v1.0.0. Il tag deve già esistere
|
||||
# sul server (git push origin v1.0.0). Le note della release sono prese da CHANGELOG.md.
|
||||
# Se la release esiste già, i file con lo stesso nome vengono sostituiti.
|
||||
# Prima eseguire `npm run package` con RELEASE_VERSION=v1.0.0 e pubblicare il tag
|
||||
# (git push origin v1.0.0): lo script si ferma se il tag non è sul server oppure se punta a
|
||||
# un commit diverso dal tag locale. Le note della release sono prese da CHANGELOG.md.
|
||||
#
|
||||
# Come l'action, una release nuova viene creata in bozza, riceve i file e solo alla fine viene
|
||||
# pubblicata. Se la release esiste già (anche come bozza lasciata dall'action), i file con lo
|
||||
# stesso nome vengono sostituiti (prima si carica il nuovo, poi si cancella il vecchio) e la
|
||||
# release viene pubblicata con titolo e note del CHANGELOG.
|
||||
# =============================================================================
|
||||
set -euo pipefail
|
||||
|
||||
@@ -31,33 +36,69 @@ command -v node >/dev/null || die "node non installato"
|
||||
API="${FORGEJO_URL%/}/api/v1/repos/${FORGEJO_REPO}"
|
||||
AUTH="Authorization: token ${FORGEJO_TOKEN}"
|
||||
|
||||
json_field() { node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{const v=JSON.parse(s)[process.argv[1]];if(v===undefined)process.exit(1);console.log(typeof v==="object"?JSON.stringify(v):v)})' "$1"; }
|
||||
# Valore di un campo (anche annidato: «commit.sha») di un oggetto JSON letto da stdin.
|
||||
json_field() { node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{let v=JSON.parse(s);for(const k of process.argv[1].split("."))v=v==null?undefined:v[k];if(v===undefined)process.exit(1);console.log(typeof v==="object"?JSON.stringify(v):v)})' "$1"; }
|
||||
# Id degli asset con un certo nome, da un elenco JSON letto da stdin.
|
||||
asset_ids() { node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{console.log(JSON.parse(s).filter(a=>a.name===process.argv[1]).map(a=>a.id).join(" "))})' "$1"; }
|
||||
urlencode() { node -e 'console.log(encodeURIComponent(process.argv[1]))' "$1"; }
|
||||
|
||||
TAG_URL="$(urlencode "$TAG")"
|
||||
NOTES="$(node scripts/changelog-notes.mjs "$TAG")"
|
||||
PAYLOAD="$(node -e 'console.log(JSON.stringify({tag_name:process.argv[1],name:process.argv[1],body:process.argv[2],draft:false,prerelease:/-/.test(process.argv[1])}))' "$TAG" "$NOTES")"
|
||||
PRERELEASE=false
|
||||
case "$TAG" in *-*) PRERELEASE=true ;; esac
|
||||
# Dati della release; $1 = true per la bozza, false per pubblicarla.
|
||||
payload() {
|
||||
node -e 'console.log(JSON.stringify({tag_name:process.argv[1],name:process.argv[1],body:process.argv[2],draft:process.argv[3]==="true",prerelease:process.argv[4]==="true"}))' \
|
||||
"$TAG" "$NOTES" "$1" "$PRERELEASE"
|
||||
}
|
||||
|
||||
echo "→ Release $TAG su $FORGEJO_REPO"
|
||||
if EXISTING="$(curl -fsS -H "$AUTH" "$API/releases/tags/$TAG" 2>/dev/null)"; then
|
||||
RELEASE_ID="$(printf '%s' "$EXISTING" | json_field id)"
|
||||
echo " release già esistente (id $RELEASE_ID): aggiornamento dei file"
|
||||
else
|
||||
CREATED="$(curl -fsS -X POST -H "$AUTH" -H 'Content-Type: application/json' -d "$PAYLOAD" "$API/releases")" \
|
||||
|| die "creazione della release non riuscita (permessi del token? il tag esiste sul server?)"
|
||||
RELEASE_ID="$(printf '%s' "$CREATED" | json_field id)"
|
||||
echo " release creata (id $RELEASE_ID)"
|
||||
|
||||
# 1) il tag deve essere già sul server: senza, Forgejo lo creerebbe sulla punta del branch
|
||||
# predefinito (un altro commit) e avvierebbe release.yml
|
||||
TAG_JSON="$(curl -fsS -H "$AUTH" "$API/tags/$TAG_URL")" \
|
||||
|| die "tag $TAG assente sul server (o token senza accesso al repository): eseguire prima git push origin $TAG"
|
||||
SERVER_SHA="$(printf '%s' "$TAG_JSON" | json_field commit.sha)" || die "risposta inattesa per il tag $TAG"
|
||||
if LOCAL_SHA="$(git rev-parse --verify --quiet "refs/tags/$TAG^{commit}" 2>/dev/null)"; then
|
||||
[ "$LOCAL_SHA" = "$SERVER_SHA" ] \
|
||||
|| die "il tag $TAG sul server punta a $SERVER_SHA, quello locale a $LOCAL_SHA: pacchetto e tag non coincidono"
|
||||
fi
|
||||
|
||||
ASSETS="$(curl -fsS -H "$AUTH" "$API/releases/$RELEASE_ID/assets")"
|
||||
# 2) release esistente (pubblicata o bozza) oppure nuova bozza
|
||||
if EXISTING="$(curl -fsS -H "$AUTH" "$API/releases/tags/$TAG_URL" 2>/dev/null)"; then
|
||||
RELEASE_ID="$(printf '%s' "$EXISTING" | json_field id)"
|
||||
if [ "$(printf '%s' "$EXISTING" | json_field draft)" = "true" ]; then
|
||||
echo " bozza già esistente (id $RELEASE_ID): caricamento dei file e pubblicazione"
|
||||
else
|
||||
echo " release già pubblicata (id $RELEASE_ID): sostituzione dei file con lo stesso nome"
|
||||
fi
|
||||
else
|
||||
CREATED="$(curl -fsS -X POST -H "$AUTH" -H 'Content-Type: application/json' -d "$(payload true)" "$API/releases")" \
|
||||
|| die "creazione della release non riuscita (il token ha il permesso write:repository?)"
|
||||
RELEASE_ID="$(printf '%s' "$CREATED" | json_field id)"
|
||||
echo " bozza creata (id $RELEASE_ID)"
|
||||
fi
|
||||
|
||||
# 3) file: prima il nuovo, poi la cancellazione dell'eventuale versione precedente, così un
|
||||
# errore a metà non lascia la release senza quel file
|
||||
ASSETS="$(curl -fsS -H "$AUTH" "$API/releases/$RELEASE_ID/assets")" \
|
||||
|| die "elenco dei file della release $RELEASE_ID non disponibile"
|
||||
for FILE in "$DIR"/*; do
|
||||
[ -f "$FILE" ] || continue
|
||||
NAME="$(basename "$FILE")"
|
||||
OLD_ID="$(printf '%s' "$ASSETS" | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{const a=JSON.parse(s).find(x=>x.name===process.argv[1]);if(a)console.log(a.id)})' "$NAME")"
|
||||
if [ -n "$OLD_ID" ]; then
|
||||
curl -fsS -X DELETE -H "$AUTH" "$API/releases/$RELEASE_ID/assets/$OLD_ID" >/dev/null
|
||||
fi
|
||||
OLD_IDS="$(printf '%s' "$ASSETS" | asset_ids "$NAME")"
|
||||
curl -fsS -X POST -H "$AUTH" -F "attachment=@${FILE}" \
|
||||
"$API/releases/$RELEASE_ID/assets?name=$(node -e 'console.log(encodeURIComponent(process.argv[1]))' "$NAME")" >/dev/null \
|
||||
"$API/releases/$RELEASE_ID/assets?name=$(urlencode "$NAME")" >/dev/null \
|
||||
|| die "caricamento di $NAME non riuscito"
|
||||
echo " ✔ $NAME"
|
||||
for OLD_ID in $OLD_IDS; do
|
||||
curl -fsS -X DELETE -H "$AUTH" "$API/releases/$RELEASE_ID/assets/$OLD_ID" >/dev/null \
|
||||
|| die "cancellazione della versione precedente di $NAME (id $OLD_ID) non riuscita"
|
||||
done
|
||||
echo " ✔ $NAME${OLD_IDS:+ (sostituito)}"
|
||||
done
|
||||
|
||||
# 4) pubblicazione (o aggiornamento di titolo e note) solo con tutti i file caricati
|
||||
curl -fsS -X PATCH -H "$AUTH" -H 'Content-Type: application/json' -d "$(payload false)" \
|
||||
"$API/releases/$RELEASE_ID" >/dev/null \
|
||||
|| die "pubblicazione non riuscita: la release $RELEASE_ID potrebbe essere rimasta in bozza"
|
||||
echo "✔ Release $TAG pubblicata: ${FORGEJO_URL%/}/${FORGEJO_REPO}/releases/tag/$TAG"
|
||||
@@ -33,8 +33,11 @@ const paths = [...readSitemapPaths(resolve(root, 'dist')), ...EXTRA_PAGES].filte
|
||||
);
|
||||
await mkdir(outDir, { recursive: true });
|
||||
const server = await startPreview();
|
||||
const browser = await chromium.launch();
|
||||
// browser avviato dentro il try: se non parte (Chromium mancante) il server viene comunque
|
||||
// fermato, invece di restare attivo in background su Linux e macOS
|
||||
let browser;
|
||||
try {
|
||||
browser = await chromium.launch();
|
||||
for (const vp of viewports) {
|
||||
const context = await browser.newContext({
|
||||
viewport: { width: vp.width, height: vp.height },
|
||||
@@ -55,6 +58,6 @@ try {
|
||||
await context.close();
|
||||
}
|
||||
} finally {
|
||||
await browser.close();
|
||||
await browser?.close().catch(() => {});
|
||||
await server.stop();
|
||||
}
|
||||
Reference in new issue
Block a user