import type { BasePayload } from 'payload' import type { I18nConfig } from '../i18n/index.js' import type { ClientIpOptions } from '../shared/rateLimit.js' import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js' import { searchContent } from './searchContent.js' type CreateSearchRouteArgs = { /** Absolute origin to prefix result URLs with. */ baseUrl?: string /** How to read the client IP for the rate limit — see clientIp(). */ clientIp?: ClientIpOptions /** Pages collection. Default 'pages'. */ collection?: string config: I18nConfig /** Default result cap when ?limit is absent. Default 10. */ defaultLimit?: number getCachedPayload: () => Promise /** Home slug map/string so the home result collapses to root. */ homeSlug?: Record | string /** * Per-IP limit (in memory per instance, or the store from setRateLimitStore). Default { max: 120, windowMs: 60_000 }. * `false` = off (a limiter in front, e.g. Cloudflare WAF rate limiting). */ rateLimit?: { max?: number; windowMs?: number } | false /** 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 { const { baseUrl, collection = 'pages', config, defaultLimit = 10, getCachedPayload, homeSlug, summaryField } = args // 120/min: a debounced search-as-you-type box stays well under it; a scraper doesn't. const rl = args.rateLimit === false ? null : { max: 120, windowMs: 60_000, ...args.rateLimit } return async (req: Request) => { if (rl) { const limit = await consumeRateLimit({ key: clientIp(req, args.clientIp), scope: 'search', ...rl }) if (!limit.ok) { return tooManyRequests(limit.retryAfter, { count: 0, error: 'Too many requests', query: '', results: [] }) } } 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 }, ) } } }