- sitemap, llms.txt and the site index leave out the page assigned as the 404 page (unlistedPageIds, exported); it stays when it is also the homepage - buildImagesConfig: in production with R2_PUBLIC_URL empty, allow the site's own /api/media/file/** so next/image no longer answers 400 - fillGlobal: a choice field (select, radio, checkbox, number, date) still at its defaultValue counts as empty; text is never overwritten - docs: LanguageSwitcher renderLabel needs a 'use client' wrapper (i18n.md, ipal-site, ipal-setup, api.md) Co-Authored-By: Claude Opus 5.5 <[email protected]>
203 lines
7.8 KiB
TypeScript
203 lines
7.8 KiB
TypeScript
import type { BasePayload } from 'payload'
|
|
|
|
import type { ContentOption } from '../content/index.js'
|
|
import type { I18nConfig } from '../i18n/index.js'
|
|
|
|
import { archiveFieldName } from '../content/index.js'
|
|
import { buildLocalizedPath, getLocaleCodes, isValidLocale } from '../i18n/index.js'
|
|
import { resolveLocalized } from '../i18n/resolveLocalized.js'
|
|
import { unlistedPageIds } from '../pages/unlistedPages.js'
|
|
|
|
/** One public, indexable document in one language. */
|
|
export type SiteIndexEntry = {
|
|
/** Collection slug, e.g. 'pages', 'posts'. */
|
|
collection: string
|
|
/** Plural label of the collection in this locale (from the project's config), e.g. 'Pages'. */
|
|
collectionLabel: string
|
|
createdAt?: string
|
|
/** Summary field (when configured and filled) or meta.description. */
|
|
description?: string
|
|
/** The raw document in this locale — for callers that render content (llms-full). */
|
|
doc: Record<string, unknown>
|
|
id: number | string
|
|
locale: string
|
|
/** Locale-aware path, e.g. /pl/blog/moj-wpis. */
|
|
path: string
|
|
/** publishedAt when the collection has it (setPublishedAt hook). */
|
|
publishedAt?: string
|
|
title: string
|
|
updatedAt?: string
|
|
/** Absolute URL (path prefixed with baseUrl). */
|
|
url: string
|
|
}
|
|
|
|
export type CollectSiteIndexArgs = {
|
|
/** Absolute origin; omit for relative URLs. */
|
|
baseUrl?: string
|
|
config: I18nConfig
|
|
/** Archive-backed collections, same value as the plugin option — their entries are included. */
|
|
content?: ContentOption
|
|
/** Population depth of `doc`. Default 0 (1 when you render blocks with images). */
|
|
depth?: number
|
|
/**
|
|
* Only paths this returns true for — e.g. the pages still open while the site
|
|
* is under construction. Default: every path.
|
|
*/
|
|
include?: (path: string) => boolean
|
|
/** Max documents per collection and locale. Default: no limit (read in batches of 500). */
|
|
limit?: number
|
|
/** Only these locales. Default: every configured locale. */
|
|
locales?: string[]
|
|
/** Pages collection. Default 'pages'. */
|
|
pagesSlug?: string
|
|
payload: BasePayload
|
|
/** SiteSettings global. Default 'site-settings'. */
|
|
settingsSlug?: string
|
|
/** Field holding a richer AI summary (buildSummaryField) to prefer as description. */
|
|
summaryField?: string
|
|
}
|
|
|
|
type Row = {
|
|
[key: string]: unknown
|
|
_status?: string
|
|
createdAt?: string
|
|
id: number | string
|
|
meta?: { description?: unknown; noindex?: boolean } | null
|
|
noindex?: boolean | null
|
|
publishedAt?: unknown
|
|
slug?: unknown
|
|
title?: unknown
|
|
updatedAt?: string
|
|
}
|
|
|
|
/** Same exclusions as the sitemap: error/system pages that exist as documents. */
|
|
const EXCLUDED_SLUGS = new Set(['404', '500', 'error', 'not-found'])
|
|
|
|
function slugMap(rel: unknown, locales: string[]): Record<string, string> | undefined {
|
|
if (!rel || typeof rel !== 'object') {return undefined}
|
|
const slug = (rel as { slug?: unknown }).slug
|
|
if (typeof slug === 'string') {return Object.fromEntries(locales.map((l) => [l, slug]))}
|
|
if (!slug || typeof slug !== 'object') {return undefined}
|
|
const map: Record<string, string> = {}
|
|
for (const l of locales) {
|
|
const v = (slug as Record<string, unknown>)[l]
|
|
if (typeof v === 'string') {map[l] = v}
|
|
}
|
|
return Object.keys(map).length ? map : undefined
|
|
}
|
|
|
|
const BATCH = 500
|
|
|
|
/** Published documents of one collection in one locale, BATCH at a time, up to `limit`. */
|
|
async function readDocs(
|
|
payload: BasePayload,
|
|
collection: string,
|
|
{ depth, limit, locale }: { depth: number; limit?: number; locale: string },
|
|
): Promise<Row[]> {
|
|
const cfg = (payload.collections as Record<string, { config?: { versions?: { drafts?: unknown } | false } }> | undefined)?.[collection]?.config
|
|
const drafts = Boolean(cfg?.versions && cfg.versions.drafts)
|
|
const docs: Row[] = []
|
|
const size = limit === undefined ? BATCH : Math.max(1, Math.min(BATCH, limit))
|
|
for (let page = 1; limit === undefined || docs.length < limit; page++) {
|
|
const res = await payload.find({
|
|
collection: collection as never,
|
|
depth,
|
|
limit: size,
|
|
locale: locale as never,
|
|
page,
|
|
...(drafts ? { where: { _status: { equals: 'published' } } } : {}),
|
|
})
|
|
docs.push(...((res?.docs ?? []) as Row[]))
|
|
if (!res?.hasNextPage) {break}
|
|
}
|
|
return limit === undefined ? docs : docs.slice(0, limit)
|
|
}
|
|
|
|
/**
|
|
* Every public page and archive entry, per language, with its URL, title,
|
|
* description and dates — ONE source for everything that lists the site to
|
|
* machines: llms.txt / llms-full.txt, the MCP server's list_pages, IndexNow.
|
|
* Uses the same rules as the sitemap (published only, no noindex, no 404/500
|
|
* pages, archive prefixes and homepage from System Pages), so all of them
|
|
* agree with what the site actually serves.
|
|
*
|
|
* Never throws for a missing field: a collection that can't be read is skipped.
|
|
*/
|
|
export async function collectSiteIndex({
|
|
baseUrl,
|
|
config,
|
|
content,
|
|
depth = 0,
|
|
include,
|
|
limit,
|
|
locales,
|
|
pagesSlug = 'pages',
|
|
payload,
|
|
settingsSlug = 'site-settings',
|
|
summaryField,
|
|
}: CollectSiteIndexArgs): Promise<SiteIndexEntry[]> {
|
|
const all = getLocaleCodes(config)
|
|
const wanted = (locales ?? all).filter((l) => isValidLocale(l, config))
|
|
const origin = baseUrl?.replace(/\/$/, '') ?? ''
|
|
|
|
let settings: Record<string, unknown> = {}
|
|
try {
|
|
settings = (await payload.findGlobal({ slug: settingsSlug as never, depth: 1, locale: 'all' as never })) as Record<string, unknown>
|
|
} catch {
|
|
// no settings yet (fresh DB) — no homepage/archives, plain paths
|
|
}
|
|
const homeSlug = slugMap(settings.homepage, all) ?? 'home'
|
|
|
|
const collections: { prefix?: Record<string, string>; slug: string }[] = [{ slug: pagesSlug }]
|
|
for (const c of content?.collections ?? []) {
|
|
const prefix = slugMap(settings[archiveFieldName(c.slug)], all)
|
|
collections.push({ slug: c.slug, prefix })
|
|
}
|
|
|
|
const entries: SiteIndexEntry[] = []
|
|
const unlisted = unlistedPageIds(settings)
|
|
for (const locale of wanted) {
|
|
for (const { slug: collection, prefix } of collections) {
|
|
// An archive collection without an archive page in this locale has no URLs there.
|
|
if (collection !== pagesSlug && !prefix?.[locale]) {continue}
|
|
let docs: Row[] = []
|
|
try {
|
|
docs = await readDocs(payload, collection, { depth, limit, locale })
|
|
} catch {
|
|
continue
|
|
}
|
|
const labels = payload.collections?.[collection as never]?.config?.labels as { plural?: unknown } | undefined
|
|
const collectionLabel = resolveLocalized(labels?.plural, locale, collection)
|
|
|
|
for (const doc of docs) {
|
|
if (doc._status && doc._status !== 'published') {continue}
|
|
if (doc.noindex || doc.meta?.noindex) {continue}
|
|
if (collection === pagesSlug && unlisted.has(doc.id)) {continue}
|
|
const title = typeof doc.title === 'string' ? doc.title.trim() : ''
|
|
const slug = typeof doc.slug === 'string' ? doc.slug : ''
|
|
if (!title || !slug || EXCLUDED_SLUGS.has(slug)) {continue}
|
|
const path = buildLocalizedPath({ config, homeSlug, locale, prefix, slugs: { [locale]: slug } })
|
|
if (!path || (include && !include(path))) {continue}
|
|
const summary = summaryField && typeof doc[summaryField] === 'string' ? (doc[summaryField]).trim() : ''
|
|
const metaDescription = typeof doc.meta?.description === 'string' ? doc.meta.description.trim() : ''
|
|
const description = summary || metaDescription
|
|
entries.push({
|
|
id: doc.id,
|
|
collection,
|
|
collectionLabel,
|
|
doc,
|
|
locale,
|
|
path,
|
|
title,
|
|
url: `${origin}${path}`,
|
|
...(description ? { description } : {}),
|
|
...(typeof doc.createdAt === 'string' ? { createdAt: doc.createdAt } : {}),
|
|
...(typeof doc.updatedAt === 'string' ? { updatedAt: doc.updatedAt } : {}),
|
|
...(typeof doc.publishedAt === 'string' ? { publishedAt: doc.publishedAt } : {}),
|
|
})
|
|
}
|
|
}
|
|
}
|
|
return entries
|
|
}
|