Files
ipal-kit/test/seoSearch.test.ts
Radosław SmolińskiandClaude Fable 5.2 0a4f001797 IAPL rename, scripted: preferred names in src, bin, scripts, services, tests; bin files and skill folders moved
Replaced by an explicit list of forms only (ten exported names, runtime env names, project file
names and marks, commands, skill names, the log prefix, the brand in prose). Package name, import
paths, routes, CSS tokens, data attributes, custom keys, context flags, the cookie and kv keys are
not touched. package.json keeps the five old bin names beside the five new ones.
The old names stop working in this commit and come back as aliases in the next; docs follow.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 17:24:21 +01:00

356 lines
17 KiB
TypeScript

import type { Config } from 'payload'
import { afterEach, describe, expect, test, vi } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import type { SitemapEntry } from '../src/modules/seo/buildSitemapEntries.js'
import { buildLlmsTxt } from '../src/modules/seo/buildLlmsTxt.js'
import { buildMetadata } from '../src/modules/seo/buildMetadata.js'
import { AI_TRAINING_BOTS, buildRobots } from '../src/modules/seo/buildRobots.js'
import { buildSitemapEntries } from '../src/modules/seo/buildSitemapEntries.js'
import { buildSitemapIndexXml } from '../src/modules/seo/buildSitemapXml.js'
import { createPageMetadata } from '../src/modules/seo/createPageMetadata.js'
import { createLlmsTxtRoute, createSitemapRouteHandler, DEFAULT_SITEMAP_CACHE_CONTROL } from '../src/modules/seo/routeHandlers.js'
import { llmsIntroFrom, normalizeVerificationToken, robotsOptionsFrom, verificationFrom } from '../src/modules/seo/searchSettings.js'
import { collectSiteIndex } from '../src/modules/seo/siteIndex.js'
import { iapl } from '../src/plugin.js'
const config: I18nConfig = {
defaultLocale: 'pl',
locales: [
{ code: 'pl', label: 'Polski' },
{ code: 'en', label: 'English' },
],
}
const single: I18nConfig = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }
type Rule = { allow?: string; disallow?: string[]; userAgent: string | string[] }
afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllEnvs()
})
describe('search verification (Site settings → Search engines)', () => {
test('keeps the code from a bare value or a pasted <meta> tag', () => {
expect(normalizeVerificationToken(' abc-123_XYZ ')).toBe('abc-123_XYZ')
expect(normalizeVerificationToken('<meta name="google-site-verification" content="Tok_9-x" />')).toBe('Tok_9-x')
expect(normalizeVerificationToken("<meta name='msvalidate.01' content='ABCDEF0123' />")).toBe('ABCDEF0123')
})
test('drops anything that is not a plain token', () => {
expect(normalizeVerificationToken('"><script>alert(1)</script>')).toBe('')
expect(normalizeVerificationToken('two words')).toBe('')
expect(normalizeVerificationToken(42)).toBe('')
})
test('maps to Next Metadata.verification; empty group → undefined', () => {
expect(verificationFrom({ searchVerification: { bing: 'B1', google: 'G1', yandex: null } })).toEqual({
google: 'G1',
other: { 'msvalidate.01': 'B1' },
})
expect(verificationFrom({ searchVerification: { bing: '', google: null } })).toBeUndefined()
expect(verificationFrom({})).toBeUndefined()
})
test('every page gets the tags from Site Settings', async () => {
const pageMetadata = createPageMetadata({
baseUrl: 'https://acme.pl',
config,
loaders: {
getSettings: async () => ({ homepage: null, searchVerification: { google: 'G1' }, siteName: 'Acme' }),
resolveRoute: async () => null,
},
})
const metadata = await pageMetadata({ slug: ['x'], locale: 'pl', payload: {} as never })
expect(metadata.verification).toEqual({ google: 'G1' })
})
test('an unknown route is noindex', async () => {
const pageMetadata = createPageMetadata({
config,
loaders: { getSettings: async () => ({ homepage: null, siteName: 'Acme' }), resolveRoute: async () => null },
})
const metadata = await pageMetadata({ slug: ['nope'], locale: 'pl', payload: {} as never })
expect(metadata.robots?.index).toBe(false)
})
test('no verification → no key in metadata', () => {
const m = buildMetadata({ config, locale: 'pl', slugs: { pl: 'a' } })
expect('verification' in m).toBe(false)
})
})
describe('AI crawlers (robots)', () => {
test('panel policy and exceptions become buildRobots options; "default" changes nothing', () => {
expect(robotsOptionsFrom({ aiCrawlers: { policy: 'default', rules: [] } })).toEqual({})
expect(
robotsOptionsFrom({
aiCrawlers: {
policy: 'block-training',
rules: [
{ access: 'allow', userAgent: ' GPTBot ' },
{ access: 'disallow', userAgent: 'Evil\nDisallow: /' },
{ access: 'disallow', userAgent: 'Bad Bot' },
],
},
}),
).toEqual({ aiBotRules: [{ access: 'allow', userAgent: 'GPTBot' }], aiBots: 'block-training' })
})
test('an exception takes the bot out of its policy group', () => {
const rules = buildRobots({
aiBotRules: [
{ access: 'allow', userAgent: 'gptbot' },
{ access: 'disallow', userAgent: 'SomeNewBot' },
],
aiBots: 'block-training',
baseUrl: 'https://acme.pl',
}).rules as Rule[]
const training = rules.find((r) => Array.isArray(r.userAgent) && r.userAgent.includes(AI_TRAINING_BOTS[1]))
expect(training?.disallow).toEqual(['/'])
expect(training?.userAgent).not.toContain('GPTBot')
expect(rules).toContainEqual({ allow: '/', disallow: ['/admin', '/api'], userAgent: ['gptbot'] })
expect(rules).toContainEqual({ disallow: ['/'], userAgent: ['SomeNewBot'] })
})
test('exceptions still apply with aiBots: false', () => {
const rules = buildRobots({ aiBotRules: [{ access: 'disallow', userAgent: 'Bytespider' }], aiBots: false, baseUrl: 'https://acme.pl' })
.rules as Rule[]
expect(rules).toHaveLength(2)
expect(rules[1]).toEqual({ disallow: ['/'], userAgent: ['Bytespider'] })
})
test('IAPL_NOINDEX still wins over every exception', () => {
vi.stubEnv('IAPL_NOINDEX', '1')
const r = buildRobots({ aiBotRules: [{ access: 'allow', userAgent: 'GPTBot' }], baseUrl: 'https://acme.pl' })
expect(r.rules).toEqual({ disallow: ['/'], userAgent: '*' })
})
})
/** Payload stub: `docs` per collection, served in pages of the requested limit. */
function fakePayload(docs: Record<string, Record<string, unknown>[]>, opts: { drafts?: string[]; fields?: string[] } = {}) {
const find = vi.fn(async ({ collection, limit, page = 1 }: { collection: string; limit: number; page?: number }) => {
const all = docs[collection] ?? []
const start = (page - 1) * limit
return { docs: all.slice(start, start + limit), hasNextPage: start + limit < all.length }
})
const collections = Object.fromEntries(
Object.keys(docs).map((slug) => [
slug,
{
config: {
flattenedFields: (opts.fields ?? ['slug', 'title', 'meta']).map((name) => ({ name })),
labels: { plural: slug },
versions: opts.drafts?.includes(slug) ? { drafts: true } : false,
},
},
]),
)
return { collections, find, findGlobal: vi.fn(async () => ({})) }
}
describe('buildSitemapEntries at scale', () => {
const pages = Array.from({ length: 1203 }, (_, i) => ({
id: i,
slug: { en: `p${i}`, pl: `s${i}` },
_status: 'published',
updatedAt: '2026-01-01T00:00:00.000Z',
}))
test('reads in batches, published only, selected fields', async () => {
const payload = fakePayload({ pages }, { drafts: ['pages'], fields: ['slug', 'title', 'meta', 'noindex', 'layout'] })
const entries = await buildSitemapEntries({ baseUrl: 'https://acme.pl', config, payload: payload as never })
expect(entries).toHaveLength(1203 * 2)
expect(payload.find).toHaveBeenCalledTimes(3)
const args = payload.find.mock.calls[0][0] as unknown as Record<string, unknown>
expect(args.limit).toBe(500)
expect(args.where).toEqual({ _status: { equals: 'published' } })
expect(args.select).toEqual({ slug: true, _status: true, meta: true, noindex: true, updatedAt: true })
})
test('the page assigned as the 404 in System pages is left out, whatever its slug', async () => {
const payload = fakePayload({ pages: pages.slice(0, 3) })
payload.findGlobal.mockImplementation(async () => ({ notFound: { id: 1 } }))
const entries = await buildSitemapEntries({ baseUrl: 'https://acme.pl', config, payload: payload as never })
expect(entries.map((e) => e.url).some((u) => /\/s1$|\/p1$/.test(u))).toBe(false)
expect(entries).toHaveLength(2 * 2)
})
test('custom images → whole documents (no select)', async () => {
const payload = fakePayload({ pages: pages.slice(0, 2) })
await buildSitemapEntries({ baseUrl: 'https://acme.pl', config, images: () => [], payload: payload as never })
const args = payload.find.mock.calls[0][0] as unknown as Record<string, unknown>
expect(args.select).toBeUndefined()
expect(args.where).toBeUndefined()
})
})
describe('sitemap route: split, cache, errors', () => {
const make = (n: number): SitemapEntry[] =>
Array.from({ length: n }, (_, i) => ({ lastModified: `2026-01-${String((i % 28) + 1).padStart(2, '0')}T00:00:00.000Z`, url: `https://acme.pl/p${i}` }))
test('small site: one urlset with the default Cache-Control', async () => {
const res = await createSitemapRouteHandler(async () => make(3), { style: false })(new Request('https://acme.pl/sitemap.xml'))
expect(res.headers.get('cache-control')).toBe(DEFAULT_SITEMAP_CACHE_CONTROL)
const xml = await res.text()
expect(xml).toContain('<urlset')
expect(xml.match(/<url>/g)).toHaveLength(3)
})
test('over maxUrls: an index, parts by ?part=N, unknown part 404', async () => {
const handler = createSitemapRouteHandler(async () => make(5), { maxUrls: 2, style: false })
const index = await (await handler(new Request('https://acme.pl/sitemap.xml'))).text()
expect(index).toContain('<sitemapindex')
expect(index.match(/<sitemap>/g)).toHaveLength(3)
expect(index).toContain('<loc>https://acme.pl/sitemap.xml?part=3</loc>')
expect(index).toContain('<lastmod>2026-01-02T00:00:00.000Z</lastmod>')
const part = await (await handler(new Request('https://acme.pl/sitemap.xml?part=3'))).text()
expect(part.match(/<url>/g)).toHaveLength(1)
expect(part).toContain('https://acme.pl/p4')
expect((await handler(new Request('https://acme.pl/sitemap.xml?part=4'))).status).toBe(404)
expect((await handler(new Request('https://acme.pl/sitemap.xml?part=x'))).status).toBe(404)
})
test('entries are reused within memoSeconds, rebuilt when 0', async () => {
const source = vi.fn(async () => make(1))
const memo = createSitemapRouteHandler(source, { style: false })
await memo(new Request('https://acme.pl/sitemap.xml'))
await memo(new Request('https://acme.pl/sitemap.xml'))
expect(source).toHaveBeenCalledTimes(1)
const fresh = vi.fn(async () => make(1))
const noMemo = createSitemapRouteHandler(fresh, { memoSeconds: 0, style: false })
await noMemo(new Request('https://acme.pl/sitemap.xml'))
await noMemo(new Request('https://acme.pl/sitemap.xml'))
expect(fresh).toHaveBeenCalledTimes(2)
})
test('runtime error → 503 Retry-After; empty → not cached and not reused', async () => {
vi.spyOn(console, 'warn').mockImplementation(() => {})
const failing = await createSitemapRouteHandler(async () => {
throw new Error('db down')
})(new Request('https://acme.pl/sitemap.xml'))
expect(failing.status).toBe(503)
expect(failing.headers.get('retry-after')).toBe('300')
const empty = vi.fn(async () => [] as SitemapEntry[])
const handler = createSitemapRouteHandler(empty, { style: false })
const res = await handler(new Request('https://acme.pl/sitemap.xml'))
expect(res.headers.get('cache-control')).toBe('no-store')
await handler(new Request('https://acme.pl/sitemap.xml'))
expect(empty).toHaveBeenCalledTimes(2)
})
test('during next build an error still gives an empty urlset', async () => {
vi.spyOn(console, 'warn').mockImplementation(() => {})
vi.stubEnv('NEXT_PHASE', 'phase-production-build')
const res = await createSitemapRouteHandler(async () => {
throw new Error('no db')
})(new Request('https://acme.pl/sitemap.xml'))
expect(res.status).toBe(200)
expect(await res.text()).toContain('<urlset')
})
test('buildSitemapIndexXml escapes', () => {
expect(buildSitemapIndexXml([{ url: 'https://acme.pl/s.xml?a=1&b=2' }])).toContain('?a=1&amp;b=2')
})
})
describe('system pages without a URL of their own', () => {
const settings = { homepage: { id: 1, slug: { en: 'home', pl: 'start' } }, notFound: { id: 2, slug: { en: 'not-found-page', pl: 'nie-znaleziono' } } }
const pages = [
{ id: 1, slug: { en: 'home', pl: 'start' }, _status: 'published', title: 'Home' },
{ id: 2, slug: { en: 'not-found-page', pl: 'nie-znaleziono' }, _status: 'published', title: 'Not found' },
{ id: 3, slug: { en: 'contact', pl: 'kontakt' }, _status: 'published', title: 'Contact' },
]
test('the assigned 404 page is left out of the sitemap, the site index and llms.txt', async () => {
const payload = fakePayload({ pages })
payload.findGlobal.mockResolvedValue(settings)
const sitemap = await buildSitemapEntries({ baseUrl: 'https://acme.pl', config, payload: payload as never })
expect(sitemap.map((e) => e.url)).toEqual(['https://acme.pl/pl', 'https://acme.pl/en', 'https://acme.pl/pl/kontakt', 'https://acme.pl/en/contact'])
const flat = fakePayload({ pages: pages.map((p) => ({ ...p, slug: p.slug.pl })) })
flat.findGlobal.mockResolvedValue(settings)
expect((await collectSiteIndex({ config: single, payload: flat as never })).map((e) => e.path)).toEqual(['/', '/kontakt'])
expect(await buildLlmsTxt({ baseUrl: 'https://acme.pl', config: single, payload: flat as never })).not.toContain('nie-znaleziono')
})
test('a 404 page that is also the homepage stays listed', async () => {
const payload = fakePayload({ pages: pages.slice(0, 1) })
payload.findGlobal.mockResolvedValue({ homepage: { id: 1 }, notFound: 1 })
expect(await buildSitemapEntries({ baseUrl: 'https://acme.pl', config, payload: payload as never })).toHaveLength(2)
})
})
describe('collectSiteIndex and llms.txt', () => {
const pages = Array.from({ length: 1205 }, (_, i) => ({ id: i, slug: `p${i}`, title: `Page ${i}` }))
test('no silent 1000 cap; limit still caps', async () => {
const payload = fakePayload({ pages })
expect(await collectSiteIndex({ config: single, payload: payload as never })).toHaveLength(1205)
expect(await collectSiteIndex({ config: single, limit: 10, payload: payload as never })).toHaveLength(10)
})
test('include filters by path', async () => {
const payload = fakePayload({ pages: pages.slice(0, 5) })
const index = await collectSiteIndex({ config: single, include: (p) => p === '/p2', payload: payload as never })
expect(index.map((e) => e.path)).toEqual(['/p2'])
})
test('llms.txt carries the editor note under the summary', async () => {
const payload = fakePayload({ pages: pages.slice(0, 1) })
payload.findGlobal.mockResolvedValue({ llmsIntro: 'Acme repairs boilers in Kraków since 1998.', siteDescription: 'Boilers', siteName: 'Acme' })
const body = await buildLlmsTxt({ baseUrl: 'https://acme.pl', config: single, payload: payload as never })
expect(body.startsWith('# Acme\n\n> Boilers\n\nAcme repairs boilers in Kraków since 1998.\n')).toBe(true)
expect(llmsIntroFrom({ llmsIntro: ' ' })).toBe('')
})
test('llms route: only included paths, cached for a CDN', async () => {
const payload = fakePayload({ pages: pages.slice(0, 3) })
const res = await createLlmsTxtRoute({
baseUrl: 'https://acme.pl',
config: single,
getCachedPayload: async () => payload as never,
getIncludedPaths: async () => ['/p1/'],
})()
const body = await res.text()
expect(body).toContain('(https://acme.pl/p1)')
expect(body).not.toContain('/p0')
expect(res.headers.get('cache-control')).toBe(DEFAULT_SITEMAP_CACHE_CONTROL)
})
})
describe('plugin: Search engines tab', () => {
const base = (): Config => ({ collections: [{ slug: 'users', auth: true, fields: [] }], secret: 'test' }) as unknown as Config
const tabs = (c: Config) => {
const settings = c.globals?.find((g) => g.slug === 'site-settings')
const field = settings?.fields[0] as unknown as { tabs: { label: { en: string } }[] }
return field.tabs.map((t) => t.label.en)
}
test('on by default, off with seo.searchSettings: false', async () => {
const on = await iapl({ access: { authCollection: 'users' }, i18n: config, twoFactor: false })(base())
expect(tabs(on)).toContain('Search engines')
const off = await iapl({
access: { authCollection: 'users' },
i18n: config,
seo: { collections: [], searchSettings: false },
twoFactor: false,
})(base())
expect(tabs(off)).not.toContain('Search engines')
const custom = await iapl({
access: { authCollection: 'users' },
i18n: config,
seo: { collections: [], searchSettings: (fields) => fields.filter((f) => 'name' in f && f.name !== 'llmsIntro') },
twoFactor: false,
})(base())
const settings = custom.globals?.find((g) => g.slug === 'site-settings')
const tab = (settings?.fields[0] as unknown as { tabs: { fields: { name?: string }[]; label: { en: string } }[] }).tabs.find((t) => t.label.en === 'Search engines')
expect(tab?.fields.map((f) => f.name)).toEqual(['searchVerification', 'aiCrawlers'])
})
})