import { ARTICLES, PAGES, RELEASES, TAGS } from '../constants/collections' import { createDiagnostics } from '../diagnostics' import type { Diagnostics } from '../diagnostics/types' import { createContentReader } from './reader' import type { ArticleEntry, Content, PageEntry, ReleaseEntry, TagEntry } from './types' interface CollectionReader { list(): Promise read(id: string): Promise } function reason(error: unknown): string { const [first, ...rest] = (error instanceof Error ? error.message : String(error)).split('\n') return first.endsWith(':') && rest.length ? rest.join('; ') : first } async function readAll( reader: CollectionReader, collection: string, problems: Diagnostics, ): Promise> { const entries = new Map() await Promise.all( (await reader.list()).map(async (id) => { try { const entry = await reader.read(id) if (entry) entries.set(id, entry) } catch (error) { problems.error(collection, id, reason(error)) } }), ) return entries } export async function loadContent(): Promise { const { collections } = createContentReader() const problems = createDiagnostics() const [articles, pages, tags, releases] = await Promise.all([ readAll(collections.articles, ARTICLES, problems), readAll(collections.pages, PAGES, problems), readAll(collections.tags, TAGS, problems), readAll(collections.releases, RELEASES, problems), ]) return { articles, pages, tags, releases, diagnostics: problems.list } }