Files
ipal-kit/src/modules/seo/buildLlmsTxt.ts
T
Radosław SmolińskiandClaude Opus 5.5 94e563055f SEO/GEO/GSC: sitemap index + caching, Search & AI settings, getRobots
- Sitemap: batched reads (500), published-only where, field select; sitemap
  index over maxUrls (default 10k) with ?part=N; Cache-Control; in-process
  memo; runtime errors → 503 Retry-After (empty urlset only during next build)
- Site Settings → Search & AI tab (seo.searchSettings: false removes it):
  Google/Bing/Yandex verification (paste code or whole meta tag) added to
  page metadata; AI crawler policy + per-bot exceptions; llms.txt note
- buildRobots aiBotRules; getRobots helper reads the panel; more AI agents
- Under construction: sitemap and llms.txt list only open pages
- collectSiteIndex: no silent 1000 cap; llms routes send Cache-Control
- IndexNow: nothing sent with IPAL_NOINDEX
- Unknown route metadata is noindex
- Tests (unit + SQLite integration) and docs/seo.md

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:09:01 +02:00

160 lines
5.8 KiB
TypeScript

import type { BasePayload } from 'payload'
import type { ContentOption } from '../content/index.js'
import type { I18nConfig } from '../i18n/index.js'
import type { SiteIndexEntry } from './siteIndex.js'
import { blocksToMarkdown } from '../content/blocksToMarkdown.js'
import { getLocaleDefinition, isValidLocale } from '../i18n/index.js'
import { llmsIntroFrom } from './searchSettings.js'
import { collectSiteIndex } from './siteIndex.js'
type BuildLlmsTxtArgs = {
/** Absolute site URL (https://…). */
baseUrl: string
config: I18nConfig
/**
* Archive-backed collections (same value as the plugin option). Their entries
* — blog posts, case studies, products — are listed too, grouped under the
* collection's own plural label. Usually the most quotable content on a site.
*/
content?: ContentOption
/**
* Full-content mode (llms-full.txt). When true, each page's full body is
* inlined as Markdown (via blocksToMarkdown) under its heading, so an agent
* gets the whole site in one request — the llmstxt.org "llms-full.txt"
* convention. Default false = the compact index (links + descriptions).
*/
full?: boolean
/** Only pages whose path passes — e.g. those open while the site is under construction. */
include?: (path: string) => boolean
/** Field holding the block layout (full mode only). Default 'layout'. */
layoutField?: string
/**
* One locale only. Default: every configured locale, each in its own
* section — an agent learns all language versions exist.
*/
locale?: string
/** Pages collection slug. Defaults to 'pages'. */
pagesSlug?: string
payload: BasePayload
/** Site settings global slug. Defaults to 'site-settings'. */
settingsSlug?: string
/**
* Field holding a richer AI summary (buildSummaryField). When set and present,
* it's used as the page description instead of meta.description.
*/
summaryField?: string
}
type SettingsShape = {
[key: string]: unknown
siteDescription?: null | string
siteName?: null | string
}
const day = (iso?: string) => (iso ? iso.slice(0, 10) : undefined)
/**
* Builds the body of /llms.txt — a Markdown file describing the site for AI
* agents / LLM crawlers, per the llmstxt.org convention. Mirrors buildRobots /
* buildSitemapEntries: the plugin already knows the site's name, description,
* and pages, so it can generate this automatically.
*
* Structure (llmstxt.org): H1 site name, a blockquote summary, the editor's
* note from Site Settings → Search & AI (when set), then — per
* language when the site has several — one list per collection (pages first,
* then archive collections such as a blog) of Markdown links with descriptions.
* Section names are the project's own locale and collection labels; the plugin
* adds no text of its own.
*
* // app/llms.txt/route.ts — use createLlmsTxtRoute (routeHandlers.ts)
*
* Data comes from the panel (siteName, siteDescription, documents) — nothing
* hardcoded. Same rules as the sitemap (collectSiteIndex): drafts, noindex and
* error pages are skipped, the homepage collapses to the language root.
*/
export async function buildLlmsTxt({
baseUrl,
config,
content,
full = false,
include,
layoutField = 'layout',
locale,
pagesSlug = 'pages',
payload,
settingsSlug = 'site-settings',
summaryField,
}: BuildLlmsTxtArgs): Promise<string> {
const origin = baseUrl.replace(/\/$/, '')
const locales = locale && isValidLocale(locale, config) ? [locale] : config.locales.map((l) => l.code)
const headerLocale = locales.includes(config.defaultLocale) ? config.defaultLocale : locales[0]
let settings: SettingsShape = {}
try {
settings = (await payload.findGlobal({ slug: settingsSlug as never, depth: 0, locale: headerLocale as never })) as SettingsShape
} catch {
// fresh DB — header falls back to the host name
}
const name = settings.siteName?.trim() || new URL(origin || 'http://localhost').host
const description = settings.siteDescription?.trim()
const index = await collectSiteIndex({
baseUrl: origin,
config,
content,
depth: full ? 1 : 0,
include,
locales,
pagesSlug,
payload,
settingsSlug,
summaryField,
})
const lines: string[] = [`# ${name}`, '']
if (description) {lines.push(`> ${description}`, '')}
// Site Settings → Search & AI: facts the editor wants assistants to know and quote.
const intro = llmsIntroFrom(settings)
if (intro) {lines.push(intro, '')}
const multi = locales.length > 1
for (const loc of locales) {
const forLocale = index.filter((e) => e.locale === loc)
if (!forLocale.length) {continue}
if (multi) {
const def = getLocaleDefinition(loc, config)
lines.push(`## ${def?.label ?? loc} (${loc})`, '')
}
const level = multi ? '###' : '##'
// Group by collection, pages first (collectSiteIndex already orders them so).
const groups = new Map<string, SiteIndexEntry[]>()
for (const e of forLocale) {groups.set(e.collection, [...(groups.get(e.collection) ?? []), e])}
for (const entries of groups.values()) {
lines.push(`${level} ${entries[0].collectionLabel}`, '')
if (full) {
const sections = entries.map((e) => {
const parts = [`${level}# ${e.title}`, e.url]
const updated = day(e.updatedAt)
if (updated) {parts.push(`Updated: ${updated}`)}
if (e.description) {parts.push(`_${e.description}_`)}
const body = blocksToMarkdown(e.doc[layoutField])
if (body) {parts.push(body)}
return parts.join('\n\n')
})
lines.push(sections.join('\n\n---\n\n'), '')
} else {
for (const e of entries) {
lines.push(`- [${e.title}](${e.url})${e.description ? `: ${e.description}` : ''}`)
}
lines.push('')
}
}
}
return lines.join('\n')
}