feat: v1.7.0 — AI-readability suite, form engine & boilerplate helpers
AI / GEO: - feat(content): lexicalToMarkdown, blocksToMarkdown, createMarkdownRenderer (+markdownResponse) — per-page Markdown for AI agents - feat(content): markdown content negotiation + discovery (prefersMarkdown, markdownHref) - feat(seo): buildRobots aiBots policy (allow/block-training/disallow) - feat(seo): llms-full.txt mode in buildLlmsTxt/createLlmsTxtRoute - feat(mcp): createMcpRoute — read-only MCP server (search_content, get_page) - feat(content): searchContent + createSearchRoute — shared JSON search - feat(seo): buildSpeakableJsonLd + buildSummaryField (aiSummary, auto-fill) Forms: - feat(forms): useForm/useContactForm + validators (logic-only, no markup) - feat(forms): honeypot anti-spam (honeypotInputProps, isHoneypotTripped) Helpers / hardening: - feat(i18n): resolveLocalized — replaces ad-hoc getSafeString - feat(hooks): buildCrossLocaleFieldSync — locales from config, no hardcoded list - feat(seo): buildNoindexField — checkbox → meta.noindex, no - feat(content): resolveRedirect — 301/308 from slugHistory - feat(env): assertEnv + ipalEnvRules — fail-fast env validation - feat(consent): ConsentScript — load third-party only after consent - feat(health): createHealthRoute — Coolify/Docker DB liveness Fixes: - fix(seo): wrap getCachedPayload in try/catch in createManifestHandler (Docker/CI build no longer crashes when DB unreachable) docs: migration.md (20 sections), new env.md/mcp.md, updated agents.md, AGENTS-TEMPLATE.md, forms/hooks/content/seo/consent/deployment/richtext
This commit is contained in:
@@ -0,0 +1,132 @@
|
||||
// Import the leaf, not the richtext barrel — the barrel re-exports
|
||||
// RenderRichText (a React component), which would pull React into this pure,
|
||||
// server-usable module.
|
||||
import { lexicalToMarkdown } from '../richtext/lexicalToMarkdown.js'
|
||||
|
||||
/**
|
||||
* Converts a page's `blocks` layout to Markdown by CONVENTION — the same field
|
||||
* names the project already standardises on (heading, subheading, body,
|
||||
* content, image, items/faq/…; see the naming rules in agents.md). The plugin
|
||||
* can't know each project's block shapes, but it CAN rely on those conventions,
|
||||
* so most blocks convert with zero per-project wiring. Special blocks get an
|
||||
* `overrides` entry keyed by blockType.
|
||||
*
|
||||
* Output is for AI/agent consumption (per-page Markdown, llms-full.txt), not
|
||||
* on-page rendering — it extracts readable text, not pixel-perfect layout.
|
||||
*
|
||||
* blocksToMarkdown(page.layout)
|
||||
* blocksToMarkdown(page.layout, {
|
||||
* overrides: { gallery: (b) => `(${(b.images as unknown[])?.length ?? 0} photos)` },
|
||||
* })
|
||||
*/
|
||||
|
||||
type Block = Record<string, unknown> & { blockType?: string }
|
||||
type BlockToMarkdown = (block: Block) => string
|
||||
|
||||
type BlocksToMarkdownArgs = {
|
||||
/** Per-blockType custom renderers. Return '' to omit a block. */
|
||||
overrides?: Record<string, BlockToMarkdown>
|
||||
}
|
||||
|
||||
const HEADING_KEYS = new Set(['heading', 'title'])
|
||||
const SUBHEADING_KEYS = new Set(['subheading', 'subtitle'])
|
||||
const QUESTION_KEYS = new Set(['question'])
|
||||
const TEXT_KEYS = new Set([
|
||||
'body',
|
||||
'text',
|
||||
'description',
|
||||
'excerpt',
|
||||
'summary',
|
||||
'answer',
|
||||
'caption',
|
||||
'label',
|
||||
'content',
|
||||
])
|
||||
const ARRAY_KEYS = new Set([
|
||||
'items',
|
||||
'features',
|
||||
'faq',
|
||||
'faqs',
|
||||
'cards',
|
||||
'columns',
|
||||
'rows',
|
||||
'questions',
|
||||
'services',
|
||||
'steps',
|
||||
'points',
|
||||
'benefits',
|
||||
'list',
|
||||
])
|
||||
|
||||
/** A populated richText value is an object with a `root`. */
|
||||
function isRichText(v: unknown): boolean {
|
||||
return !!v && typeof v === 'object' && 'root' in (v as Record<string, unknown>)
|
||||
}
|
||||
|
||||
/** A populated upload (image) is an object with a `url`. */
|
||||
function imageMarkdown(v: unknown): string {
|
||||
if (!v || typeof v !== 'object') return ''
|
||||
const o = v as Record<string, unknown>
|
||||
const url = typeof o.url === 'string' ? o.url : ''
|
||||
const alt = typeof o.alt === 'string' ? o.alt : ''
|
||||
return url ? `` : ''
|
||||
}
|
||||
|
||||
/** Extract readable Markdown from one block's known content fields. */
|
||||
function extractBlock(block: Block, depth: number): string {
|
||||
const lines: string[] = []
|
||||
|
||||
for (const [key, value] of Object.entries(block)) {
|
||||
if (value == null) continue
|
||||
|
||||
if (HEADING_KEYS.has(key) && typeof value === 'string' && value.trim()) {
|
||||
lines.push(`## ${value.trim()}`)
|
||||
} else if (SUBHEADING_KEYS.has(key) && typeof value === 'string' && value.trim()) {
|
||||
lines.push(`### ${value.trim()}`)
|
||||
} else if (QUESTION_KEYS.has(key) && typeof value === 'string' && value.trim()) {
|
||||
lines.push(`**${value.trim()}**`)
|
||||
} else if (key === 'image') {
|
||||
const img = imageMarkdown(value)
|
||||
if (img) lines.push(img)
|
||||
} else if (isRichText(value)) {
|
||||
const md = lexicalToMarkdown(value as never)
|
||||
if (md) lines.push(md)
|
||||
} else if (TEXT_KEYS.has(key) && typeof value === 'string' && value.trim()) {
|
||||
lines.push(value.trim())
|
||||
} else if (ARRAY_KEYS.has(key) && Array.isArray(value) && depth < 4) {
|
||||
for (const item of value) {
|
||||
if (item && typeof item === 'object') {
|
||||
const sub = extractBlock(item as Block, depth + 1)
|
||||
if (sub.trim()) lines.push(sub)
|
||||
} else if (typeof item === 'string' && item.trim()) {
|
||||
lines.push(`- ${item.trim()}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return lines.join('\n\n')
|
||||
}
|
||||
|
||||
export function blocksToMarkdown(layout: unknown, args: BlocksToMarkdownArgs = {}): string {
|
||||
if (!Array.isArray(layout)) return ''
|
||||
const { overrides = {} } = args
|
||||
const out: string[] = []
|
||||
|
||||
for (const block of layout) {
|
||||
if (!block || typeof block !== 'object') continue
|
||||
const b = block as Block
|
||||
const type = typeof b.blockType === 'string' ? b.blockType : ''
|
||||
|
||||
if (type && overrides[type]) {
|
||||
const md = overrides[type](b)
|
||||
if (md.trim()) out.push(md.trim())
|
||||
continue
|
||||
}
|
||||
|
||||
const md = extractBlock(b, 0)
|
||||
if (md.trim()) out.push(md.trim())
|
||||
}
|
||||
|
||||
return out.join('\n\n').trim()
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import type { BasePayload } from 'payload'
|
||||
|
||||
import type { ContentOption } from './types.js'
|
||||
|
||||
import { blocksToMarkdown } from './blocksToMarkdown.js'
|
||||
import { resolveRoute } from './resolveRoute.js'
|
||||
|
||||
type CreateMarkdownRendererArgs = {
|
||||
/** Pages collection. Default 'pages'. */
|
||||
collection?: string
|
||||
/** Archive-backed collections, same value as the plugin option (optional). */
|
||||
content?: ContentOption
|
||||
/** Prepend a YAML frontmatter block (title/description/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
|
||||
}
|
||||
|
||||
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 {
|
||||
collection = 'pages',
|
||||
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)}`)}
|
||||
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): 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',
|
||||
},
|
||||
status: 200,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import type { BasePayload } from 'payload'
|
||||
|
||||
import type { I18nConfig } from '../i18n/index.js'
|
||||
|
||||
import { searchContent } from './searchContent.js'
|
||||
|
||||
type CreateSearchRouteArgs = {
|
||||
/** Absolute origin to prefix result URLs with. */
|
||||
baseUrl?: string
|
||||
/** Pages collection. Default 'pages'. */
|
||||
collection?: string
|
||||
config: I18nConfig
|
||||
/** Default result cap when ?limit is absent. Default 10. */
|
||||
defaultLimit?: number
|
||||
getCachedPayload: () => Promise<BasePayload>
|
||||
/** Home slug map/string so the home result collapses to root. */
|
||||
homeSlug?: Record<string, string> | string
|
||||
/** Field holding a richer AI summary (buildSummaryField) to prefer as description. */
|
||||
summaryField?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* A JSON content-search endpoint. Powers both the site's own search UI and
|
||||
* external agents — one ranking, one source of truth (shares searchContent with
|
||||
* the MCP server's search_content tool).
|
||||
*
|
||||
* // app/api/search/route.ts
|
||||
* import { createSearchRoute } from '@intecion/ipal-kit'
|
||||
* import { getCachedPayload } from '@/lib/content'
|
||||
* import { i18nConfig } from '@/i18n.config'
|
||||
* export const dynamic = 'force-dynamic'
|
||||
* export const GET = createSearchRoute({ getCachedPayload, config: i18nConfig,
|
||||
* baseUrl: process.env.NEXT_PUBLIC_SERVER_URL! })
|
||||
*
|
||||
* Query params: `q` (required), `locale`, `limit`. Response:
|
||||
* { query, locale, count, results: [{ title, url, description?, slug }] }
|
||||
*
|
||||
* Uses the global Request/Response — no next/server import.
|
||||
*/
|
||||
export function createSearchRoute(
|
||||
args: CreateSearchRouteArgs,
|
||||
): (req: Request) => Promise<Response> {
|
||||
const {
|
||||
baseUrl,
|
||||
collection = 'pages',
|
||||
config,
|
||||
defaultLimit = 10,
|
||||
getCachedPayload,
|
||||
homeSlug,
|
||||
summaryField,
|
||||
} = args
|
||||
|
||||
return async (req: Request) => {
|
||||
const url = new URL(req.url)
|
||||
const query = url.searchParams.get('q')?.trim() ?? ''
|
||||
const locale = url.searchParams.get('locale') ?? undefined
|
||||
const limitParam = url.searchParams.get('limit')
|
||||
const limit = limitParam ? Number(limitParam) : defaultLimit
|
||||
|
||||
if (!query) {
|
||||
return Response.json(
|
||||
{ count: 0, error: 'Missing ?q', query: '', results: [] },
|
||||
{ headers: { 'cache-control': 'no-store' }, status: 400 },
|
||||
)
|
||||
}
|
||||
|
||||
try {
|
||||
const payload = await getCachedPayload()
|
||||
const results = await searchContent({
|
||||
baseUrl,
|
||||
collection,
|
||||
config,
|
||||
homeSlug,
|
||||
limit,
|
||||
locale,
|
||||
payload,
|
||||
query,
|
||||
summaryField,
|
||||
})
|
||||
return Response.json(
|
||||
{ count: results.length, locale: locale ?? config.defaultLocale, query, results },
|
||||
{
|
||||
headers: {
|
||||
'cache-control': 'public, max-age=0, s-maxage=60, stale-while-revalidate=600',
|
||||
},
|
||||
},
|
||||
)
|
||||
} catch (err) {
|
||||
// DB unreachable (build) or unexpected — empty result rather than 500.
|
||||
console.warn('[ipal] createSearchRoute: search failed:', err)
|
||||
return Response.json(
|
||||
{ count: 0, query, results: [] },
|
||||
{ headers: { 'cache-control': 'no-store' }, status: 200 },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,15 @@
|
||||
export { buildArchiveFields } from './archiveFields.js'
|
||||
export { blocksToMarkdown } from './blocksToMarkdown.js'
|
||||
export { createMarkdownRenderer, markdownResponse } from './createMarkdownRenderer.js'
|
||||
export { createSearchRoute } from './createSearchRoute.js'
|
||||
export { getArchiveEntries } from './getArchiveEntries.js'
|
||||
export type { ArchiveEntries } from './getArchiveEntries.js'
|
||||
export { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegotiation.js'
|
||||
export { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js'
|
||||
export { resolveRedirect } from './resolveRedirect.js'
|
||||
export { resolveRoute } from './resolveRoute.js'
|
||||
export type { ResolvedRoute } from './resolveRoute.js'
|
||||
export { searchContent } from './searchContent.js'
|
||||
export type { SearchResult } from './searchContent.js'
|
||||
export type { ContentCollectionOption, ContentOption } from './types.js'
|
||||
export { archiveFieldName } from './types.js'
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Helpers for making the per-page Markdown (createMarkdownRenderer) discoverable
|
||||
* and negotiable, so AI agents reliably find and read it.
|
||||
*
|
||||
* Two mechanisms:
|
||||
* - `markdownHref` — the `<link rel="alternate" type="text/markdown">` href a
|
||||
* page advertises, so an agent fetching the HTML sees there's a Markdown
|
||||
* version and can switch to it.
|
||||
* - `prefersMarkdown` — reads the Accept header, so the same URL can serve
|
||||
* Markdown when asked (content negotiation via a proxy rewrite).
|
||||
*/
|
||||
|
||||
/** Default URL prefix the Markdown route is mounted at (see createMarkdownRenderer). */
|
||||
export const MARKDOWN_PREFIX = '/md'
|
||||
|
||||
/**
|
||||
* The Markdown URL for a given page path. Keeps the `/md` prefix in ONE place so
|
||||
* the discovery link and the route agree.
|
||||
*
|
||||
* markdownHref('/pl/o-nas') // '/md/pl/o-nas'
|
||||
* markdownHref('/pl/o-nas', '/ai') // '/ai/pl/o-nas'
|
||||
*
|
||||
* Advertise it from Next metadata so every page's <head> points to its Markdown:
|
||||
*
|
||||
* // generateMetadata
|
||||
* return { ...meta, alternates: { ...meta.alternates, types: { 'text/markdown': markdownHref(path) } } }
|
||||
*/
|
||||
export function markdownHref(pathname: string, prefix: string = MARKDOWN_PREFIX): string {
|
||||
const clean = pathname.startsWith('/') ? pathname : `/${pathname}`
|
||||
const p = prefix.replace(/\/$/, '')
|
||||
return `${p}${clean === '/' ? '' : clean}` || p
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the client asked for Markdown via the Accept header (q-values
|
||||
* respected: a higher-weighted text/html wins). Accepts a header string, a
|
||||
* Headers object, or a Request. Use it in proxy.ts to serve the same URL as
|
||||
* Markdown when an agent negotiates for it:
|
||||
*
|
||||
* // proxy.ts
|
||||
* if (prefersMarkdown(request)) {
|
||||
* return NextResponse.rewrite(new URL(markdownHref(request.nextUrl.pathname), request.url))
|
||||
* }
|
||||
*/
|
||||
export function prefersMarkdown(input: Headers | null | Request | string | undefined): boolean {
|
||||
let accept: null | string = null
|
||||
if (!input) {return false}
|
||||
if (typeof input === 'string') {accept = input}
|
||||
else if (input instanceof Headers) {accept = input.get('accept')}
|
||||
else if ('headers' in input && input.headers) {accept = input.headers.get('accept')}
|
||||
if (!accept) {return false}
|
||||
|
||||
// Parse "type/subtype;q=0.8" entries into {type, q}.
|
||||
const entries = accept.split(',').map((part) => {
|
||||
const [type, ...params] = part.trim().split(';')
|
||||
const qParam = params.find((p) => p.trim().startsWith('q='))
|
||||
const q = qParam ? Number(qParam.split('=')[1]) : 1
|
||||
return { type: type.trim().toLowerCase(), q: Number.isFinite(q) ? q : 1 }
|
||||
})
|
||||
|
||||
const md = entries.find((e) => e.type === 'text/markdown')
|
||||
if (!md) {return false}
|
||||
// Markdown must be at least as preferred as html (and html not strictly higher).
|
||||
const html = entries.find((e) => e.type === 'text/html')
|
||||
return !html || md.q >= html.q
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import type { BasePayload } from 'payload'
|
||||
|
||||
import type { I18nConfig } from '../i18n/index.js'
|
||||
|
||||
import { buildLocalizedPath, getDefaultLocale, isValidLocale } from '../i18n/index.js'
|
||||
|
||||
export type SearchResult = {
|
||||
description?: string
|
||||
slug: string
|
||||
title: string
|
||||
/** Locale-aware path, prefixed with baseUrl when given. */
|
||||
url: string
|
||||
}
|
||||
|
||||
type SearchContentArgs = {
|
||||
/** Absolute origin to prefix URLs with. Omit for relative paths. */
|
||||
baseUrl?: string
|
||||
/** Pages collection. Default 'pages'. */
|
||||
collection?: string
|
||||
config: I18nConfig
|
||||
/** Home slug map/string so the home result collapses to root. */
|
||||
homeSlug?: Record<string, string> | string
|
||||
/** Max results. Default 10, clamped 1–50. */
|
||||
limit?: number
|
||||
/** Locale to search/return. Defaults to config.defaultLocale; invalid → default. */
|
||||
locale?: string
|
||||
payload: BasePayload
|
||||
/** Keywords. */
|
||||
query: string
|
||||
/**
|
||||
* Field holding a richer AI summary (see buildSummaryField). When set and
|
||||
* present on a doc, it's preferred over meta.description for the result's
|
||||
* description.
|
||||
*/
|
||||
summaryField?: string
|
||||
}
|
||||
|
||||
type PageRow = {
|
||||
[key: string]: unknown
|
||||
_status?: string
|
||||
id: number | string
|
||||
meta?: { description?: unknown; noindex?: boolean } | null
|
||||
slug?: unknown
|
||||
title?: unknown
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared content search: title / meta-description keyword match over a
|
||||
* collection, returning structured results (published, non-noindex only). One
|
||||
* implementation behind BOTH the JSON search route (createSearchRoute) and the
|
||||
* MCP server's search_content tool — so site search, API and AI all rank the
|
||||
* same way.
|
||||
*
|
||||
* Degrades to [] (never throws) when the collection's fields aren't queryable —
|
||||
* same guard class as the drafts/_status lesson.
|
||||
*/
|
||||
export async function searchContent({
|
||||
baseUrl,
|
||||
collection = 'pages',
|
||||
config,
|
||||
homeSlug,
|
||||
limit = 10,
|
||||
locale,
|
||||
payload,
|
||||
query,
|
||||
summaryField,
|
||||
}: SearchContentArgs): Promise<SearchResult[]> {
|
||||
const q = query.trim()
|
||||
if (!q) {return []}
|
||||
|
||||
const loc = locale && isValidLocale(locale, config) ? locale : getDefaultLocale(config)
|
||||
const max = Math.min(Math.max(Math.trunc(limit) || 10, 1), 50)
|
||||
const origin = baseUrl?.replace(/\/$/, '') ?? ''
|
||||
|
||||
let docs: PageRow[] = []
|
||||
try {
|
||||
const res = await payload.find({
|
||||
collection: collection as never,
|
||||
depth: 0,
|
||||
limit: max * 3, // over-fetch; drafts/noindex filtered in memory
|
||||
locale: loc as never,
|
||||
where: {
|
||||
or: [{ title: { like: q } }, { 'meta.description': { like: q } }],
|
||||
} as never,
|
||||
})
|
||||
docs = (res?.docs ?? []) as PageRow[]
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
|
||||
const results: SearchResult[] = []
|
||||
for (const doc of docs) {
|
||||
if (doc._status && doc._status !== 'published') {continue}
|
||||
if (doc.meta?.noindex) {continue}
|
||||
const title = typeof doc.title === 'string' ? doc.title : undefined
|
||||
const slug = typeof doc.slug === 'string' ? doc.slug : undefined
|
||||
if (!title || !slug) {continue}
|
||||
const path = buildLocalizedPath({ config, homeSlug, locale: loc, slugs: { [loc]: slug } })
|
||||
// Prefer the richer AI summary when configured and present, else meta.description.
|
||||
const summary =
|
||||
summaryField && typeof doc[summaryField] === 'string'
|
||||
? (doc[summaryField])
|
||||
: undefined
|
||||
const description =
|
||||
summary?.trim() ||
|
||||
(typeof doc.meta?.description === 'string' ? doc.meta.description : undefined)
|
||||
results.push({
|
||||
slug,
|
||||
title,
|
||||
url: `${origin}${path ?? `/${slug}`}`,
|
||||
...(description ? { description } : {}),
|
||||
})
|
||||
if (results.length >= max) {break}
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
Reference in New Issue
Block a user