Files
ipal-kit/src/modules/content/createMarkdownRenderer.ts
T
radoslaw.smolinskiandClaude Opus 5.5 924b5cf8be
CI / check (push) Canceled after 0s
Markdown route: type-safe locale code read
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 13:42:17 +02:00

207 lines
8.1 KiB
TypeScript

import type { BasePayload } from 'payload'
import type { ContentOption } from './types.js'
import { blocksToMarkdown } from './blocksToMarkdown.js'
import { resolveRoute } from './resolveRoute.js'
type CreateMarkdownRendererArgs = {
/**
* Absolute origin. With it the frontmatter carries `url:` — the canonical page
* address an assistant should cite (instead of the /md/… mirror).
*/
baseUrl?: string
/** Pages collection. Default 'pages'. */
collection?: string
/**
* i18n config — only to know a single-locale site has no /{locale} prefix in
* its URLs (for `url:`). Omit on multilingual sites if you like.
*/
config?: { defaultLocale?: string; locales: readonly unknown[] }
/** Archive-backed collections, same value as the plugin option (optional). */
content?: ContentOption
/** Prepend a YAML frontmatter block (title, description, url, updated, locale). Default true. */
frontmatter?: boolean
/** Field holding the block layout. Default 'layout'. */
layoutField?: string
/** Per-blockType overrides passed to blocksToMarkdown. */
overrides?: Record<string, (block: Record<string, unknown>) => string>
/** SiteSettings global slug. Default 'site-settings'. */
settingsSlug?: string
}
type MarkdownContext = {
locale: string
payload: BasePayload
/** Route slug segments; empty/undefined = locale root (home). */
slug?: string[]
}
type DocShape = {
[key: string]: unknown
meta?: { description?: null | string } | null
title?: null | string
updatedAt?: string
}
function yamlEscape(v: string): string {
return `"${v.replace(/"/g, '\\"')}"`
}
/**
* Returns a function that renders a page (or archive/entry) to clean Markdown —
* title, meta description, then the block layout via blocksToMarkdown. The
* point is AI-readability: an agent (Claude's WebFetch, GPT, Perplexity) gets
* structured Markdown instead of parsing HTML, so it reads the page reliably.
*
* Mirrors createPageMetadata: the plugin can't call getPayload, so it returns a
* function the project invokes from its route handler.
*
* // app/md/[locale]/[[...slug]]/route.ts (serves /md/pl/o-nas as text/markdown)
* import { createMarkdownRenderer, markdownResponse } from '@intecion/ipal-kit'
* import { getPayload } from 'payload'
* import config from '@payload-config'
* const render = createMarkdownRenderer({ content })
* export const dynamic = 'force-dynamic'
* export async function GET(_req: Request, { params }: { params: Promise<{ locale: string; slug?: string[] }> }) {
* const { locale, slug } = await params
* const md = await render({ payload: await getPayload({ config }), locale, slug })
* return markdownResponse(md)
* }
*
* Returns null when the route doesn't resolve (so the handler can 404).
*/
export function createMarkdownRenderer(args: CreateMarkdownRendererArgs = {}) {
const {
baseUrl,
collection = 'pages',
config,
content,
frontmatter = true,
layoutField = 'layout',
overrides,
settingsSlug = 'site-settings',
} = args
return async function render({ slug, locale, payload }: MarkdownContext): Promise<null | string> {
const route = await resolveRoute({
content,
locale,
pagesSlug: collection,
payload,
segments: slug,
settingsSlug,
})
if (!route) {return null}
const doc = route.doc as DocShape
const title = typeof doc.title === 'string' ? doc.title : ''
const description = typeof doc.meta?.description === 'string' ? doc.meta.description : ''
const body = blocksToMarkdown(doc[layoutField], { overrides })
const parts: string[] = []
if (frontmatter) {
const fm = ['---', `locale: ${locale}`]
if (title) {fm.push(`title: ${yamlEscape(title)}`)}
if (description) {fm.push(`description: ${yamlEscape(description)}`)}
const url = canonicalOf(baseUrl, config, locale, slug)
if (url) {fm.push(`url: ${url}`)}
if (typeof doc.updatedAt === 'string') {fm.push(`updated: ${doc.updatedAt.slice(0, 10)}`)}
fm.push('---')
parts.push(fm.join('\n'))
}
if (title) {parts.push(`# ${title}`)}
if (description) {parts.push(`_${description}_`)}
if (body) {parts.push(body)}
const md = parts.join('\n\n').trim()
return md || null
}
}
/**
* Wraps a Markdown string in a `text/markdown` Response, or a 404 when null.
* Uses the global Response — no next/server import.
*/
export function markdownResponse(md: null | string, options: { canonical?: string } = {}): Response {
if (md == null) {
return new Response('Not found', { headers: { 'content-type': 'text/plain' }, status: 404 })
}
return new Response(md, {
headers: {
'cache-control': 'public, max-age=0, s-maxage=3600, stale-while-revalidate=86400',
'content-type': 'text/markdown; charset=utf-8',
// A mirror of an HTML page: AI agents read it, search engines must not
// index it as a duplicate — and should credit the HTML page instead.
'x-robots-tag': 'noindex',
...(options.canonical ? { link: `<${options.canonical}>; rel="canonical"` } : {}),
},
status: 200,
})
}
/** Canonical HTML URL of a Markdown page — same rule as the frontmatter `url:`. */
function canonicalOf(baseUrl: string | undefined, config: { locales: readonly unknown[] } | undefined, locale: string, slug?: string[]) {
if (!baseUrl) {return undefined}
const segments = config?.locales.length === 1 ? (slug ?? []) : [locale, ...(slug ?? [])]
return `${baseUrl.replace(/\/$/, '')}/${segments.join('/')}`.replace(/\/$/, '')
}
type MarkdownRouteContext = { params: Promise<{ locale?: string; slug?: string[] }> }
/**
* Locale + slug of a Markdown request. Multilingual: app/md/[locale]/[[...slug]].
* Single language (no /pl in URLs): app/md/[[...slug]] — no locale param, the
* only locale is used; the [locale] route also works there for subpages
* ("/md/kontakt" arrives as locale "kontakt" and is read as the slug).
*/
function routeOf(
params: { locale?: string; slug?: string[] },
config: CreateMarkdownRendererArgs['config'],
): { locale: string; slug?: string[] } {
const codes = (config?.locales ?? []).map((l) => (l && typeof l === 'object' ? (l as { code?: string }).code ?? '' : typeof l === 'string' ? l : ''))
const fallback = config?.defaultLocale ?? codes[0] ?? ''
if (!params.locale) {return { slug: params.slug, locale: fallback }}
if (codes.length === 1 && !codes.includes(params.locale)) {
return { slug: [params.locale, ...(params.slug ?? [])], locale: codes[0] }
}
return { slug: params.slug, locale: params.locale }
}
/**
* The whole Markdown route in one call — same options as createMarkdownRenderer
* plus `getCachedPayload`:
*
* // src/app/md/[locale]/[[...slug]]/route.ts
* import { createMarkdownRoute } from '@intecion/ipal-kit'
* import { getCachedPayload } from '@/lib/content'
* import { contentConfig } from '@/content.config'
* import { i18nConfig } from '@/i18n.config'
* export const dynamic = 'force-dynamic'
* export const { GET } = createMarkdownRoute({ getCachedPayload, content: contentConfig,
* config: i18nConfig, baseUrl: process.env.NEXT_PUBLIC_SERVER_URL })
*
* 404 for unknown/unpublished pages; a database error returns a generic 503
* (details only in the server log).
*/
export function createMarkdownRoute(
args: { getCachedPayload: () => Promise<BasePayload> } & CreateMarkdownRendererArgs,
): { GET: (req: Request, ctx: MarkdownRouteContext) => Promise<Response> } {
const { getCachedPayload, ...rendererArgs } = args
const render = createMarkdownRenderer(rendererArgs)
return {
GET: async (_req, { params }) => {
try {
const { slug, locale } = routeOf(await params, rendererArgs.config)
const md = await render({ slug, locale, payload: await getCachedPayload() })
return markdownResponse(md, { canonical: canonicalOf(rendererArgs.baseUrl, rendererArgs.config, locale, slug) })
} catch (err) {
console.warn('[ipal] createMarkdownRoute: render failed:', err)
return new Response('Service unavailable', { headers: { 'content-type': 'text/plain' }, status: 503 })
}
},
}
}