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]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
12fbd424a5
commit
94e563055f
@@ -15,6 +15,7 @@ import type { PageMetadata, RobotsOptions, RobotsRules, SitemapEntry, SitemapSty
|
||||
|
||||
import { getAnalyticsConfig } from '../analytics/getAnalyticsConfig.js'
|
||||
import { getConsentTexts } from '../consent/getConsentTexts.js'
|
||||
import { normalizePath } from '../construction/logic.js'
|
||||
import { createMarkdownRoute } from '../content/createMarkdownRenderer.js'
|
||||
import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js'
|
||||
import { MARKDOWN_PREFIX, markdownHref } from '../content/markdownNegotiation.js'
|
||||
@@ -30,9 +31,19 @@ import { buildWebSiteJsonLd } from '../seo/buildWebSiteJsonLd.js'
|
||||
import { buildArticleJsonLd, buildBreadcrumbJsonLd, buildFaqJsonLd, buildRobots, buildSitemapEntries, createManifestHandler, createPageMetadata, createSitemapRouteHandler } from '../seo/index.js'
|
||||
import { createIndexNowKeyRoute } from '../seo/indexNow.js'
|
||||
import { createLlmsTxtRoute } from '../seo/routeHandlers.js'
|
||||
import { robotsOptionsFrom } from '../seo/searchSettings.js'
|
||||
import { type ThemeConfig, themeConfigFrom } from '../theme/theme.js'
|
||||
import { getTurnstileConfig } from '../turnstile/config.js'
|
||||
|
||||
/** Path of an absolute or relative URL: 'https://acme.pl/pl/o-nas' → '/pl/o-nas'. */
|
||||
const pathOf = (url: string): string => {
|
||||
try {
|
||||
return new URL(url, 'http://local').pathname
|
||||
} catch {
|
||||
return url
|
||||
}
|
||||
}
|
||||
|
||||
type CreateContentHelpersArgs = {
|
||||
/**
|
||||
* Absolute site origin for sitemap/robots URLs. Falls back to
|
||||
@@ -424,7 +435,7 @@ export function createContentHelpers({
|
||||
)
|
||||
}
|
||||
try {
|
||||
return await buildSitemapEntries({
|
||||
const entries = await buildSitemapEntries({
|
||||
baseUrl: origin,
|
||||
config: i18n,
|
||||
content,
|
||||
@@ -433,10 +444,19 @@ export function createContentHelpers({
|
||||
payload: await getCachedPayload(),
|
||||
settingsSlug,
|
||||
})
|
||||
// Under construction: list only the pages visitors can still open — the
|
||||
// rest redirect to the homepage notice, which crawlers would index.
|
||||
const open = await constructionPaths()
|
||||
if (!open) {return entries}
|
||||
const allowed = new Set(open.map(normalizePath))
|
||||
return entries.filter((e) => allowed.has(normalizePath(pathOf(e.url))))
|
||||
} catch (error) {
|
||||
// DB unreachable (typically a container build with no DB network) — return
|
||||
// an empty sitemap instead of failing the build. Runtime regeneration will
|
||||
// produce the real one once the DB is reachable. See dynamic='force-dynamic'.
|
||||
// At runtime a failure is an error (the sitemap route answers 503, so
|
||||
// crawlers retry) — an empty sitemap would read as "no pages".
|
||||
if (process.env.NEXT_PHASE !== 'phase-production-build') {throw error}
|
||||
// DB unreachable during `next build` (container with no DB network) —
|
||||
// return an empty sitemap instead of failing the build. Runtime regeneration
|
||||
// produces the real one. See dynamic='force-dynamic'.
|
||||
console.warn(
|
||||
'[ipal] sitemap: could not reach the database, returning empty entries ' +
|
||||
"(add `export const dynamic = 'force-dynamic'` to app/sitemap.ts to " +
|
||||
@@ -457,6 +477,37 @@ export function createContentHelpers({
|
||||
*/
|
||||
const robots = (): RobotsRules => buildRobots({ ...robotsOptions, baseUrl: origin })
|
||||
|
||||
/**
|
||||
* `robots` plus what editors set in Site Settings → Search & AI (AI bot policy
|
||||
* and per-bot exceptions), read per request. Use it instead of `robots` to
|
||||
* let the panel manage AI crawlers:
|
||||
*
|
||||
* ```ts
|
||||
* // app/robots.ts
|
||||
* export { getRobots as default } from '@/lib/content'
|
||||
* export const dynamic = 'force-dynamic'
|
||||
* ```
|
||||
*
|
||||
* Database unreachable → the options from code, as `robots` returns.
|
||||
*/
|
||||
const getRobots = async (): Promise<RobotsRules> => {
|
||||
let fromPanel: ReturnType<typeof robotsOptionsFrom> = {}
|
||||
try {
|
||||
const payload = await getCachedPayload()
|
||||
fromPanel = robotsOptionsFrom(
|
||||
(await payload.findGlobal({ slug: settingsSlug as never, depth: 0 })) as Record<string, unknown>,
|
||||
)
|
||||
} catch {
|
||||
// keep the code options
|
||||
}
|
||||
return buildRobots({
|
||||
...robotsOptions,
|
||||
...fromPanel,
|
||||
aiBotRules: [...(robotsOptions?.aiBotRules ?? []), ...(fromPanel.aiBotRules ?? [])],
|
||||
baseUrl: origin,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Next.js generateStaticParams for the [[...slug]] route (or
|
||||
* [locale]/[[...slug]]). Returns every routable page as a params object, so
|
||||
@@ -680,6 +731,21 @@ export function createContentHelpers({
|
||||
}
|
||||
})
|
||||
|
||||
/**
|
||||
* While Site Settings → Under construction is on: the paths still open (every
|
||||
* language), which the sitemap and llms.txt list instead of everything.
|
||||
* null when the site is open or the setting can't be read.
|
||||
*/
|
||||
const constructionPaths = async (): Promise<null | string[]> => {
|
||||
if (!i18n) {return null}
|
||||
try {
|
||||
const mode = await getConstructionMode(i18n.defaultLocale)
|
||||
return mode.enabled ? mode.allowedPaths : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// ── Layout ────────────────────────────────────────────────────────────────
|
||||
/** Notifications → form texts in this locale (BuilderForm / RenderForm `texts`). */
|
||||
const getFormTexts = cache(async (locale: string): Promise<FormNotificationTexts> =>
|
||||
@@ -730,8 +796,8 @@ export function createContentHelpers({
|
||||
let value: T | undefined
|
||||
return () => (value ??= make())
|
||||
}
|
||||
const llms = lazy(() => createLlmsTxtRoute({ baseUrl: origin, config: needI18n('llmsRoute'), content, getCachedPayload, pagesSlug, settingsSlug, summaryField }))
|
||||
const llmsFull = lazy(() => createLlmsTxtRoute({ baseUrl: origin, config: needI18n('llmsFullRoute'), content, full: true, getCachedPayload, pagesSlug, settingsSlug, summaryField }))
|
||||
const llms = lazy(() => createLlmsTxtRoute({ baseUrl: origin, config: needI18n('llmsRoute'), content, getCachedPayload, getIncludedPaths: constructionPaths, pagesSlug, settingsSlug, summaryField }))
|
||||
const llmsFull = lazy(() => createLlmsTxtRoute({ baseUrl: origin, config: needI18n('llmsFullRoute'), content, full: true, getCachedPayload, getIncludedPaths: constructionPaths, pagesSlug, settingsSlug, summaryField }))
|
||||
const md = lazy(() => createMarkdownRoute({ baseUrl: origin || undefined, collection: pagesSlug, config: i18n, content, getCachedPayload, settingsSlug, ...markdownOptions }))
|
||||
const mcp = lazy(() => createMcpRoute({ baseUrl: origin, collection: pagesSlug, config: needI18n('mcpRoute'), content, getCachedPayload, settingsSlug, summaryField, ...mcpOptions }))
|
||||
const health = lazy(() => createHealthRoute({ collection: pagesSlug, getCachedPayload }))
|
||||
@@ -766,6 +832,7 @@ export function createContentHelpers({
|
||||
getLinkOptions,
|
||||
getNotFoundPage,
|
||||
getPageJsonLd,
|
||||
getRobots,
|
||||
getSettings,
|
||||
getSiteShell,
|
||||
getSystemLinks,
|
||||
|
||||
@@ -197,6 +197,7 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
|
||||
baseUrl: origin,
|
||||
config,
|
||||
content,
|
||||
limit: 1000, // list_pages shows at most 200 — no need to read a huge site whole
|
||||
locales: [locale],
|
||||
pagesSlug: collection,
|
||||
payload,
|
||||
|
||||
@@ -6,6 +6,7 @@ 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 = {
|
||||
@@ -25,6 +26,8 @@ type BuildLlmsTxtArgs = {
|
||||
* 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
|
||||
/**
|
||||
@@ -45,6 +48,7 @@ type BuildLlmsTxtArgs = {
|
||||
}
|
||||
|
||||
type SettingsShape = {
|
||||
[key: string]: unknown
|
||||
siteDescription?: null | string
|
||||
siteName?: null | string
|
||||
}
|
||||
@@ -57,7 +61,8 @@ const day = (iso?: string) => (iso ? iso.slice(0, 10) : undefined)
|
||||
* 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 — per
|
||||
* 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
|
||||
@@ -74,6 +79,7 @@ export async function buildLlmsTxt({
|
||||
config,
|
||||
content,
|
||||
full = false,
|
||||
include,
|
||||
layoutField = 'layout',
|
||||
locale,
|
||||
pagesSlug = 'pages',
|
||||
@@ -99,6 +105,7 @@ export async function buildLlmsTxt({
|
||||
config,
|
||||
content,
|
||||
depth: full ? 1 : 0,
|
||||
include,
|
||||
locales,
|
||||
pagesSlug,
|
||||
payload,
|
||||
@@ -108,6 +115,9 @@ export async function buildLlmsTxt({
|
||||
|
||||
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) {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { I18nConfig, LocalizedSlugs } from '../i18n/index.js'
|
||||
import type { TitleOrder } from './composeTitle.js'
|
||||
import type { VerificationMetadata } from './searchSettings.js'
|
||||
import type { SeoMeta } from './types.js'
|
||||
|
||||
import { buildLocalizedPath } from '../i18n/index.js'
|
||||
@@ -59,6 +60,8 @@ export type PageMetadata = {
|
||||
images?: string[]
|
||||
title: string
|
||||
}
|
||||
/** Search console ownership tags (google-site-verification, msvalidate.01, yandex-verification). */
|
||||
verification?: VerificationMetadata
|
||||
}
|
||||
|
||||
type BuildMetadataArgs = {
|
||||
@@ -122,6 +125,8 @@ type BuildMetadataArgs = {
|
||||
siteName?: null | string
|
||||
/** slug per locale for this document — drives canonical + hreflang. */
|
||||
slugs: LocalizedSlugs
|
||||
/** Site Settings → Search & AI verification codes; rendered as <meta> tags by Next. */
|
||||
verification?: VerificationMetadata
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -151,6 +156,7 @@ export function buildMetadata({
|
||||
siteDescription,
|
||||
siteName,
|
||||
slugs,
|
||||
verification,
|
||||
}: BuildMetadataArgs): PageMetadata {
|
||||
// Title source priority: titleOverride (exact, wins outright) > meta.title
|
||||
// (SEO title an editor set) > pageTitle (the document's own name). This means
|
||||
@@ -203,6 +209,7 @@ export function buildMetadata({
|
||||
...(description && { description }),
|
||||
...(ogImage ? { images: [ogImage.url] } : {}),
|
||||
},
|
||||
...(verification ? { verification } : {}),
|
||||
// robots: noindex pages are excluded (follow keeps link authority). Indexed
|
||||
// pages get generous snippet/preview limits so Google can show rich results
|
||||
// (long snippets, large image previews, full video previews).
|
||||
|
||||
@@ -12,12 +12,15 @@ type RobotRule = { allow?: string; disallow?: string[]; userAgent: string | stri
|
||||
*/
|
||||
export const AI_ASSISTANT_BOTS = [
|
||||
'ClaudeBot',
|
||||
'Claude-User',
|
||||
'Claude-Web',
|
||||
'Claude-SearchBot',
|
||||
'ChatGPT-User',
|
||||
'OAI-SearchBot',
|
||||
'PerplexityBot',
|
||||
'Perplexity-User',
|
||||
'MistralAI-User',
|
||||
'DuckAssistBot',
|
||||
] as const
|
||||
|
||||
export const AI_TRAINING_BOTS = [
|
||||
@@ -30,7 +33,10 @@ export const AI_TRAINING_BOTS = [
|
||||
'Meta-ExternalAgent',
|
||||
] as const
|
||||
|
||||
type AiBotsPolicy = 'allow' | 'block-training' | 'disallow' | false
|
||||
export type AiBotsPolicy = 'allow' | 'block-training' | 'disallow' | false
|
||||
|
||||
/** One bot treated differently from the policy, e.g. { userAgent: 'Bytespider', access: 'disallow' }. */
|
||||
export type AiBotRule = { access: 'allow' | 'disallow'; userAgent: string }
|
||||
|
||||
export type RobotsOptions = {
|
||||
/**
|
||||
@@ -41,6 +47,12 @@ export type RobotsOptions = {
|
||||
adminRoute?: false | string
|
||||
/** Override the assistant/search bot list. */
|
||||
aiAssistantAgents?: readonly string[]
|
||||
/**
|
||||
* Per-bot exceptions that win over `aiBots` — a listed bot leaves its policy
|
||||
* group and gets its own allow or block. Unknown bots can be added this way.
|
||||
* Site Settings → Search & AI fills it when you use `getRobots`.
|
||||
*/
|
||||
aiBotRules?: readonly AiBotRule[]
|
||||
/**
|
||||
* How to treat AI crawlers (assistant/search + training). Default 'allow' —
|
||||
* explicitly welcome them so the site stays visible to Claude, ChatGPT,
|
||||
@@ -118,6 +130,7 @@ export type RobotsRules = {
|
||||
export function buildRobots({
|
||||
adminRoute = '/admin',
|
||||
aiAssistantAgents = AI_ASSISTANT_BOTS,
|
||||
aiBotRules = [],
|
||||
aiBots = 'allow',
|
||||
aiTrainingAgents = AI_TRAINING_BOTS,
|
||||
baseUrl,
|
||||
@@ -139,15 +152,32 @@ export function buildRobots({
|
||||
|
||||
const baseRule: RobotRule = { allow: '/', disallow, userAgent: '*' }
|
||||
|
||||
const aiRules: RobotRule[] = []
|
||||
if (aiBots === 'allow') {
|
||||
aiRules.push({ allow: '/', disallow, userAgent: [...aiAssistantAgents, ...aiTrainingAgents] })
|
||||
} else if (aiBots === 'block-training') {
|
||||
aiRules.push({ allow: '/', disallow, userAgent: [...aiAssistantAgents] })
|
||||
aiRules.push({ disallow: ['/'], userAgent: [...aiTrainingAgents] })
|
||||
} else if (aiBots === 'disallow') {
|
||||
aiRules.push({ disallow: ['/'], userAgent: [...aiAssistantAgents, ...aiTrainingAgents] })
|
||||
// Exceptions: last rule per bot wins; those bots leave the policy groups.
|
||||
const exceptions = new Map<string, AiBotRule>()
|
||||
for (const r of aiBotRules) {
|
||||
const ua = r.userAgent.trim()
|
||||
if (ua) {exceptions.set(ua.toLowerCase(), { access: r.access, userAgent: ua })}
|
||||
}
|
||||
const notExcepted = (list: readonly string[]) => list.filter((ua) => !exceptions.has(ua.toLowerCase()))
|
||||
const assistants = notExcepted(aiAssistantAgents)
|
||||
const training = notExcepted(aiTrainingAgents)
|
||||
|
||||
const aiRules: RobotRule[] = []
|
||||
const push = (rule: RobotRule) => {
|
||||
if (rule.userAgent.length) {aiRules.push(rule)}
|
||||
}
|
||||
if (aiBots === 'allow') {
|
||||
push({ allow: '/', disallow, userAgent: [...assistants, ...training] })
|
||||
} else if (aiBots === 'block-training') {
|
||||
push({ allow: '/', disallow, userAgent: assistants })
|
||||
push({ disallow: ['/'], userAgent: training })
|
||||
} else if (aiBots === 'disallow') {
|
||||
push({ disallow: ['/'], userAgent: [...assistants, ...training] })
|
||||
}
|
||||
const allowed = [...exceptions.values()].filter((r) => r.access === 'allow').map((r) => r.userAgent)
|
||||
const blocked = [...exceptions.values()].filter((r) => r.access === 'disallow').map((r) => r.userAgent)
|
||||
push({ allow: '/', disallow, userAgent: allowed })
|
||||
push({ disallow: ['/'], userAgent: blocked })
|
||||
|
||||
return {
|
||||
rules: aiRules.length > 0 ? [baseRule, ...aiRules] : baseRule,
|
||||
|
||||
@@ -52,10 +52,19 @@ type BuildSitemapArgs = {
|
||||
/** Pages collection slug. Defaults to 'pages'. */
|
||||
pagesSlug?: string
|
||||
payload: BasePayload
|
||||
/**
|
||||
* Read only the fields the sitemap needs (slug, dates, status, noindex, meta).
|
||||
* Default: on with the default `images`, off with a custom `images` (it may
|
||||
* read any field). `false` reads whole documents.
|
||||
*/
|
||||
select?: boolean
|
||||
/** SiteSettings global slug. Defaults to 'site-settings'. */
|
||||
settingsSlug?: string
|
||||
}
|
||||
|
||||
/** Documents read per query — keeps memory flat on large collections. */
|
||||
export const SITEMAP_BATCH_SIZE = 500
|
||||
|
||||
type DocRow = {
|
||||
[key: string]: unknown
|
||||
_status?: string
|
||||
@@ -140,6 +149,51 @@ function defaultImages(doc: Record<string, unknown>): (null | string | undefined
|
||||
return image && typeof image === 'object' ? [(image as { url?: string }).url] : []
|
||||
}
|
||||
|
||||
type CollectionConfigShape = {
|
||||
flattenedFields?: { name?: string }[]
|
||||
versions?: { drafts?: unknown } | false
|
||||
}
|
||||
|
||||
/**
|
||||
* Query shape for one collection: published only (when it has drafts) and,
|
||||
* with `select`, just the fields entryFor/isIndexable read. Fields the
|
||||
* collection doesn't have are left out of the select.
|
||||
*/
|
||||
function queryFor(payload: BasePayload, slug: string, select: boolean) {
|
||||
const cfg = (payload.collections as Record<string, { config?: CollectionConfigShape }> | undefined)?.[slug]?.config
|
||||
const hasDrafts = Boolean(cfg?.versions && cfg.versions.drafts)
|
||||
const names = new Set((cfg?.flattenedFields ?? []).map((f) => f.name))
|
||||
const pick = select && cfg?.flattenedFields
|
||||
? Object.fromEntries(
|
||||
['slug', 'updatedAt', 'noindex', 'meta']
|
||||
.filter((n) => n === 'updatedAt' || names.has(n))
|
||||
.concat(hasDrafts ? ['_status'] : [])
|
||||
.map((n) => [n, true]),
|
||||
)
|
||||
: undefined
|
||||
return {
|
||||
...(hasDrafts ? { where: { _status: { equals: 'published' } } } : {}),
|
||||
...(pick ? { select: pick } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
/** Every document of a collection, SITEMAP_BATCH_SIZE at a time. */
|
||||
async function* readAll(payload: BasePayload, slug: string, select: boolean): AsyncGenerator<DocRow> {
|
||||
const query = queryFor(payload, slug, select)
|
||||
for (let page = 1; ; page++) {
|
||||
const result = await payload.find({
|
||||
collection: slug as never,
|
||||
depth: 1, // populate uploads so image URLs are available
|
||||
limit: SITEMAP_BATCH_SIZE,
|
||||
locale: 'all' as never,
|
||||
page,
|
||||
...(query as object),
|
||||
})
|
||||
yield* result.docs as DocRow[]
|
||||
if (!result.hasNextPage) {return}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects every public URL — pages and archive entries — as sitemap entries
|
||||
* with per-URL hreflang and lastmod.
|
||||
@@ -170,6 +224,7 @@ export async function buildSitemapEntries({
|
||||
images: imagesOf = defaultImages,
|
||||
pagesSlug = 'pages',
|
||||
payload,
|
||||
select = imagesOf === defaultImages,
|
||||
settingsSlug = 'site-settings',
|
||||
}: BuildSitemapArgs): Promise<SitemapEntry[]> {
|
||||
const origin = baseUrl.replace(/\/$/, '')
|
||||
@@ -212,16 +267,10 @@ export async function buildSitemapEntries({
|
||||
|
||||
for (const collection of collections) {
|
||||
// Read every doc once, across locales, so one row yields all its language
|
||||
// alternates without re-querying per locale.
|
||||
const result = await payload.find({
|
||||
collection: collection.slug as never,
|
||||
depth: 1, // populate uploads so image URLs are available
|
||||
limit: 0, // no pagination — sitemap wants everything
|
||||
locale: 'all' as never,
|
||||
pagination: false as never,
|
||||
})
|
||||
|
||||
for (const raw of result.docs as DocRow[]) {
|
||||
// alternates without re-querying per locale. Batched, published only, and
|
||||
// (by default) only the fields used here — a 20k-entry blog no longer
|
||||
// loads every block of every post into memory at once.
|
||||
for await (const raw of readAll(payload, collection.slug, select)) {
|
||||
if (!isIndexable(raw)) {continue}
|
||||
const images = [...new Set(imagesOf(raw).map(absolute).filter((u): u is string => Boolean(u)))]
|
||||
|
||||
|
||||
@@ -43,27 +43,53 @@ type BuildSitemapXmlOptions = {
|
||||
* NOTE: if you use this custom route, DON'T also keep app/sitemap.ts — pick one.
|
||||
* Two sitemaps confuse crawlers.
|
||||
*/
|
||||
const esc = (s: string): string =>
|
||||
s
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''')
|
||||
|
||||
const isoOf = (d: Date | string): string => (d instanceof Date ? d.toISOString() : String(d))
|
||||
|
||||
/** One child sitemap listed in a sitemap index. */
|
||||
export type SitemapIndexItem = { lastModified?: Date | string; url: string }
|
||||
|
||||
/**
|
||||
* Sitemap index (`<sitemapindex>`) — what /sitemap.xml returns once a site has
|
||||
* more URLs than one file should hold. Each child carries the newest lastmod
|
||||
* of its URLs, so crawlers re-read only the parts that changed.
|
||||
*/
|
||||
export function buildSitemapIndexXml(items: SitemapIndexItem[], opts: BuildSitemapXmlOptions = {}): string {
|
||||
const stylesheet = opts.cssUrl ? `<?xml-stylesheet type="text/css" href="${esc(opts.cssUrl)}"?>\n` : ''
|
||||
const body = items
|
||||
.map((i) => {
|
||||
const parts = [` <loc>${esc(i.url)}</loc>`]
|
||||
if (i.lastModified) {parts.push(` <lastmod>${esc(isoOf(i.lastModified))}</lastmod>`)}
|
||||
return ` <sitemap>\n${parts.join('\n')}\n </sitemap>`
|
||||
})
|
||||
.join('\n')
|
||||
return (
|
||||
`<?xml version="1.0" encoding="UTF-8"?>\n` +
|
||||
stylesheet +
|
||||
`<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n` +
|
||||
body +
|
||||
`\n</sitemapindex>`
|
||||
)
|
||||
}
|
||||
|
||||
export function buildSitemapXml(
|
||||
entries: SitemapEntry[],
|
||||
opts: BuildSitemapXmlOptions = {},
|
||||
): string {
|
||||
const { cssUrl } = opts
|
||||
|
||||
const esc = (s: string): string =>
|
||||
s
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''')
|
||||
|
||||
const urls = entries
|
||||
.map((e) => {
|
||||
const parts = [` <loc>${esc(e.url)}</loc>`]
|
||||
if (e.lastModified) {
|
||||
const iso =
|
||||
e.lastModified instanceof Date ? e.lastModified.toISOString() : String(e.lastModified)
|
||||
parts.push(` <lastmod>${esc(iso)}</lastmod>`)
|
||||
parts.push(` <lastmod>${esc(isoOf(e.lastModified))}</lastmod>`)
|
||||
}
|
||||
if (e.changeFrequency) {parts.push(` <changefreq>${e.changeFrequency}</changefreq>`)}
|
||||
if (typeof e.priority === 'number') {parts.push(` <priority>${e.priority}</priority>`)}
|
||||
|
||||
@@ -145,6 +145,7 @@ export function createPageMetadata(args: CreatePageMetadataArgs) {
|
||||
// fallback opisu: strona bez meta.description dostaje Site Settings → siteDescription (seo.md)
|
||||
siteDescription: site.siteDescription,
|
||||
siteName: site.siteName,
|
||||
verification: site.verification,
|
||||
}
|
||||
|
||||
const route = loaders?.resolveRoute
|
||||
@@ -162,8 +163,9 @@ export function createPageMetadata(args: CreatePageMetadataArgs) {
|
||||
|
||||
// Unknown route (the page component will 404) — still return something
|
||||
// coherent rather than throwing during metadata generation.
|
||||
// noindex: a 404 must never be indexed, even if a host serves it with 200.
|
||||
if (!route) {
|
||||
return buildMetadata({ ...base, meta: null, slugs: {} })
|
||||
return buildMetadata({ ...base, meta: null, noindex: true, slugs: {} })
|
||||
}
|
||||
|
||||
const doc = route.doc as DocShape
|
||||
|
||||
@@ -13,11 +13,12 @@ export { buildNoindexField } from './buildNoindexField.js'
|
||||
export { buildOrganizationJsonLd, sameAsUrls } from './buildOrganizationJsonLd.js'
|
||||
export { buildProductJsonLd } from './buildProductJsonLd.js'
|
||||
export { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, buildRobots } from './buildRobots.js'
|
||||
export type { AiBotRule, AiBotsPolicy } from './buildRobots.js'
|
||||
export type { RobotsOptions, RobotsRules } from './buildRobots.js'
|
||||
export { buildServiceJsonLd } from './buildServiceJsonLd.js'
|
||||
export { buildSitemapEntries } from './buildSitemapEntries.js'
|
||||
export type { SitemapEntry } from './buildSitemapEntries.js'
|
||||
export { buildSitemapXml } from './buildSitemapXml.js'
|
||||
export { buildSitemapIndexXml, buildSitemapXml } from './buildSitemapXml.js'
|
||||
export { buildNavigationJsonLd, buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js'
|
||||
export { buildSpeakableJsonLd } from './buildSpeakableJsonLd.js'
|
||||
export { buildSummaryField } from './buildSummaryField.js'
|
||||
@@ -42,8 +43,10 @@ export { injectSeoTabs } from './injectSeoTabs.js'
|
||||
export { JsonLdGraph } from './JsonLdGraph.js'
|
||||
export { readSiteMetaConfig } from './readSiteMetaConfig.js'
|
||||
export type { SiteMetaConfig } from './readSiteMetaConfig.js'
|
||||
export { createLlmsTxtRoute, createSitemapRouteHandler } from './routeHandlers.js'
|
||||
export { createLlmsTxtRoute, createSitemapRouteHandler, DEFAULT_SITEMAP_CACHE_CONTROL, DEFAULT_SITEMAP_MAX_URLS, SITEMAP_PART_PARAM } from './routeHandlers.js'
|
||||
export type { SitemapRouteOptions } from './routeHandlers.js'
|
||||
export { normalizeVerificationToken, robotsOptionsFrom, searchSettingsFields, verificationFrom } from './searchSettings.js'
|
||||
export type { VerificationMetadata } from './searchSettings.js'
|
||||
export { buildSeoPlugin } from './seoPluginConfig.js'
|
||||
export { collectSiteIndex } from './siteIndex.js'
|
||||
export type { CollectSiteIndexArgs, SiteIndexEntry } from './siteIndex.js'
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { I18nConfig } from '../i18n/index.js'
|
||||
|
||||
import { archiveFieldName } from '../content/types.js'
|
||||
import { buildLocalizedPath, getLocaleCodes, getLocalizedSlugs } from '../i18n/index.js'
|
||||
import { isSiteNoindex } from './siteNoindex.js'
|
||||
|
||||
/**
|
||||
* IndexNow — tell search engines a URL changed the moment it's published
|
||||
@@ -76,9 +77,14 @@ export function createIndexNowKeyRoute({ getCachedPayload }: { getCachedPayload:
|
||||
}
|
||||
}
|
||||
|
||||
/** True when submissions may leave this machine: production + a public https origin. */
|
||||
/**
|
||||
* True when submissions may leave this machine: production + a public https
|
||||
* origin, and not a staging copy (IPAL_NOINDEX) — a staging build runs with
|
||||
* NODE_ENV=production too, and its URLs must not reach Bing.
|
||||
*/
|
||||
function publicOrigin(baseUrl?: string): null | string {
|
||||
const origin = (baseUrl ?? process.env.NEXT_PUBLIC_SERVER_URL ?? '').replace(/\/$/, '')
|
||||
if (isSiteNoindex()) {return null}
|
||||
if (process.env.NODE_ENV !== 'production' || !/^https:\/\//i.test(origin)) {return null}
|
||||
if (/localhost|127\.0\.0\.1|\.local\b|\.test\b/i.test(origin)) {return null}
|
||||
return origin
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import type { BasePayload } from 'payload'
|
||||
|
||||
import type { TitleOrder } from './composeTitle.js'
|
||||
import type { VerificationMetadata } from './searchSettings.js'
|
||||
|
||||
import { verificationFrom } from './searchSettings.js'
|
||||
|
||||
type SettingsShape = {
|
||||
[key: string]: unknown
|
||||
@@ -25,6 +28,8 @@ export type SiteMetaConfig = {
|
||||
/** Global fallback meta description. */
|
||||
siteDescription?: null | string
|
||||
siteName: null | string
|
||||
/** Site Settings → Search & AI → verification codes (Search Console, Bing, Yandex). */
|
||||
verification?: VerificationMetadata
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -102,7 +107,9 @@ export async function readSiteMetaConfig({
|
||||
}
|
||||
|
||||
const share = settings.defaultShareImage
|
||||
const verification = verificationFrom(settings)
|
||||
return {
|
||||
...(verification ? { verification } : {}),
|
||||
defaultShareImage: share && typeof share === 'object' ? (share as Record<string, unknown>) : null,
|
||||
siteDescription: (settings.siteDescription as string | undefined) ?? null,
|
||||
siteName: (settings[siteNameField] as string | undefined) ?? null,
|
||||
|
||||
@@ -4,8 +4,9 @@ import type { ContentOption } from '../content/index.js'
|
||||
import type { I18nConfig } from '../i18n/index.js'
|
||||
import type { SitemapEntry } from './buildSitemapEntries.js'
|
||||
|
||||
import { normalizePath } from '../construction/logic.js'
|
||||
import { buildLlmsTxt } from './buildLlmsTxt.js'
|
||||
import { buildSitemapXml } from './buildSitemapXml.js'
|
||||
import { buildSitemapIndexXml, buildSitemapXml } from './buildSitemapXml.js'
|
||||
import { buildSitemapCss, SITEMAP_STYLE_PARAM, type SitemapStyleOptions } from './sitemapStyle.js'
|
||||
|
||||
/**
|
||||
@@ -35,6 +36,11 @@ export function createLlmsTxtRoute(opts: {
|
||||
/** Inline every page's full Markdown (llms-full.txt). Default false. */
|
||||
full?: boolean
|
||||
getCachedPayload: () => Promise<BasePayload>
|
||||
/**
|
||||
* Paths to list, read per request — null lists everything. createContentHelpers
|
||||
* passes the pages still open while the site is under construction.
|
||||
*/
|
||||
getIncludedPaths?: () => Promise<null | readonly string[]>
|
||||
pagesSlug?: string
|
||||
settingsSlug?: string
|
||||
/** Field holding a richer AI summary (buildSummaryField) to prefer as description. */
|
||||
@@ -43,11 +49,14 @@ export function createLlmsTxtRoute(opts: {
|
||||
return async () => {
|
||||
try {
|
||||
const payload = await opts.getCachedPayload()
|
||||
const paths = opts.getIncludedPaths ? await opts.getIncludedPaths() : null
|
||||
const allowed = paths ? new Set(paths.map(normalizePath)) : null
|
||||
const body = await buildLlmsTxt({
|
||||
baseUrl: opts.baseUrl,
|
||||
config: opts.config,
|
||||
content: opts.content,
|
||||
full: opts.full,
|
||||
...(allowed ? { include: (path: string) => allowed.has(normalizePath(path)) } : {}),
|
||||
pagesSlug: opts.pagesSlug,
|
||||
payload,
|
||||
settingsSlug: opts.settingsSlug,
|
||||
@@ -56,22 +65,61 @@ export function createLlmsTxtRoute(opts: {
|
||||
return new Response(body, {
|
||||
// For AI agents, not a search result: keep it (and the full-content
|
||||
// copy, a duplicate of every page) out of search indexes.
|
||||
headers: { 'Content-Type': 'text/plain; charset=utf-8', 'X-Robots-Tag': 'noindex' },
|
||||
headers: {
|
||||
// Same as the sitemap: a CDN keeps it an hour; llms-full renders every page.
|
||||
'Cache-Control': DEFAULT_SITEMAP_CACHE_CONTROL,
|
||||
'Content-Type': 'text/plain; charset=utf-8',
|
||||
'X-Robots-Tag': 'noindex',
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
// DB unreachable at build (container) — return a minimal valid file so the
|
||||
// route doesn't 500; it fills in at runtime. No per-project try/catch.
|
||||
console.warn('[ipal] createLlmsTxtRoute: could not build llms.txt:', err)
|
||||
return new Response('# llms.txt\n', {
|
||||
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
|
||||
headers: { 'Cache-Control': 'no-store', 'Content-Type': 'text/plain; charset=utf-8', 'X-Robots-Tag': 'noindex' },
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Query parameter of a sitemap part: /sitemap.xml?part=2. */
|
||||
export const SITEMAP_PART_PARAM = 'part'
|
||||
export const DEFAULT_SITEMAP_MAX_URLS = 10_000
|
||||
export const DEFAULT_SITEMAP_CACHE_CONTROL = 'public, max-age=0, s-maxage=3600, stale-while-revalidate=86400'
|
||||
|
||||
/** Newest lastModified of a batch — the part's own lastmod in the index. */
|
||||
function newest(entries: SitemapEntry[]): string | undefined {
|
||||
let best: number | undefined
|
||||
for (const e of entries) {
|
||||
const t = e.lastModified ? new Date(e.lastModified).getTime() : NaN
|
||||
if (!Number.isNaN(t) && (best === undefined || t > best)) {best = t}
|
||||
}
|
||||
return best === undefined ? undefined : new Date(best).toISOString()
|
||||
}
|
||||
|
||||
export type SitemapRouteOptions = {
|
||||
/**
|
||||
* Cache-Control of the XML. Default: browsers revalidate, shared caches (CDN)
|
||||
* keep it an hour and may serve a stale copy for a day while refreshing.
|
||||
* `false` sends no header. An error response is never cached.
|
||||
*/
|
||||
cacheControl?: false | string
|
||||
/** Legacy: your own stylesheet URL (e.g. '/sitemap.css'). Overrides `style`. */
|
||||
cssUrl?: string
|
||||
/**
|
||||
* Max URLs in one file. Above it /sitemap.xml becomes a sitemap index of
|
||||
* parts at `?part=1`, `?part=2`… (the protocol allows 50 000 URLs / 50 MB;
|
||||
* hreflang alternates make each URL large, hence the lower default).
|
||||
* Default 10 000.
|
||||
*/
|
||||
maxUrls?: number
|
||||
/**
|
||||
* Seconds the built entries are reused inside this server process, so the
|
||||
* index and its parts (and repeated crawler hits) don't rebuild from the
|
||||
* database each time. Default 300; 0 turns it off.
|
||||
*/
|
||||
memoSeconds?: number
|
||||
/**
|
||||
* Built-in browser look (default ON): the XML points at `<this route>?style`
|
||||
* and the same handler serves the CSS — nothing to copy into /public.
|
||||
@@ -90,6 +138,8 @@ export type SitemapRouteOptions = {
|
||||
* export const dynamic = 'force-dynamic'
|
||||
*
|
||||
* `GET /sitemap.xml` → XML (crawlers), `GET /sitemap.xml?style` → its CSS.
|
||||
* Over `maxUrls` URLs, /sitemap.xml is an index and the URLs sit in
|
||||
* `/sitemap.xml?part=N` — robots.txt and Search Console keep the one address.
|
||||
* Don't keep app/sitemap.ts next to it — two sitemaps confuse crawlers.
|
||||
*/
|
||||
export function createSitemapRouteHandler(
|
||||
@@ -97,6 +147,25 @@ export function createSitemapRouteHandler(
|
||||
opts: SitemapRouteOptions = {},
|
||||
): (req: Request) => Promise<Response> {
|
||||
const style = opts.cssUrl ? false : opts.style === false ? false : (opts.style ?? {})
|
||||
const maxUrls = Math.max(1, Math.floor(opts.maxUrls ?? DEFAULT_SITEMAP_MAX_URLS))
|
||||
const memoMs = Math.max(0, opts.memoSeconds ?? 300) * 1000
|
||||
const cacheControl = opts.cacheControl === undefined ? DEFAULT_SITEMAP_CACHE_CONTROL : opts.cacheControl
|
||||
const xmlHeaders = {
|
||||
'Content-Type': 'application/xml; charset=utf-8',
|
||||
...(cacheControl ? { 'Cache-Control': cacheControl } : {}),
|
||||
}
|
||||
|
||||
let memo: { at: number; entries: Promise<SitemapEntry[]> } | undefined
|
||||
const entries = (): Promise<SitemapEntry[]> => {
|
||||
if (memoMs && memo && Date.now() - memo.at < memoMs) {return memo.entries}
|
||||
const fresh = sitemap()
|
||||
// A failed or empty build (sitemap() returns [] when the database is
|
||||
// unreachable) is not reused — the next request tries again.
|
||||
const forget = () => { if (memo?.entries === fresh) {memo = undefined} }
|
||||
fresh.then((list) => { if (!list.length) {forget()} }, forget)
|
||||
if (memoMs) {memo = { at: Date.now(), entries: fresh }}
|
||||
return fresh
|
||||
}
|
||||
|
||||
// `req` is required: Next 16 type-checks the first argument of a route handler
|
||||
// (`Request | undefined` fails the build). A zero-argument call is not supported.
|
||||
@@ -121,19 +190,47 @@ export function createSitemapRouteHandler(
|
||||
|
||||
const cssUrl = opts.cssUrl ?? (style ? `${url.pathname}?${SITEMAP_STYLE_PARAM}` : undefined)
|
||||
try {
|
||||
const entries = await sitemap()
|
||||
const xml = buildSitemapXml(entries, { cssUrl })
|
||||
return new Response(xml, {
|
||||
headers: { 'Content-Type': 'application/xml; charset=utf-8' },
|
||||
})
|
||||
const all = await entries()
|
||||
const parts = Math.ceil(all.length / maxUrls)
|
||||
const partParam = url.searchParams.get(SITEMAP_PART_PARAM)
|
||||
|
||||
if (partParam !== null) {
|
||||
const part = Number(partParam)
|
||||
if (!Number.isInteger(part) || part < 1 || part > Math.max(parts, 1)) {
|
||||
return new Response('Not found', { headers: { 'Cache-Control': 'no-store' }, status: 404 })
|
||||
}
|
||||
const slice = all.slice((part - 1) * maxUrls, part * maxUrls)
|
||||
return new Response(buildSitemapXml(slice, { cssUrl }), { headers: xmlHeaders })
|
||||
}
|
||||
|
||||
if (parts > 1) {
|
||||
const items = Array.from({ length: parts }, (_, i) => {
|
||||
const slice = all.slice(i * maxUrls, (i + 1) * maxUrls)
|
||||
return { lastModified: newest(slice), url: `${url.origin}${url.pathname}?${SITEMAP_PART_PARAM}=${i + 1}` }
|
||||
})
|
||||
return new Response(buildSitemapIndexXml(items, { cssUrl }), { headers: xmlHeaders })
|
||||
}
|
||||
|
||||
// Empty usually means the database was unreachable — don't let a CDN keep it.
|
||||
const headers = all.length ? xmlHeaders : { ...xmlHeaders, 'Cache-Control': 'no-store' }
|
||||
return new Response(buildSitemapXml(all, { cssUrl }), { headers })
|
||||
} catch (err) {
|
||||
console.warn('[ipal] createSitemapRouteHandler: could not build sitemap:', err)
|
||||
// At runtime: 503 + Retry-After — crawlers come back later, while an empty
|
||||
// sitemap with 200 would tell them the site has no pages.
|
||||
if (process.env.NEXT_PHASE !== 'phase-production-build') {
|
||||
return new Response('Sitemap temporarily unavailable', {
|
||||
headers: { 'Cache-Control': 'no-store', 'Content-Type': 'text/plain; charset=utf-8', 'Retry-After': '300' },
|
||||
status: 503,
|
||||
})
|
||||
}
|
||||
// Valid empty urlset so the route doesn't 500 during a DB-less build.
|
||||
const empty =
|
||||
'<?xml version="1.0" encoding="UTF-8"?>\n' +
|
||||
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>'
|
||||
return new Response(empty, {
|
||||
headers: { 'Content-Type': 'application/xml; charset=utf-8' },
|
||||
// Never let a CDN keep the empty fallback.
|
||||
headers: { 'Cache-Control': 'no-store', 'Content-Type': 'application/xml; charset=utf-8' },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
import type { Field } from 'payload'
|
||||
|
||||
import type { AiBotRule, AiBotsPolicy, RobotsOptions } from './buildRobots.js'
|
||||
|
||||
/**
|
||||
* Site Settings → Search & AI: what editors set for search engines and AI
|
||||
* assistants without a deploy — Search Console / Bing verification codes, the
|
||||
* AI crawler policy for robots.txt, and a note for llms.txt. Empty fields
|
||||
* change nothing: verification tags appear only once a code is pasted, and the
|
||||
* robots policy stays the one set in code until an editor picks another.
|
||||
*/
|
||||
|
||||
export const SEARCH_VERIFICATION_FIELD = 'searchVerification'
|
||||
export const AI_CRAWLERS_FIELD = 'aiCrawlers'
|
||||
export const LLMS_INTRO_FIELD = 'llmsIntro'
|
||||
|
||||
/** Next `Metadata.verification` — site ownership tags for search consoles. */
|
||||
export type VerificationMetadata = {
|
||||
google?: string
|
||||
other?: Record<string, string>
|
||||
yandex?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Accepts the bare code or the whole tag an editor copies from Search Console
|
||||
* (`<meta name="google-site-verification" content="abc…" />`) and keeps only
|
||||
* the code. Anything that isn't a plain token is dropped — the value ends up
|
||||
* in every page's <head>.
|
||||
*/
|
||||
export function normalizeVerificationToken(raw: unknown): string {
|
||||
if (typeof raw !== 'string') {return ''}
|
||||
let value = raw.trim()
|
||||
const content = /content\s*=\s*["']([^"']*)["']/i.exec(value)
|
||||
if (content) {value = content[1].trim()}
|
||||
value = value.replace(/^["']|["']$/g, '')
|
||||
return /^[\w\-.:+/=]{1,200}$/.test(value) ? value : ''
|
||||
}
|
||||
|
||||
const tokenField = (name: string, label: string, description: string): Field => ({
|
||||
name,
|
||||
type: 'text',
|
||||
admin: { description },
|
||||
hooks: { beforeChange: [({ value }) => normalizeVerificationToken(value) || null] },
|
||||
label,
|
||||
})
|
||||
|
||||
const AI_POLICY_OPTIONS = [
|
||||
{ label: 'As set by the developer (default)', value: 'default' },
|
||||
{ label: 'Allow all AI assistants and AI training', value: 'allow' },
|
||||
{ label: 'Allow AI assistants and AI search, block AI training', value: 'block-training' },
|
||||
{ label: 'Block all known AI bots', value: 'disallow' },
|
||||
] as const
|
||||
|
||||
/** The "Search & AI" tab fields. Not localized, except the llms.txt note. */
|
||||
export const searchSettingsFields: Field[] = [
|
||||
{
|
||||
name: SEARCH_VERIFICATION_FIELD,
|
||||
type: 'group',
|
||||
admin: {
|
||||
description:
|
||||
'Proves to search engines that you own this site. Paste the code (or the whole <meta> tag) from the search engine; it is added to every page. Leave empty if you verify another way (DNS, file).',
|
||||
},
|
||||
fields: [
|
||||
tokenField('google', 'Google Search Console', 'Search Console → Settings → Ownership verification → HTML tag.'),
|
||||
tokenField('bing', 'Bing Webmaster Tools', 'Bing Webmaster Tools → Add site → HTML Meta Tag (msvalidate.01). Bing also powers ChatGPT Search and Copilot.'),
|
||||
tokenField('yandex', 'Yandex Webmaster', 'Yandex Webmaster → Site verification → Meta tag.'),
|
||||
],
|
||||
label: 'Search engine verification',
|
||||
},
|
||||
{
|
||||
name: AI_CRAWLERS_FIELD,
|
||||
type: 'group',
|
||||
admin: {
|
||||
description:
|
||||
'Which AI bots may read the site (robots.txt). Assistants (ClaudeBot, ChatGPT-User, PerplexityBot…) fetch pages to answer questions and cite you; training crawlers (GPTBot, Google-Extended, CCBot…) collect pages to train models. Blocking assistants removes the site from AI answers.',
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
name: 'policy',
|
||||
type: 'select',
|
||||
defaultValue: 'default',
|
||||
label: 'AI bots',
|
||||
options: AI_POLICY_OPTIONS.map((o) => ({ ...o })),
|
||||
},
|
||||
{
|
||||
name: 'rules',
|
||||
type: 'array',
|
||||
admin: {
|
||||
description:
|
||||
'Exceptions for single bots, by user agent exactly as the bot announces itself (e.g. GPTBot, Bytespider). Wins over the setting above.',
|
||||
initCollapsed: true,
|
||||
},
|
||||
fields: [
|
||||
{ name: 'userAgent', type: 'text', label: 'User agent', required: true },
|
||||
{
|
||||
name: 'access',
|
||||
type: 'select',
|
||||
defaultValue: 'disallow',
|
||||
options: [
|
||||
{ label: 'Allow', value: 'allow' },
|
||||
{ label: 'Block', value: 'disallow' },
|
||||
],
|
||||
required: true,
|
||||
},
|
||||
],
|
||||
label: 'Per-bot exceptions',
|
||||
},
|
||||
],
|
||||
label: 'AI crawlers',
|
||||
},
|
||||
{
|
||||
name: LLMS_INTRO_FIELD,
|
||||
type: 'textarea',
|
||||
admin: {
|
||||
description:
|
||||
'Shown at the top of /llms.txt, under the site description: key facts an AI assistant should know and may quote — what you do, where, for whom, since when. Plain sentences, no marketing slogans.',
|
||||
},
|
||||
label: 'About the site for AI assistants (llms.txt)',
|
||||
localized: true,
|
||||
},
|
||||
]
|
||||
|
||||
type SettingsLike = null | Record<string, unknown> | undefined
|
||||
|
||||
/** Site Settings → verification codes as Next `Metadata.verification`; undefined when none is set. */
|
||||
export function verificationFrom(settings: SettingsLike): undefined | VerificationMetadata {
|
||||
const group = settings?.[SEARCH_VERIFICATION_FIELD] as null | Record<string, unknown> | undefined
|
||||
if (!group || typeof group !== 'object') {return undefined}
|
||||
const google = normalizeVerificationToken(group.google)
|
||||
const bing = normalizeVerificationToken(group.bing)
|
||||
const yandex = normalizeVerificationToken(group.yandex)
|
||||
if (!google && !bing && !yandex) {return undefined}
|
||||
return {
|
||||
...(google ? { google } : {}),
|
||||
...(yandex ? { yandex } : {}),
|
||||
...(bing ? { other: { 'msvalidate.01': bing } } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
const POLICIES = new Set<string>(['allow', 'block-training', 'disallow'])
|
||||
|
||||
/**
|
||||
* Site Settings → AI crawlers as buildRobots options. Only what the editor
|
||||
* changed: policy 'default' keeps the option from code, no rules adds none.
|
||||
*/
|
||||
export function robotsOptionsFrom(settings: SettingsLike): Pick<RobotsOptions, 'aiBotRules' | 'aiBots'> {
|
||||
const group = settings?.[AI_CRAWLERS_FIELD] as { policy?: unknown; rules?: unknown } | null | undefined
|
||||
if (!group || typeof group !== 'object') {return {}}
|
||||
const policy = typeof group.policy === 'string' && POLICIES.has(group.policy) ? (group.policy as AiBotsPolicy) : undefined
|
||||
const rules: AiBotRule[] = Array.isArray(group.rules)
|
||||
? group.rules.flatMap((r: unknown) => {
|
||||
const row = r as { access?: unknown; userAgent?: unknown } | null
|
||||
// A user agent is one token — no spaces, colons or newlines that could
|
||||
// inject other robots.txt lines.
|
||||
const ua = typeof row?.userAgent === 'string' ? row.userAgent.trim() : ''
|
||||
if (!/^[\w\-.*/]{1,100}$/.test(ua)) {return []}
|
||||
return [{ access: row?.access === 'allow' ? ('allow' as const) : ('disallow' as const), userAgent: ua }]
|
||||
})
|
||||
: []
|
||||
return {
|
||||
...(policy ? { aiBots: policy } : {}),
|
||||
...(rules.length ? { aiBotRules: rules } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
/** Site Settings → llms.txt note in the locale it was read in. Empty string when unset. */
|
||||
export function llmsIntroFrom(settings: SettingsLike): string {
|
||||
const v = settings?.[LLMS_INTRO_FIELD]
|
||||
return typeof v === 'string' ? v.trim() : ''
|
||||
}
|
||||
@@ -38,7 +38,12 @@ export type CollectSiteIndexArgs = {
|
||||
content?: ContentOption
|
||||
/** Population depth of `doc`. Default 0 (1 when you render blocks with images). */
|
||||
depth?: number
|
||||
/** Max documents per collection and locale. Default 1000. */
|
||||
/**
|
||||
* 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[]
|
||||
@@ -80,6 +85,33 @@ function slugMap(rel: unknown, locales: string[]): Record<string, string> | unde
|
||||
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
|
||||
@@ -95,7 +127,8 @@ export async function collectSiteIndex({
|
||||
config,
|
||||
content,
|
||||
depth = 0,
|
||||
limit = 1000,
|
||||
include,
|
||||
limit,
|
||||
locales,
|
||||
pagesSlug = 'pages',
|
||||
payload,
|
||||
@@ -127,8 +160,7 @@ export async function collectSiteIndex({
|
||||
if (collection !== pagesSlug && !prefix?.[locale]) {continue}
|
||||
let docs: Row[] = []
|
||||
try {
|
||||
const res = await payload.find({ collection: collection as never, depth, limit, locale: locale as never })
|
||||
docs = (res?.docs ?? []) as Row[]
|
||||
docs = await readDocs(payload, collection, { depth, limit, locale })
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
@@ -142,7 +174,7 @@ export async function collectSiteIndex({
|
||||
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) {continue}
|
||||
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
|
||||
|
||||
@@ -46,28 +46,28 @@ export function buildSitemapCss({ accent, credit, title }: SitemapStyleOptions =
|
||||
--badge-bg: #1a1c26; --badge-border: #282b3d; --badge-text: #9ca3af;
|
||||
}
|
||||
}
|
||||
urlset {
|
||||
urlset, sitemapindex {
|
||||
display: flex; flex-direction: column; box-sizing: border-box; min-height: 100vh;
|
||||
max-width: 1040px; margin: 0 auto; padding: 3rem 1.5rem; line-height: 1.5;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Inter, Helvetica, Arial, sans-serif;
|
||||
background-color: var(--bg); color: var(--text-main);
|
||||
}
|
||||
urlset::before {
|
||||
urlset::before, sitemapindex::before {
|
||||
content: ${cssString(heading)};
|
||||
display: block; order: -2; font-size: 1.35rem; font-weight: 600; letter-spacing: -0.02em;
|
||||
color: var(--text-main); ${note ? 'padding-bottom: 0.4rem;' : divider}
|
||||
}
|
||||
${note ? `urlset::after {
|
||||
${note ? `urlset::after, sitemapindex::after {
|
||||
content: ${cssString(note)};
|
||||
display: block; order: -1; font-size: 0.8rem; color: var(--text-muted); ${divider}
|
||||
}
|
||||
` : ''}url {
|
||||
` : ''}url, sitemap {
|
||||
display: block; width: 100%; order: 0; box-sizing: border-box;
|
||||
background-color: var(--card); border: 1px solid var(--border); border-radius: 8px;
|
||||
padding: 1rem 1.25rem; margin-bottom: 0.65rem;
|
||||
transition: border-color 0.15s ease, box-shadow 0.15s ease;
|
||||
}
|
||||
url:hover { border-color: var(--accent); box-shadow: 0 2px 6px rgba(0, 0, 0, 0.03); }
|
||||
url:hover, sitemap:hover { border-color: var(--accent); box-shadow: 0 2px 6px rgba(0, 0, 0, 0.03); }
|
||||
loc {
|
||||
display: block; margin-bottom: 0.45rem; word-break: break-all; line-height: 1.45;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;
|
||||
|
||||
@@ -36,6 +36,12 @@ export type SeoOption = {
|
||||
generateDescription?: (args: { doc: Record<string, unknown> }) => string
|
||||
/** Optional: customize how meta titles are generated in the admin preview. */
|
||||
generateTitle?: (args: { doc: Record<string, unknown> }) => string
|
||||
/**
|
||||
* Site Settings → "Search & AI" tab: Search Console / Bing / Yandex
|
||||
* verification, AI crawler policy for robots.txt (getRobots), llms.txt note.
|
||||
* On by default (empty fields change nothing); false removes the tab.
|
||||
*/
|
||||
searchSettings?: false
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user