feat(seo): sitemap, robots, canonical URLs, OG images and JSON-LD

- Add sitemap.ts and robots.ts
- pageMetadata() helper: consistent title, canonical URL, Open Graph,
  Twitter card and feed alternate on every page
- Generated OG images: a site card, and per post either the cover image
  or a branded title card (pre-rendered at build)
- BlogPosting JSON-LD on post pages
- Fail fast with a clear error when SITE_URL is missing

Content loading:
- Validate post frontmatter at build time and normalize dates to ISO
  (fixes invalid <time datetime> values)
- Add draft: true support (drafts only render in development)
- Cache markdown rendering so metadata and page share one render
- Replace the three copy-pasted about/projects/setup pages with a shared
  MarkdownPage component
This commit is contained in:
HangerThem 2026-10-19 14:22:40 +02:00
parent 88c8676d3f
commit 64ae30b545
20 changed files with 447 additions and 210 deletions

View file

@ -1,4 +1,4 @@
import { metadata } from '@/app/metadata'
import { pageMetadata } from '@/app/metadata'
import { getAllCategories, getCategoryBySlug, getPostsByCategory } from '@/lib/categories'
import { dateFormatter } from '@/utils/time'
import type { Metadata } from 'next'
@ -26,17 +26,11 @@ export async function generateMetadata({ params }: CategoryPageProps): Promise<M
const category = getCategoryBySlug(categorySlug)
if (!category) notFound()
return {
title: `${category} | ${metadata.title!.toString()}`,
description: 'List of posts in this category',
openGraph: {
type: 'website',
title: `${category} | ${metadata.title!.toString()}`,
description: 'List of posts in this category',
url: process.env.SITE_URL + `/categories/${categorySlug}`,
siteName: metadata.title!.toString(),
},
}
return pageMetadata({
title: category,
description: `Posts in the “${category}” category`,
path: `/categories/${categorySlug}`,
})
}
export default async function CategoryPage({ params }: CategoryPageProps) {

View file

@ -3,21 +3,15 @@ import { getAllPostsMeta } from '@/lib/posts'
import { slugify } from '@/utils/slug'
import type { Metadata } from 'next'
import Link from 'next/link'
import { metadata } from '@/app/metadata'
import { pageMetadata } from '@/app/metadata'
import { dateFormatter } from '@/utils/time'
export async function generateMetadata(): Promise<Metadata> {
return {
title: `Categories | ${metadata.title!.toString()}`,
description: 'List of categories',
openGraph: {
type: 'website',
title: `Categories | ${metadata.title!.toString()}`,
description: 'List of categories',
url: process.env.SITE_URL + '/categories',
siteName: metadata.title!.toString(),
},
}
return pageMetadata({
title: 'Categories',
description: 'All post categories on the blog',
path: '/categories',
})
}
export default function CategoriesPage() {

View file

@ -1,5 +1,8 @@
import { getAllPostsMeta } from '@/lib/posts'
import { Post } from '@/components/post/Post'
import type { Metadata } from 'next'
export const metadata: Metadata = { alternates: { canonical: '/' } }
export default function Homepage() {
const posts = getAllPostsMeta()

View file

@ -1,4 +1,4 @@
import { metadata } from '@/app/metadata'
import { pageMetadata } from '@/app/metadata'
import { getAllTags, getPostsByTag, getTagBySlug } from '@/lib/tags'
import { dateFormatter } from '@/utils/time'
import type { Metadata } from 'next'
@ -26,17 +26,11 @@ export async function generateMetadata({ params }: TagPageProps): Promise<Metada
const tag = getTagBySlug(tagSlug)
if (!tag) notFound()
return {
title: `${tag} | ${metadata.title!.toString()}`,
description: 'List of posts in this tag',
openGraph: {
type: 'website',
title: `${tag} | ${metadata.title!.toString()}`,
description: 'List of posts in this tag',
url: process.env.SITE_URL + `/tags/${tagSlug}`,
siteName: metadata.title!.toString(),
},
}
return pageMetadata({
title: tag,
description: `Posts tagged “${tag}”`,
path: `/tags/${tagSlug}`,
})
}
export default async function TagPage({ params }: TagPageProps) {

View file

@ -3,21 +3,11 @@ import { getAllPostsMeta } from '@/lib/posts'
import { slugify } from '@/utils/slug'
import type { Metadata } from 'next'
import Link from 'next/link'
import { metadata } from '@/app/metadata'
import { pageMetadata } from '@/app/metadata'
import { dateFormatter } from '@/utils/time'
export async function generateMetadata(): Promise<Metadata> {
return {
title: `Tags | ${metadata.title!.toString()}`,
description: 'List of tags',
openGraph: {
type: 'website',
title: `Tags | ${metadata.title!.toString()}`,
description: 'List of tags',
url: process.env.SITE_URL + '/tags',
siteName: metadata.title!.toString(),
},
}
return pageMetadata({ title: 'Tags', description: 'All tags used on the blog', path: '/tags' })
}
export default function TagsPage() {

View file

@ -1,35 +1,7 @@
import { metadata } from '@/app/metadata'
import { TableOfContents } from '@/components/post/TableOfContents'
import { getPostBySlug } from '@/lib/posts'
import type { Metadata } from 'next'
import { MarkdownPage, markdownPageMetadata } from '@/components/content/MarkdownPage'
export async function generateMetadata(): Promise<Metadata> {
const { meta } = await getPostBySlug('about', 'content/pages')
return {
title: `${meta.title} | ${metadata.title!.toString()}`,
description: meta.description,
openGraph: {
type: 'website',
title: `${meta.title} | ${metadata.title!.toString()}`,
description: meta.description,
url: process.env.SITE_URL + `/about`,
siteName: metadata.title!.toString(),
},
}
}
export default async function AboutPage() {
const { meta, content, tableOfContents } = await getPostBySlug('about', 'content/pages')
return (
<main className="flex w-full">
<article className="max-w-3xl 2xl:max-w-4xl mx-auto px-4 py-8 mb-8 lg:py-16 min-w-0">
<h1 className="text-4xl font-bold mb-4">{meta.title}</h1>
<p className="text-fg text-lg mb-4">{meta.description}</p>
<div className="prose">{content}</div>
</article>
<TableOfContents items={tableOfContents} />
</main>
)
export const generateMetadata = () => markdownPageMetadata('about')
export default function AboutPage() {
return <MarkdownPage slug="about" />
}

View file

@ -1,11 +1,9 @@
import { metadata } from '@/app/metadata'
import { AUTHOR, SITE_NAME, SITE_URL } from '@/app/metadata'
import { getAllPostsMeta } from '@/lib/posts'
import type { PostMeta } from '@/types/Post.type'
export const dynamic = 'force-static'
const SITE_URL = process.env.SITE_URL
const lastModified = (p: PostMeta) => new Date(p.updated ?? p.date)
function escapeXml(str: string) {
@ -46,14 +44,15 @@ export async function GET(req: Request) {
const feed = `<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<id>${SITE_URL}/</id>
<title>${escapeXml(metadata.title!.toString())}</title>
<title>${escapeXml(SITE_NAME)}</title>
<updated>${updated}</updated>
<author>
<name>${escapeXml(metadata.creator!.toString())}</name>
<name>${escapeXml(AUTHOR.name)}
<uri>${AUTHOR.url}</uri></name>
</author>
<link href="${SITE_URL}/feed.xml" rel="self" type="application/atom+xml" />
<link href="${SITE_URL}" rel="alternate" type="text/html" />
<rights> © ${new Date().getFullYear()} Frank Borisjuk </rights>
<rights>© ${new Date().getFullYear()} ${escapeXml(AUTHOR.name)}</rights>
${entries}
</feed>`

View file

@ -1,20 +1,84 @@
import { Metadata } from 'next'
if (!process.env.SITE_URL) {
throw new Error('SITE_URL environment variable is not set (e.g. SITE_URL=https://example.com)')
}
export const SITE_URL = process.env.SITE_URL.replace(/\/$/, '')
export const SITE_NAME = 'Ephemeris'
export const SITE_DESCRIPTION = 'A blog about me and my interests'
export const AUTHOR = { name: 'Frank Borisjuk', handle: 'hangerthem', url: SITE_URL + '/about' }
// Child segments replace `alternates` wholesale, so every page re-declares the feed link
const feedAlternate = { 'application/atom+xml': [{ url: '/feed.xml', title: SITE_NAME }] }
export const metadata: Metadata = {
metadataBase: new URL(process.env.SITE_URL!),
title: 'Ephemeris',
description: 'A blog about me and my interests',
creator: 'hangerthem',
metadataBase: new URL(SITE_URL),
title: SITE_NAME,
description: SITE_DESCRIPTION,
creator: AUTHOR.handle,
authors: [{ name: AUTHOR.name, url: AUTHOR.url }],
alternates: { types: feedAlternate },
openGraph: {
type: 'website',
title: 'Ephemeris',
description: 'A blog about me and my interests',
url: process.env.SITE_URL,
siteName: 'Ephemeris',
title: SITE_NAME,
description: SITE_DESCRIPTION,
url: SITE_URL,
siteName: SITE_NAME,
},
twitter: {
card: 'summary_large_image',
title: SITE_NAME,
description: SITE_DESCRIPTION,
},
appleWebApp: {
title: 'Ephemeris',
title: SITE_NAME,
statusBarStyle: 'default',
capable: true,
},
}
type PageMetadataOptions = {
title: string
description: string
/** Path relative to the site root, starting with a slash. */
path: string
/** Open Graph / Twitter image URL. Defaults to the generated site card. */
image?: string
openGraph?: Metadata['openGraph']
}
// Generated by app/opengraph-image.tsx. Child segments that set `openGraph` don't inherit
// file-based images, and explicit images win over them, so every page names its image here.
const defaultOgImage = '/opengraph-image'
/** Builds consistent page metadata (title, canonical URL, Open Graph and Twitter card). */
export function pageMetadata({
title,
description,
path,
image = defaultOgImage,
openGraph,
}: PageMetadataOptions): Metadata {
const fullTitle = `${title} | ${SITE_NAME}`
return {
title: fullTitle,
description,
alternates: { canonical: path, types: feedAlternate },
openGraph: {
type: 'website',
title: fullTitle,
description,
url: SITE_URL + path,
siteName: SITE_NAME,
images: image,
...openGraph,
},
twitter: {
card: 'summary_large_image',
title: fullTitle,
description,
images: image,
},
}
}

10
app/opengraph-image.tsx Normal file
View file

@ -0,0 +1,10 @@
import { SITE_DESCRIPTION, SITE_NAME } from '@/app/metadata'
import { ogImageSize, renderOgCard } from '@/lib/og-image'
export const alt = SITE_NAME
export const size = ogImageSize
export const contentType = 'image/png'
export default function OpengraphImage() {
return renderOgCard({ title: SITE_NAME, description: SITE_DESCRIPTION })
}

View file

@ -0,0 +1,19 @@
import { getAllPostSlugs, getPostMeta } from '@/lib/posts'
import { ogImageSize, renderOgCard, renderOgCover } from '@/lib/og-image'
export const size = ogImageSize
export const contentType = 'image/png'
export function generateStaticParams() {
return getAllPostSlugs().map((slug) => ({ slug }))
}
/** Uses the post's cover image when it has one, otherwise a generated title card. */
export default async function OpengraphImage({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params
const meta = getPostMeta(slug)
return (
(meta.coverImage && renderOgCover(meta.coverImage)) ??
renderOgCard({ title: meta.title, description: meta.description, eyebrow: meta.category })
)
}

View file

@ -1,4 +1,4 @@
import { metadata } from '@/app/metadata'
import { AUTHOR, pageMetadata, SITE_NAME, SITE_URL } from '@/app/metadata'
import { ImageWrapper } from '@/components/content/ImageWrapper'
import { ShareLinks } from '@/components/post/ShareLinks'
import { TableOfContents } from '@/components/post/TableOfContents'
@ -21,29 +21,52 @@ export async function generateMetadata({
}): Promise<Metadata> {
const { slug } = await params
const { meta } = await getPostBySlug(slug)
return {
title: `${meta.title} | ${metadata.title!.toString()}`,
return pageMetadata({
title: meta.title,
description: meta.description,
path: `/posts/${slug}`,
image: `/posts/${slug}/opengraph-image`,
openGraph: {
type: 'article',
title: `${meta.title} | ${metadata.title!.toString()}`,
description: meta.description,
url: process.env.SITE_URL + `/posts/${slug}`,
images: meta.coverImage ? [`/posts/${meta.coverImage}`] : undefined,
publishedTime: meta.date,
modifiedTime: meta.updated,
authors: [AUTHOR.url],
section: meta.category,
tags: meta.tags,
...(meta.updated && { modifiedTime: new Date(meta.updated).toISOString() }),
siteName: metadata.title!.toString(),
},
}
})
}
export default async function Post({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params
const { meta, content, tableOfContents } = await getPostBySlug(slug)
const { next, previous } = getNextAndPreviousPosts(slug)
const url = `${SITE_URL}/posts/${slug}`
const jsonLd = {
'@context': 'https://schema.org',
'@type': 'BlogPosting',
headline: meta.title,
description: meta.description,
url,
mainEntityOfPage: url,
datePublished: meta.date,
dateModified: meta.updated ?? meta.date,
image: `${url}/opengraph-image`,
articleSection: meta.category,
keywords: meta.tags.join(', '),
author: { '@type': 'Person', name: AUTHOR.name, url: AUTHOR.url },
publisher: { '@type': 'Person', name: AUTHOR.name, url: AUTHOR.url },
isPartOf: { '@type': 'Blog', name: SITE_NAME, url: SITE_URL },
}
return (
<main className="flex w-full">
<script
type="application/ld+json"
// Escape "<" so post content can never close the script tag early
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd).replace(/</g, '\\u003c') }}
/>
<article className="max-w-3xl 2xl:max-w-4xl mx-auto px-4 py-8 mb-8 lg:py-16 min-w-0">
{meta.category && (
<Link
@ -114,7 +137,7 @@ export default async function Post({ params }: { params: Promise<{ slug: string
)}
<div className="prose">{content}</div>
{meta.tags && (
{meta.tags.length > 0 && (
<div className="mt-6 border-t border-border pt-4 flex gap-2 items-center flex-wrap">
<h2 className="text-lg font-bold">Tags</h2>
<div className="flex flex-wrap gap-1">
@ -132,11 +155,7 @@ export default async function Post({ params }: { params: Promise<{ slug: string
)}
<div className="mt-8 mx-auto flex">
<ShareLinks
url={process.env.SITE_URL + `/posts/${slug}`}
title={meta.title}
description={meta.description}
/>
<ShareLinks url={url} title={meta.title} description={meta.description} />
</div>
<div className="mt-12 grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4 border-t border-border pt-8">

View file

@ -1,35 +1,7 @@
import { metadata } from '@/app/metadata'
import { TableOfContents } from '@/components/post/TableOfContents'
import { getPostBySlug } from '@/lib/posts'
import type { Metadata } from 'next'
import { MarkdownPage, markdownPageMetadata } from '@/components/content/MarkdownPage'
export async function generateMetadata(): Promise<Metadata> {
const { meta } = await getPostBySlug('projects', 'content/pages')
return {
title: `${meta.title} | ${metadata.title!.toString()}`,
description: meta.description,
openGraph: {
type: 'website',
title: `${meta.title} | ${metadata.title!.toString()}`,
description: meta.description,
url: process.env.SITE_URL + `/projects`,
siteName: metadata.title!.toString(),
},
}
}
export default async function ProjectsPage() {
const { meta, content, tableOfContents } = await getPostBySlug('projects', 'content/pages')
return (
<main className="flex w-full">
<article className="max-w-3xl 2xl:max-w-4xl mx-auto px-4 py-8 mb-8 lg:py-16 min-w-0">
<h1 className="text-4xl font-bold mb-4">{meta.title}</h1>
<p className="text-fg text-lg mb-4">{meta.description}</p>
<div className="prose">{content}</div>
</article>
<TableOfContents items={tableOfContents} />
</main>
)
export const generateMetadata = () => markdownPageMetadata('projects')
export default function ProjectsPage() {
return <MarkdownPage slug="projects" />
}

9
app/robots.ts Normal file
View file

@ -0,0 +1,9 @@
import type { MetadataRoute } from 'next'
import { SITE_URL } from '@/app/metadata'
export default function robots(): MetadataRoute.Robots {
return {
rules: { userAgent: '*', allow: '/' },
sitemap: `${SITE_URL}/sitemap.xml`,
}
}

View file

@ -1,35 +1,7 @@
import { metadata } from '@/app/metadata'
import { TableOfContents } from '@/components/post/TableOfContents'
import { getPostBySlug } from '@/lib/posts'
import type { Metadata } from 'next'
import { MarkdownPage, markdownPageMetadata } from '@/components/content/MarkdownPage'
export async function generateMetadata(): Promise<Metadata> {
const { meta } = await getPostBySlug('setup', 'content/pages')
return {
title: `${meta.title} | ${metadata.title!.toString()}`,
description: meta.description,
openGraph: {
type: 'website',
title: `${meta.title} | ${metadata.title!.toString()}`,
description: meta.description,
url: process.env.SITE_URL + `/setup`,
siteName: metadata.title!.toString(),
},
}
}
export default async function SetupPage() {
const { meta, content, tableOfContents } = await getPostBySlug('setup', 'content/pages')
return (
<main className="flex w-full">
<article className="max-w-3xl 2xl:max-w-4xl mx-auto px-4 py-8 mb-8 lg:py-16 min-w-0">
<h1 className="text-4xl font-bold mb-4">{meta.title}</h1>
<p className="text-fg text-lg mb-4">{meta.description}</p>
<div className="prose">{content}</div>
</article>
<TableOfContents items={tableOfContents} />
</main>
)
export const generateMetadata = () => markdownPageMetadata('setup')
export default function SetupPage() {
return <MarkdownPage slug="setup" />
}

41
app/sitemap.ts Normal file
View file

@ -0,0 +1,41 @@
import type { MetadataRoute } from 'next'
import { SITE_URL } from '@/app/metadata'
import { getAllCategories } from '@/lib/categories'
import { getAllPostsMeta } from '@/lib/posts'
import { getAllTags } from '@/lib/tags'
import { slugify } from '@/utils/slug'
export default function sitemap(): MetadataRoute.Sitemap {
const posts = getAllPostsMeta()
const lastPostUpdate = posts
.map((post) => post.updated ?? post.date)
.toSorted()
.at(-1)
return [
{ url: SITE_URL, lastModified: lastPostUpdate, changeFrequency: 'weekly', priority: 1 },
...['about', 'projects', 'setup'].map((page) => ({
url: `${SITE_URL}/${page}`,
changeFrequency: 'monthly' as const,
priority: 0.8,
})),
...posts.map((post) => ({
url: `${SITE_URL}/posts/${post.slug}`,
lastModified: post.updated ?? post.date,
changeFrequency: 'monthly' as const,
priority: 0.9,
})),
{ url: `${SITE_URL}/categories`, changeFrequency: 'weekly', priority: 0.4 },
...Object.keys(getAllCategories()).map((category) => ({
url: `${SITE_URL}/categories/${slugify(category)}`,
changeFrequency: 'weekly' as const,
priority: 0.3,
})),
{ url: `${SITE_URL}/tags`, changeFrequency: 'weekly', priority: 0.4 },
...Object.keys(getAllTags()).map((tag) => ({
url: `${SITE_URL}/tags/${slugify(tag)}`,
changeFrequency: 'weekly' as const,
priority: 0.3,
})),
]
}

View file

@ -0,0 +1,27 @@
import { pageMetadata } from '@/app/metadata'
import { TableOfContents } from '@/components/post/TableOfContents'
import { getPageBySlug } from '@/lib/posts'
import type { Metadata } from 'next'
/** Metadata for a standalone page served at `/<slug>` from content/pages/<slug>.md. */
export async function markdownPageMetadata(slug: string): Promise<Metadata> {
const { meta } = await getPageBySlug(slug)
return pageMetadata({ title: meta.title, description: meta.description, path: `/${slug}` })
}
/** Renders a standalone page from content/pages/<slug>.md. */
export async function MarkdownPage({ slug }: { slug: string }) {
const { meta, content, tableOfContents } = await getPageBySlug(slug)
return (
<main className="flex w-full">
<article className="max-w-3xl 2xl:max-w-4xl mx-auto px-4 py-8 mb-8 lg:py-16 min-w-0">
<h1 className="text-4xl font-bold mb-4">{meta.title}</h1>
<p className="text-fg text-lg mb-4">{meta.description}</p>
<div className="prose">{content}</div>
</article>
<TableOfContents items={tableOfContents} />
</main>
)
}

View file

@ -1,4 +1,4 @@
import { metadata } from '@/app/metadata'
import { SITE_NAME } from '@/app/metadata'
import { NavLinks } from '@/components/layout/NavLinks'
import { siBluesky, siGithub, siMatrix, siTelegram, type SimpleIcon } from 'simple-icons'
import { ExternalLink } from '@/components/ui/ExternalLink'
@ -39,7 +39,7 @@ export async function Sidebar() {
<div>
<h2 className="text-2xl font-bold mb-4 flex items-center gap-2">
<Image src="/logo.png" alt="Ephemeris Logo" width={32} height={32} />
<span>{metadata.title!.toString()}</span>
<span>{SITE_NAME}</span>
</h2>
<ul className="space-y-2">
<NavLinks />

81
lib/og-image.tsx Normal file
View file

@ -0,0 +1,81 @@
import fs from 'fs'
import path from 'path'
import { ImageResponse } from 'next/og'
import { SITE_NAME, SITE_URL } from '@/app/metadata'
export const ogImageSize = { width: 1200, height: 630 }
const colors = { bg: '#040404', fg: '#e0e0e0', fgDim: '#b0b0b0', accent: '#ef1f1f' }
function toDataUri(filePath: string, mime: string) {
return `data:${mime};base64,${fs.readFileSync(filePath).toString('base64')}`
}
const logo = toDataUri(path.join(process.cwd(), 'public/logo.png'), 'image/png')
type OgCardProps = {
title: string
description?: string
eyebrow?: string
}
/** Renders the branded title card used for pages and posts without a cover image. */
export function renderOgCard({ title, description, eyebrow }: OgCardProps) {
return new ImageResponse(
<div
style={{
width: '100%',
height: '100%',
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-between',
padding: '64px 72px',
background: colors.bg,
color: colors.fg,
borderLeft: `16px solid ${colors.accent}`,
}}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
{eyebrow && (
<div style={{ fontSize: 28, color: colors.accent, textTransform: 'uppercase' }}>
{eyebrow}
</div>
)}
<div style={{ fontSize: title.length > 50 ? 60 : 76, fontWeight: 700, lineHeight: 1.1 }}>
{title}
</div>
{description && (
<div style={{ fontSize: 30, color: colors.fgDim, lineHeight: 1.4, maxHeight: 130 }}>
{description.length > 140 ? description.slice(0, 137).trimEnd() + '…' : description}
</div>
)}
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 16, fontSize: 30 }}>
{/* oxlint-disable-next-line nextjs/no-img-element -- Satori renders plain <img> only */}
<img src={logo} width={48} height={48} alt="" />
<span style={{ fontWeight: 700 }}>{SITE_NAME}</span>
<span style={{ color: colors.fgDim }}>{SITE_URL.replace(/^https?:\/\//, '')}</span>
</div>
</div>,
ogImageSize,
)
}
const coverMimeTypes: Record<string, string> = {
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
}
/** Renders a post's cover image at OG size, or null if the format isn't supported by Satori. */
export function renderOgCover(coverImage: string) {
const mime = coverMimeTypes[path.extname(coverImage).toLowerCase()]
if (!mime) return null
const src = toDataUri(path.join(process.cwd(), 'public/posts', coverImage), mime)
return new ImageResponse(
// oxlint-disable-next-line nextjs/no-img-element -- Satori renders plain <img> only
<img src={src} width={ogImageSize.width} height={ogImageSize.height} alt="" />,
ogImageSize,
)
}

View file

@ -9,7 +9,14 @@ import remarkRehype from 'remark-rehype'
import rehypeHighlight from 'rehype-highlight'
import rehypeKatex from 'rehype-katex'
import rehypeReact from 'rehype-react'
import { cloneElement, isValidElement, type ReactElement, Fragment, type ReactNode } from 'react'
import {
cache,
cloneElement,
isValidElement,
type ReactElement,
Fragment,
type ReactNode,
} from 'react'
import { jsx, jsxs } from 'react/jsx-runtime'
import { rehypeCodeMeta } from '@/lib/rehype-code-meta'
import { CodeWrapper } from '@/components/content/CodeWrapper'
@ -28,28 +35,86 @@ import { PostMeta } from '@/types/Post.type'
import Link from 'next/link'
const postsDirectory = path.join(process.cwd(), 'content/posts')
const pagesDirectory = path.join(process.cwd(), 'content/pages')
export function getAllPostSlugs(): string[] {
return fs
.readdirSync(postsDirectory)
.filter((f) => f.endsWith('.md'))
.map((f) => f.replace(/\.md$/, ''))
const includeDrafts = process.env.NODE_ENV !== 'production'
type TocItem = { text: string; id: string; level: number }
function readMarkdownFile(directory: string, slug: string) {
return matter(fs.readFileSync(path.join(directory, `${slug}.md`), 'utf8'))
}
/**
* Validates post frontmatter and normalizes dates to ISO strings.
* Throws at build time with the offending file and field instead of rendering a broken post.
*/
function parsePostFrontmatter(slug: string, data: Record<string, unknown>) {
const fail = (message: string): never => {
throw new Error(`Invalid frontmatter in content/posts/${slug}.md: ${message}`)
}
const requireString = (key: string) => {
const value = data[key]
return typeof value === 'string' && value.trim() !== ''
? value
: fail(`"${key}" is required and must be a non-empty string`)
}
const optionalString = (key: string) => {
const value = data[key]
return value === undefined || typeof value === 'string'
? value
: fail(`"${key}" must be a string`)
}
// YAML parses bare dates (2024-08-04) into Date objects, anything with a time stays a string
const optionalDate = (key: string) => {
const value = data[key]
if (value === undefined) return undefined
const date = value instanceof Date ? value : new Date(String(value))
return Number.isNaN(date.getTime()) ? fail(`"${key}" is not a valid date`) : date.toISOString()
}
const tags = data.tags ?? []
if (!Array.isArray(tags) || tags.some((tag) => typeof tag !== 'string')) {
fail('"tags" must be a list of strings')
}
return {
title: requireString('title'),
description: requireString('description'),
date: optionalDate('date') ?? fail('"date" is required'),
updated: optionalDate('updated'),
category: requireString('category'),
tags: tags as string[],
math: data.math === true,
mermaid: data.mermaid === true,
draft: data.draft === true,
coverImage: optionalString('coverImage'),
coverImageAlt: optionalString('coverImageAlt'),
}
}
export function getPostMeta(slug: string): PostMeta {
const { data, content } = readMarkdownFile(postsDirectory, slug)
return {
slug,
...parsePostFrontmatter(slug, data),
readingTimeText: readingTime(content).text,
}
}
export function getAllPostsMeta(): PostMeta[] {
return getAllPostSlugs()
.map((slug) => {
const fullPath = path.join(postsDirectory, `${slug}.md`)
const { data, content } = matter(fs.readFileSync(fullPath, 'utf8'))
const readingTimeText = readingTime(content).text
return Object.assign({ slug }, {
...data,
readingTimeText,
} as Omit<PostMeta, 'slug'>)
})
return fs
.readdirSync(postsDirectory)
.filter((f) => f.endsWith('.md'))
.map((f) => getPostMeta(f.replace(/\.md$/, '')))
.filter((post) => includeDrafts || !post.draft)
.toSorted((a, b) => (a.date < b.date ? 1 : -1))
}
export function getAllPostSlugs(): string[] {
return getAllPostsMeta().map((post) => post.slug)
}
export function getNextAndPreviousPosts(slug: string): {
next: PostMeta | null
previous: PostMeta | null
@ -61,13 +126,27 @@ export function getNextAndPreviousPosts(slug: string): {
return { next, previous }
}
export async function getPostBySlug(slug: string, postDirectory: string = postsDirectory) {
const fullPath = path.join(postDirectory, `${slug}.md`)
const { data, content } = matter(fs.readFileSync(fullPath, 'utf8'))
// Cached so generateMetadata and the page share one render per request/build
export const getPostBySlug = cache(async (slug: string) => {
const meta = getPostMeta(slug)
const { content } = readMarkdownFile(postsDirectory, slug)
return { meta, ...(await renderMarkdown(content, meta)) }
})
/** Loads a standalone page (about, projects, ...) from content/pages. */
export const getPageBySlug = cache(async (slug: string) => {
const { data, content } = readMarkdownFile(pagesDirectory, slug)
const meta = { title: String(data.title), description: String(data.description) }
return { meta, ...(await renderMarkdown(content, data)) }
})
async function renderMarkdown(
content: string,
options: { math?: boolean; mermaid?: boolean },
): Promise<{ content: ReactNode; tableOfContents: TocItem[] }> {
let processor = remark().use(remarkParse).use(remarkGfm)
if (data.math) {
if (options.math) {
processor = processor.use(remarkMath)
}
@ -78,11 +157,11 @@ export async function getPostBySlug(slug: string, postDirectory: string = postsD
.use(rehypeMark)
.use(rehypeDefinition)
if (data.math) {
if (options.math) {
processor = processor.use(rehypeKatex)
}
if (data.mermaid) {
if (options.mermaid) {
processor = processor.use(rehypeMermaidSsg)
}
@ -124,9 +203,7 @@ export async function getPostBySlug(slug: string, postDirectory: string = postsD
const file = await processor.process(content)
const rawContentNode = file.result as ReactNode
const readingTimeText = readingTime(content).text
const tableOfContents: { text: string; id: string; level: number }[] = []
const tableOfContents: TocItem[] = []
const seenIds = new Map<string, number>()
function withHeadingIds(node: ReactNode): ReactNode {
@ -161,9 +238,5 @@ export async function getPostBySlug(slug: string, postDirectory: string = postsD
? cloneElement(rawContentNode, {}, processedChildren)
: rawContentNode
return {
meta: { ...(data as Omit<PostMeta, 'slug'>), readingTimeText },
content: processedContent,
tableOfContents,
}
return { content: processedContent, tableOfContents }
}

View file

@ -2,12 +2,16 @@ export interface PostMeta {
slug: string
title: string
description: string
/** ISO 8601 */
date: string
/** ISO 8601 */
updated?: string
category: string
tags: string[]
math: boolean
mermaid: boolean
/** Drafts are rendered in development only. */
draft: boolean
readingTimeText: string
coverImage?: string
coverImageAlt?: string