177 lines
6.0 KiB
TypeScript
177 lines
6.0 KiB
TypeScript
import type { BasePayload } from 'payload'
|
|
|
|
import type { I18nConfig } from '../i18n/index.js'
|
|
|
|
import { blocksToMarkdown } from '../content/blocksToMarkdown.js'
|
|
import { buildLocalizedPath } from '../i18n/index.js'
|
|
|
|
type BuildLlmsTxtArgs = {
|
|
/** Absolute site URL (https://…). */
|
|
baseUrl: string
|
|
config: I18nConfig
|
|
/**
|
|
* 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
|
|
/** Field holding the block layout (full mode only). Default 'layout'. */
|
|
layoutField?: string
|
|
/** Locale for names/descriptions. Defaults to config.defaultLocale. */
|
|
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 = {
|
|
siteDescription?: null | string
|
|
siteName?: null | string
|
|
}
|
|
|
|
type PageRow = {
|
|
[key: string]: unknown
|
|
_status?: string
|
|
id: number | string
|
|
meta?: { description?: unknown; noindex?: boolean } | null
|
|
noindex?: boolean | null
|
|
slug?: unknown
|
|
title?: unknown
|
|
}
|
|
|
|
/**
|
|
* 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, then a list of
|
|
* key pages as Markdown links with short descriptions. Agents read this to
|
|
* understand the site quickly without crawling everything.
|
|
*
|
|
* Wire it as a route that returns text/plain:
|
|
*
|
|
* // app/llms.txt/route.ts
|
|
* import { buildLlmsTxt } from '@intecion/ipal-kit'
|
|
* import { getCachedPayload } from '@/lib/content'
|
|
* import { i18nConfig } from '@/i18n.config'
|
|
* export const dynamic = 'force-dynamic'
|
|
* export async function GET() {
|
|
* const body = await buildLlmsTxt({
|
|
* payload: await getCachedPayload(),
|
|
* config: i18nConfig,
|
|
* baseUrl: process.env.NEXT_PUBLIC_SERVER_URL!,
|
|
* })
|
|
* return new Response(body, { headers: { 'Content-Type': 'text/plain; charset=utf-8' } })
|
|
* }
|
|
*
|
|
* Data comes from the panel (siteName, siteDescription, pages) — nothing
|
|
* hardcoded. Skips drafts and noindex pages (same as the sitemap).
|
|
*/
|
|
export async function buildLlmsTxt({
|
|
baseUrl,
|
|
config,
|
|
full = false,
|
|
layoutField = 'layout',
|
|
locale,
|
|
pagesSlug = 'pages',
|
|
payload,
|
|
settingsSlug = 'site-settings',
|
|
summaryField,
|
|
}: BuildLlmsTxtArgs): Promise<string> {
|
|
const pickDescription = (raw: PageRow): string | undefined => {
|
|
if (
|
|
summaryField &&
|
|
typeof raw[summaryField] === 'string' &&
|
|
(raw[summaryField]).trim()
|
|
) {
|
|
return (raw[summaryField]).trim()
|
|
}
|
|
return typeof raw.meta?.description === 'string' ? raw.meta.description : undefined
|
|
}
|
|
const loc = locale ?? config.defaultLocale
|
|
const origin = baseUrl.replace(/\/$/, '')
|
|
|
|
const settings = (await payload.findGlobal({
|
|
slug: settingsSlug as never,
|
|
depth: 0,
|
|
locale: loc as never,
|
|
})) as SettingsShape
|
|
|
|
const name = settings.siteName?.trim() || 'Website'
|
|
const description = settings.siteDescription?.trim()
|
|
|
|
// NO where:{_status} filter — collections without drafts enabled don't
|
|
// register the _status field, and querying it throws
|
|
// "path cannot be queried: _status" (a real bug report). Draft filtering
|
|
// happens in memory below, which is safe for every collection. Same as
|
|
// buildSitemapEntries and generateStaticParams.
|
|
// Full mode needs depth:1 so block images/relations populate for the Markdown.
|
|
const result = await payload.find({
|
|
collection: pagesSlug as never,
|
|
depth: full ? 1 : 0,
|
|
limit: 1000,
|
|
locale: loc as never,
|
|
})
|
|
|
|
const lines: string[] = [`# ${name}`, '']
|
|
if (description) {
|
|
lines.push(`> ${description}`, '')
|
|
}
|
|
|
|
if (full) {
|
|
// Full-content: each published page inlined as Markdown under its heading.
|
|
const sections: string[] = []
|
|
for (const raw of result.docs as PageRow[]) {
|
|
if (raw._status && raw._status !== 'published') {continue}
|
|
if (raw.noindex || raw.meta?.noindex) {continue}
|
|
|
|
const title = typeof raw.title === 'string' ? raw.title : undefined
|
|
const slug = typeof raw.slug === 'string' ? raw.slug : undefined
|
|
if (!title || !slug) {continue}
|
|
|
|
const path = buildLocalizedPath({ config, locale: loc, slugs: { [loc]: slug } })
|
|
const body = blocksToMarkdown(raw[layoutField])
|
|
const desc = pickDescription(raw)
|
|
const parts = [`## ${title}`]
|
|
if (path) {parts.push(`${origin}${path}`)}
|
|
if (desc) {parts.push(`_${desc}_`)}
|
|
if (body) {parts.push(body)}
|
|
sections.push(parts.join('\n\n'))
|
|
}
|
|
if (sections.length > 0) {lines.push(sections.join('\n\n---\n\n'), '')}
|
|
return lines.join('\n')
|
|
}
|
|
|
|
const pageLinks: string[] = []
|
|
for (const raw of result.docs as PageRow[]) {
|
|
if (raw._status && raw._status !== 'published') {continue}
|
|
if (raw.noindex || raw.meta?.noindex) {continue}
|
|
|
|
const title = typeof raw.title === 'string' ? raw.title : undefined
|
|
const slug = typeof raw.slug === 'string' ? raw.slug : undefined
|
|
if (!title || !slug) {continue}
|
|
|
|
const path = buildLocalizedPath({ config, locale: loc, slugs: { [loc]: slug } })
|
|
if (!path) {continue}
|
|
|
|
const desc = pickDescription(raw)
|
|
const pageDesc = desc ? ` — ${desc}` : ''
|
|
pageLinks.push(`- [${title}](${origin}${path})${pageDesc}`)
|
|
}
|
|
|
|
if (pageLinks.length > 0) {
|
|
lines.push('## Strony', '', ...pageLinks, '')
|
|
}
|
|
|
|
return lines.join('\n')
|
|
}
|