import { getCollection, type CollectionEntry } from 'astro:content'; import MarkdownIt from 'markdown-it'; import type { Artwork, CountedLink, LinkGraphData, PageLink } from './layouts'; import { backgroundImage, featureImage, type BackgroundImage, type FeatureImage } from './images'; import { absoluteUrl, site } from './site'; import { isResource } from './resources'; import { siteNavigation } from './site-navigation'; import { defaultBackground, genericBackgrounds } from './default-background.mjs'; import { authorImage } from './author-image.mjs'; import { categoryHref, categoryId, categorySlug } from './categories.mjs'; export type Author = CollectionEntry<'authors'>; export type Category = CountedLink & { id: string; content?: CollectionEntry<'categories'>; entries: Document[]; }; type DocumentEntry = CollectionEntry<'posts' | 'placeholder'>; export type Document = Omit & { authors: { author: Author; count: number }[]; categories: CountedLink[]; data: Omit & { featureImage?: FeatureImage }; }; export type Post = Document & { data: Document['data'] & { date: Date } }; export type Connections = { outgoing: PageLink[]; incoming: PageLink[] }; export type Page = PageLink & { type: 'website' | 'article' | 'profile'; art: Artwork }; export const documentHref = (entry: Document) => `/${entry.id}/`; export const authorId = (author: Author) => `authors/${author.id}`; export const authorHref = (author: Author) => `/${authorId(author)}/`; export const documentMetadata = (entry: Document) => ({ authors: entry.authors.map(({ author, count }) => ({ name: author.data.name, href: authorHref(author), count, })), date: entry.data.date?.toISOString(), categories: entry.categories, }); const documentTime = (entry: Document) => entry.data.date?.getTime() ?? 0; const isPost = (entry: Document): entry is Post => entry.data.date !== undefined; const byCountAndName = (a: CountedLink, b: CountedLink) => b.count - a.count || a.name.localeCompare(b.name); const markdown = new MarkdownIt({ html: true }); function internalLinks(body: string, source: Page, pages: Map): PageLink[] { const links = new Map(); const tokens = markdown.parse(body, {}).flatMap((token) => token.children || []); for (const token of tokens.filter((token) => token.type === 'link_open')) { const href = String(token.attrGet('href') ?? ''); if (!href || href.startsWith('#')) continue; const url = new URL(href, absoluteUrl(source.href)); if (url.origin !== site.origin) continue; const path = decodeURI(url.pathname).replace(/\/?$/, '/'); const page = pages.get(path); if (!page) { // Files and feeds are resources, not vertices. Unknown page paths are authoring errors. if (!isResource(url.pathname)) throw new Error(`${source.id}: unknown linked page ${url.pathname}`); continue; } if (page.id !== source.id) links.set(page.id, page); } return [...links.values()]; } export async function catalog() { const [authored, placeholders, authors, standalone, categoryFiles] = await Promise.all([ getCollection('posts'), getCollection('placeholder'), getCollection('authors'), getCollection('pages'), getCollection('categories'), ]); const entries = [...authored, ...placeholders].sort((a, b) => a.id.localeCompare(b.id)); const categoriesById = new Map(); for (const entry of entries) { const seen = new Set(); for (const name of entry.data.categories) { const id = categorySlug(name); if (seen.has(id)) throw new Error(`${entry.id}: duplicate category ${name}`); seen.add(id); const category = categoriesById.get(id); if (category) category.count++; else categoriesById.set(id, { id, name, href: categoryHref(id), count: 1, entries: [] }); } } for (const content of categoryFiles) { const id = categorySlug(content.id); const category = categoriesById.get(id); if (category?.content) throw new Error(`Two category files share the slug ${id}`); if (category) { category.content = content; category.name = content.data.title ?? category.name; } else categoriesById.set(id, { id, name: content.data.title ?? content.id.replace(/-/g, ' '), href: categoryHref(id), count: 0, content, entries: [], }); } const categories = [...categoriesById.values()].sort(byCountAndName); const generic = entries.some(({ data }) => !data.backgroundImage) || authors.some(({ data }) => !data.backgroundImage) || standalone.some(({ data }) => !data.backgroundImage) || categories.some(({ content }) => !content?.data.backgroundImage) ? await genericBackgrounds() : []; const artwork = (id: string, image?: string | BackgroundImage) => backgroundImage(image ?? defaultBackground(id, generic)); authors.sort((a, b) => a.data.name.localeCompare(b.data.name)); const authorsById = new Map(authors.map((author) => [author.id, author])); const authorCounts = new Map(); for (const entry of entries.filter(({ data }) => data.date)) for (const { id } of entry.data.authors) authorCounts.set(id, (authorCounts.get(id) ?? 0) + 1); const documents: Document[] = ( await Promise.all( entries.map(async (entry) => { const creditedAuthors = entry.data.authors.map(({ id }) => { const author = authorsById.get(id); if (!author) throw new Error(`${entry.id}: unknown author ${id}`); return { author, count: authorCounts.get(id) ?? 0 }; }); if (new Set(creditedAuthors.map(({ author }) => author.id)).size !== creditedAuthors.length) throw new Error(`${entry.id}: duplicate author`); return { ...entry, authors: creditedAuthors, categories: entry.data.categories .map((name) => categoriesById.get(categorySlug(name))!) .sort(byCountAndName) .map(({ name, href, count }) => ({ name, href, count })), data: { ...entry.data, featureImage: await featureImage(entry.data.featureImage) }, }; }), ) ).sort((a, b) => documentTime(b) - documentTime(a) || a.id.localeCompare(b.id)); const authorEntries = new Map(authors.map(({ id }): [string, Document[]] => [id, []])); for (const entry of documents) { for (const { author } of entry.authors) authorEntries.get(author.id)!.push(entry); for (const name of entry.data.categories) categoriesById.get(categorySlug(name))!.entries.push(entry); } const posts = documents.filter(isPost); const configuredPage = async (entry: CollectionEntry<'pages'>): Promise => { const { backgroundImage: background, order: _order, ...metadata } = entry.data; return { id: entry.id, ...metadata, type: 'website', kind: 'page', art: await artwork(entry.id, background), }; }; const notFoundEntry = standalone.find(({ id }) => id === 'not-found'); if (!notFoundEntry) throw new Error('Missing src/content/pages/not-found.md'); const pages: Page[] = await Promise.all([ ...documents.map(async (entry): Promise => ({ id: entry.id, href: documentHref(entry), title: entry.data.title, excerpt: entry.data.excerpt, art: await artwork(entry.id, entry.data.backgroundImage), featureImage: entry.data.featureImage, type: 'article', kind: entry.data.date ? 'post' : 'page', ...documentMetadata(entry), })), ...standalone .filter(({ id }) => id !== 'not-found') .sort((a, b) => a.data.order - b.data.order) .map(configuredPage), ...authors.map(async (author): Promise => ({ id: authorId(author), href: authorHref(author), title: author.data.name, excerpt: author.data.excerpt, type: 'profile', kind: 'author', art: await artwork(authorId(author), author.data.backgroundImage), featureImage: await featureImage(authorImage(author.id, author.data).image), })), ...categories.map(async (category): Promise => ({ id: categoryId(category.id), href: category.href, title: category.name, excerpt: category.content?.data.excerpt ?? `Writing filed under ${category.name}.`, type: 'website', kind: 'category', art: await artwork(categoryId(category.id), category.content?.data.backgroundImage), featureImage: await featureImage(category.content?.data.featureImage), })), ]); const byHref = new Map(pages.map((page) => [page.href, page])); const byId = new Map(pages.map((page) => [page.id, page])); if (byHref.size !== pages.length || byId.size !== pages.length) throw new Error('Two pages share a URL or page ID.'); const page = (id: string) => { const value = byId.get(id); if (!value) throw new Error(`Unknown page: ${id}`); return value; }; const connections: Record = Object.fromEntries( pages.map((page) => [page.id, { outgoing: [], incoming: [] }]), ); const connect = (id: string, related: PageLink[], body = '') => { const source = page(id); const targets = [...internalLinks(body, source, byHref), ...related]; connections[source.id].outgoing = [ ...new Map(targets.map((target) => [target.id, target])).values(), ]; for (const target of connections[source.id].outgoing) connections[target.id].incoming.push(source); }; for (const entry of documents) connect( entry.id, entry.data.categories.map((name) => page(categoryId(categorySlug(name)))), entry.body, ); connect( 'home', [...siteNavigation.header, ...siteNavigation.footer] .filter(({ id }) => id !== 'home') .map(({ id }) => page(id)), ); connect( 'latest', posts.map((entry) => page(entry.id)), ); connect( 'authors', authors.map((author) => page(authorId(author))), ); for (const author of authors) connect( authorId(author), authorEntries.get(author.id)!.map((entry) => page(entry.id)), author.body, ); for (const category of categories) connect( categoryId(category.id), category.entries.map((entry) => page(entry.id)), category.content?.body, ); const graph: LinkGraphData = { nodes: pages.map(({ art, type, ...preview }) => preview), edges: pages.flatMap(({ id }) => connections[id].outgoing.map((target): [string, string] => [id, target.id]), ), }; return { context: (id: string) => ({ page: page(id), graph, connections: connections[id] }), documents, posts, authors, authorCounts, authorEntries, categories, pages, graph, notFound: await configuredPage(notFoundEntry), }; }