import { existsSync, readdirSync, readFileSync } from 'node:fs'; import { readFile } from 'node:fs/promises'; import { extname, join, relative, sep } from 'node:path'; import { escapeHtml, type Font, type LegalPage } from '@homepage/indexer'; export type Asset = { body: Buffer; type: string; /** Vite puts a content hash into every file name below assets/. */ immutable: boolean; }; const TYPES: Record = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.woff': 'font/woff', '.woff2': 'font/woff2', '.txt': 'text/plain; charset=utf-8', }; function walk(directory: string): string[] { return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => { const path = join(directory, entry.name); if (entry.isDirectory()) return walk(path); return entry.isFile() ? [path] : []; }); } /** Loads the built frontend into memory, keyed by URL path. The index page is also served at "/". */ export function loadAssets(directory: string): Map { const assets = new Map(); if (!existsSync(directory)) return assets; for (const file of walk(directory)) { const path = `/${relative(directory, file).split(sep).join('/')}`; assets.set(path, { body: readFileSync(file), type: TYPES[extname(file)] ?? 'application/octet-stream', immutable: path.startsWith('/assets/'), }); } const index = assets.get('/index.html'); if (index) assets.set('/', index); return assets; } /** * Writes the configured legal pages into the header of the terminal page, * which the frontend build cannot know. Without legal pages the header has no links. */ export function setLegalLinks(assets: Map, legal: LegalPage[]): void { const index = assets.get('/index.html'); if (!index) return; const links = legal.map((page) => { const english = page.aliases[0] ? ` data-en="${escapeHtml(page.aliases[0])}"` : ''; return `${escapeHtml(page.route)}`; }); const html = index.body.toString('utf8').replace(/