/** * Avvia `astro preview` su una porta libera e restituisce l'URL base e una funzione di stop. * Usato dagli script che devono navigare il sito compilato (link, screenshot). */ import { spawn } from 'node:child_process'; import { existsSync } from 'node:fs'; import { createServer } from 'node:net'; import { resolve } from 'node:path'; export const root = resolve(import.meta.dirname, '..', '..'); async function freePort(preferred) { const tryPort = (port) => new Promise((ok) => { const srv = createServer(); srv.once('error', () => ok(null)); srv.listen(port, '127.0.0.1', () => srv.close(() => ok(port))); }); return (await tryPort(preferred)) ?? (await tryPort(0)); } export async function startPreview({ port = 4322 } = {}) { if (!existsSync(resolve(root, 'dist', 'index.html'))) { throw new Error('Cartella dist/ assente: esegui prima `npm run build`.'); } const p = await freePort(port); const astroBin = resolve(root, 'node_modules', 'astro', 'bin', 'astro.mjs'); const child = spawn( process.execPath, [astroBin, 'preview', '--host', '127.0.0.1', '--port', String(p), '--ignore-lock'], { cwd: root, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, ASTRO_TELEMETRY_DISABLED: '1' }, }, ); let output = ''; child.stdout.on('data', (d) => (output += d)); child.stderr.on('data', (d) => (output += d)); const base = `http://127.0.0.1:${p}`; const deadline = Date.now() + 30_000; for (;;) { try { const res = await fetch(`${base}/`); if (res.ok) break; } catch { // server non ancora pronto } if (child.exitCode !== null || Date.now() > deadline) { child.kill(); throw new Error(`Impossibile avviare astro preview:\n${output}`); } await new Promise((r) => setTimeout(r, 250)); } return { base, stop: () => new Promise((ok) => { if (child.exitCode !== null) return ok(); child.once('exit', () => ok()); child.kill('SIGTERM'); }), }; }