import sharp from 'sharp'; import { parse } from 'yaml'; import { copyFile, readFile, writeFile, mkdir, readdir, access } from 'node:fs/promises'; import { resolve } from 'node:path'; import { pathToFileURL } from 'node:url'; import { artPalette, bayer8 } from './image-palette.mjs'; import { defaultBackground, genericBackgrounds } from '../src/lib/default-background.mjs'; import { authorImage } from '../src/lib/author-image.mjs'; import { categoryId, categorySlug } from '../src/lib/categories.mjs'; import { imageKey, fileExists, imageProfile, mediaDirectory, mediaFile, sourceFile, stillPath, variantPath, } from '../src/lib/image-files.mjs'; import { syncBlueskyAvatar } from './sync-bluesky-avatar.mjs'; import { serveAssets, watchAssets } from './asset-server.mjs'; async function records(directory) { const paths = (await readdir(directory, { recursive: true })).filter((path) => path.endsWith('.md'), ); return Promise.all( paths.sort().map(async (path) => { const text = await readFile(`${directory}/${path}`, 'utf8'); const frontmatter = text.match(/^---\r?\n([\s\S]*?)\r?\n---/); if (!frontmatter) throw new Error(`${directory}/${path}: missing frontmatter`); return { id: path.slice(0, -3), ...parse(frontmatter[1]) }; }), ); } export async function prepareAssets() { const [posts, placeholders, authors, standalone, categoryFiles, placeholderCategories] = await Promise.all([ records('src/content/posts'), records('src/content/placeholder/posts'), records('src/content/authors'), records('src/content/pages'), records('src/content/categories'), records('src/content/placeholder/categories'), ]); const documents = [...posts, ...placeholders]; const authorIds = new Set(authors.map(({ id }) => id)); const categories = new Map( documents.flatMap(({ categories = [] }) => categories.map((name) => { const id = categorySlug(name); return [id, { id }]; }), ), ); for (const category of [...categoryFiles, ...placeholderCategories]) { const id = categorySlug(category.id); if (categories.get(id)?.content) throw new Error(`Two category files share the slug ${id}`); categories.set(id, { ...category, id, content: true }); } const categoryPages = [...categories.values()]; const generic = [...documents, ...authors, ...categoryPages, ...standalone].some( ({ backgroundImage }) => backgroundImage == null, ) ? await genericBackgrounds() : []; for (const document of documents) for (const author of document.authors ?? []) if (!authorIds.has(author)) throw new Error(`${document.id}: missing author record ${author}`); const backgrounds = new Set(); const features = new Set(); const usedBackgrounds = new Map(); const withBackground = (record, id) => ({ ...record, id, fallback: record.backgroundImage == null, backgroundImage: record.backgroundImage ?? defaultBackground(id, generic), }); const authorPages = await Promise.all( authors.map(async (author) => { const { image, actor } = authorImage(author.id, author); if (actor) await syncBlueskyAvatar(actor, image.src); return withBackground({ ...author, featureImage: image }, `authors/${author.id}`); }), ); const pages = [ ...documents.map((document) => withBackground(document, document.id)), ...authorPages, ...categoryPages.map((category) => withBackground(category, categoryId(category.id))), ...standalone.map((page) => withBackground(page, page.id)), ]; for (const record of pages) { const background = typeof record.backgroundImage === 'string' ? record.backgroundImage : record.backgroundImage?.src; if (!background) throw new Error(`${record.id || record.title}: backgroundImage is required`); if (!record.fallback && usedBackgrounds.has(background)) throw new Error( `${record.id}: backgroundImage is also used by ${usedBackgrounds.get(background)}`, ); if (!record.fallback) usedBackgrounds.set(background, record.id); backgrounds.add(background); if (record.featureImage) features.add(record.featureImage.src); } await mkdir(mediaDirectory, { recursive: true }); const media = new Set(); for (const src of [...new Set([...backgrounds, ...features])].sort()) { const input = await readFile(await sourceFile(src)); const hash = imageKey(input); const original = await sharp(input).metadata(); const { width, height } = original.autoOrient; const limits = new Set([ ...(backgrounds.has(src) ? [imageProfile.backgroundWidth] : []), ...(features.has(src) ? [imageProfile.featureWidth, imageProfile.previewWidth] : []), ]); for (const limit of limits) { const targetWidth = Math.min(width, limit); const path = variantPath(hash, targetWidth); media.add(path); const file = mediaFile(path); if (await fileExists(file)) continue; // Already-sized AVIFs are preserved byte for byte; other inputs are oriented and resized once. if ( original.format === 'heif' && original.compression === 'av1' && targetWidth === width && !original.orientation ) await writeFile(file, input); else await sharp(input) .rotate() .resize({ width: targetWidth, withoutEnlargement: true }) .avif({ quality: imageProfile.quality, effort: 6 }) .toFile(file); } if (!backgrounds.has(src)) continue; const still = stillPath(hash); media.add(still); if (await fileExists(mediaFile(still))) continue; const background = variantPath(hash, width, imageProfile.backgroundWidth); const { data, info } = await sharp(mediaFile(background)) .resize({ width: Math.min( width, width >= height ? imageProfile.stillLandscape : imageProfile.stillPortrait, ), }) .greyscale() .raw() .toBuffer({ resolveWithObject: true }); for (let y = 0; y < info.height; y++) for (let x = 0; x < info.width; x++) { const index = y * info.width + x; const light = (data[index] / 255) ** 0.92 - 0.035; data[index] = light >= 0.045 + bayer8(x, info.height - 1 - y) * 0.94 ? artPalette.at(-1) : artPalette[0]; } await sharp(data, { raw: info }).png({ palette: true, colours: 2 }).toFile(mediaFile(still)); } return { authorIds: [...authorIds], categoryIds: [...categories.keys()], media }; } export function imageAssets() { let prepared; return { name: 'local-image-assets', hooks: { 'astro:config:setup': async () => { prepared = await prepareAssets(); }, 'astro:server:setup': ({ server }) => { serveAssets(server, (path) => (path.startsWith('/media/') ? mediaFile(path) : undefined)); watchAssets(server, ['src/content', 'src/assets/images'], prepareAssets); }, 'astro:build:done': async ({ dir }) => { for (const id of prepared.authorIds) await access(new URL(`authors/${id}/index.html`, dir)).catch(() => { throw new Error(`Author page was not emitted: ${id}`); }); for (const id of prepared.categoryIds) await access(new URL(`categories/${id}/index.html`, dir)).catch(() => { throw new Error(`Category page was not emitted: ${id}`); }); await mkdir(new URL('media/', dir), { recursive: true }); await Promise.all( [...prepared.media].map((src) => copyFile(mediaFile(src), new URL(src.slice(1), dir))), ); }, }, }; } if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) await prepareAssets();