import { createHash } from 'node:crypto'; import { lstat, readdir, readFile } from 'node:fs/promises'; import { join } from 'node:path'; export type Entry = { /** Path relative to the content root with forward slashes; the root itself is "". */ path: string; name: string; kind: 'file' | 'dir'; size: number; modified: Date; /** Missing for directories and for files above the size limit. */ content?: Buffer; children?: string[]; }; export type ContentIndex = { entries: Map; hash: string; warnings: string[]; }; export type WalkOptions = { maxFileBytes: number; maxTotalBytes: number; maxEntries: number; /** Top level names that would collide with the app's own routes. */ reserved: Set; signal?: AbortSignal; }; /** * Indexes the content directory. Symlinks are never followed, because the * walk runs on the host side and a link could point anywhere; dotfiles are * skipped so that things like .git or .env never become public. */ export async function buildIndex(root: string, options: WalkOptions): Promise { const entries = new Map(); const warnings: string[] = []; const hash = createHash('sha256'); let total = 0; async function visit(path: string, absolute: string): Promise { options.signal?.throwIfAborted(); const stats = await lstat(absolute); const name = path.split('/').at(-1) ?? ''; if (stats.isSymbolicLink()) return undefined; if (entries.size >= options.maxEntries) { warnings.push(`stopped at ${options.maxEntries} entries, ${path} and later ones are missing`); return undefined; } if (stats.isDirectory()) { const entry: Entry = { path, name, kind: 'dir', size: 0, modified: stats.mtime, children: [] }; entries.set(path, entry); hash.update(`d\0${path}\0`); const names = (await readdir(absolute)).filter((child) => !child.startsWith('.')).sort((a, b) => a.localeCompare(b, 'en')); for (const child of names) { if (path === '' && options.reserved.has(child)) { warnings.push(`"${child}" is skipped because the name is reserved for the site itself`); continue; } const visited = await visit(path ? `${path}/${child}` : child, join(absolute, child)); if (visited) entry.children!.push(visited.path); } return entry; } if (!stats.isFile()) return undefined; const entry: Entry = { path, name, kind: 'file', size: stats.size, modified: stats.mtime }; if (stats.size > options.maxFileBytes) { warnings.push(`${path} is listed but not served, it is larger than ${options.maxFileBytes} bytes`); } else if (total + stats.size > options.maxTotalBytes) { warnings.push(`${path} is listed but not served, the content exceeds ${options.maxTotalBytes} bytes in total`); } else { entry.content = await readFile(absolute); total += entry.content.length; } entries.set(path, entry); hash.update(`f\0${path}\0`); hash.update(entry.content ?? `${stats.size}:${stats.mtimeMs}`); return entry; } try { await visit('', root); } catch (error) { if (options.signal?.aborted) throw error; warnings.push(`the content directory cannot be read: ${(error as Error).message}`); } if (!entries.has('')) entries.set('', { path: '', name: '', kind: 'dir', size: 0, modified: new Date(0), children: [] }); return { entries, hash: hash.digest('hex').slice(0, 16), warnings }; }