Separate from the mail rule so that it can be taken or left. A site whose address matches
iapl({ developmentHosts }) - built in: *.dev.netscale.pl - is noindex with no env: robots.txt disallows
everything, pages carry noindex, IndexNow sends nothing, buildSecurityHeaders() adds X-Robots-Tag. Nothing
kept a development copy out of search engines until now unless somebody set the variable.
- iapl({ developmentNoindex: false }) switches it off for the project, IAPL_NOINDEX=0 for one environment
- buildSecurityHeaders({ developmentHosts, serverUrl }): next.config runs before the plugin
- the mail rule keeps its own two signals: the development pattern, and the variable itself
- changelog "what changes on upgrade", deployment.md, security.md, AGENT.md, skills
Co-Authored-By: Claude Fable 5.2 <[email protected]>
425 lines
21 KiB
TypeScript
425 lines
21 KiB
TypeScript
import { describe, expect, test } from 'vitest'
|
|
|
|
import type { I18nConfig } from '../src/modules/i18n/types.js'
|
|
|
|
import { parseConsent, serializeConsent } from '../src/modules/consent/storage.js'
|
|
import { markdownHref, prefersMarkdown } from '../src/modules/content/markdownNegotiation.js'
|
|
import { lexicalToMarkdown } from '../src/modules/richtext/lexicalToMarkdown.js'
|
|
import { buildCsp } from '../src/modules/security/buildCsp.js'
|
|
import { buildSecurityHeaders } from '../src/modules/security/buildSecurityHeaders.js'
|
|
import { buildAutoFillMetaHook } from '../src/modules/seo/autoFillMeta.js'
|
|
import { AI_TRAINING_BOTS, buildRobots } from '../src/modules/seo/buildRobots.js'
|
|
import { buildSitemapXml } from '../src/modules/seo/buildSitemapXml.js'
|
|
import { createPageMetadata } from '../src/modules/seo/createPageMetadata.js'
|
|
import { buildHreflangAlternates } from '../src/modules/seo/hreflang.js'
|
|
import { describeFromMarkdown } from '../src/modules/seo/plainText.js'
|
|
|
|
const config: I18nConfig = {
|
|
defaultLocale: 'pl',
|
|
locales: [
|
|
{ code: 'pl', label: 'Polski' },
|
|
{ code: 'en', label: 'English' },
|
|
],
|
|
}
|
|
|
|
describe('buildRobots', () => {
|
|
test('defaults: allow all but admin/api, sitemap, explicit AI allow', () => {
|
|
const r = buildRobots({ baseUrl: 'https://acme.pl/' })
|
|
expect(r.sitemap).toBe('https://acme.pl/sitemap.xml')
|
|
expect(r.host).toBe('https://acme.pl')
|
|
const [base, ai] = r.rules as { disallow: string[]; userAgent: string | string[] }[]
|
|
expect(base.disallow).toEqual(['/admin', '/api'])
|
|
expect(ai.userAgent).toEqual(expect.arrayContaining(['ClaudeBot', 'GPTBot']))
|
|
})
|
|
|
|
test('hidden admin route is not revealed', () => {
|
|
const r = buildRobots({ adminRoute: false, aiBots: false, baseUrl: 'https://acme.pl' })
|
|
expect((r.rules as { disallow: string[] }).disallow).toEqual(['/api'])
|
|
})
|
|
|
|
test('block-training keeps assistants, blocks training crawlers', () => {
|
|
const rules = buildRobots({ aiBots: 'block-training', baseUrl: 'https://acme.pl' }).rules as {
|
|
disallow: string[]
|
|
userAgent: string[]
|
|
}[]
|
|
const training = rules.find((r) => r.userAgent.includes(AI_TRAINING_BOTS[0]))
|
|
expect(training?.disallow).toEqual(['/'])
|
|
})
|
|
|
|
test('disallowParams covers the param in any position', () => {
|
|
const r = buildRobots({ aiBots: false, baseUrl: 'https://acme.pl', disallowParams: ['s'] })
|
|
expect((r.rules as { disallow: string[] }).disallow).toEqual(['/admin', '/api', '/*?s=', '/*&s='])
|
|
})
|
|
})
|
|
|
|
describe('buildSitemapXml', () => {
|
|
test('escapes URLs and emits hreflang alternates', () => {
|
|
const xml = buildSitemapXml(
|
|
[
|
|
{
|
|
alternates: { languages: { en: 'https://acme.pl/en/a', pl: 'https://acme.pl/pl/a' } },
|
|
lastModified: new Date('2026-01-02T00:00:00Z'),
|
|
url: 'https://acme.pl/pl/a?x=1&y=2',
|
|
},
|
|
],
|
|
{ cssUrl: '/sitemap.css' },
|
|
)
|
|
expect(xml).toMatch(/^<\?xml/)
|
|
expect(xml).toContain('<?xml-stylesheet type="text/css" href="/sitemap.css"?>')
|
|
expect(xml).toContain('<loc>https://acme.pl/pl/a?x=1&y=2</loc>')
|
|
expect(xml).toContain('<lastmod>2026-01-02T00:00:00.000Z</lastmod>')
|
|
expect(xml).toContain('<xhtml:link rel="alternate" hreflang="en" href="https://acme.pl/en/a"/>')
|
|
})
|
|
})
|
|
|
|
describe('buildHreflangAlternates', () => {
|
|
test('one URL per locale plus x-default → default locale', () => {
|
|
expect(
|
|
buildHreflangAlternates({ baseUrl: 'https://acme.pl', config, slugs: { en: 'about', pl: 'o-nas' } }),
|
|
).toEqual({
|
|
en: 'https://acme.pl/en/about',
|
|
pl: 'https://acme.pl/pl/o-nas',
|
|
'x-default': 'https://acme.pl/pl/o-nas',
|
|
})
|
|
})
|
|
|
|
test('single-locale sites get no alternates', () => {
|
|
const single: I18nConfig = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }
|
|
expect(buildHreflangAlternates({ config: single, slugs: { pl: 'o-nas' } })).toEqual({})
|
|
})
|
|
})
|
|
|
|
describe('security headers', () => {
|
|
test('CSP: hard defaults, opt-in sources, report-only header name', () => {
|
|
const csp = buildCsp({ turnstile: true })
|
|
expect(csp.key).toBe('Content-Security-Policy')
|
|
expect(csp.value).toContain("frame-ancestors 'none'")
|
|
expect(csp.value).toContain("object-src 'none'")
|
|
expect(csp.value).toMatch(/script-src [^;]*https:\/\/challenges\.cloudflare\.com/)
|
|
expect(csp.value).not.toContain('unsafe-eval')
|
|
expect(buildCsp({ mode: 'report-only' }).key).toBe('Content-Security-Policy-Report-Only')
|
|
})
|
|
|
|
test('CSP: relative R2 URL is not added (already self)', () => {
|
|
expect(buildCsp({ r2Url: '/media' }).value).not.toContain('/media')
|
|
expect(buildCsp({ r2Url: 'https://cdn.acme.pl' }).value).toContain('https://cdn.acme.pl')
|
|
})
|
|
|
|
test('headers: HSTS, nosniff, overrides by key', () => {
|
|
const headers = buildSecurityHeaders({ additional: [{ key: 'x-frame-options', value: 'SAMEORIGIN' }] })
|
|
const get = (k: string) => headers.find((h) => h.key.toLowerCase() === k.toLowerCase())?.value
|
|
expect(get('Strict-Transport-Security')).toBe('max-age=63072000; includeSubDomains')
|
|
expect(get('X-Content-Type-Options')).toBe('nosniff')
|
|
expect(get('X-Frame-Options')).toBe('SAMEORIGIN')
|
|
expect(headers.filter((h) => h.key.toLowerCase() === 'x-frame-options')).toHaveLength(1)
|
|
})
|
|
})
|
|
|
|
describe('Markdown for AI', () => {
|
|
test('markdownHref', () => {
|
|
expect(markdownHref('/pl/o-nas')).toBe('/md/pl/o-nas')
|
|
expect(markdownHref('/')).toBe('/md')
|
|
expect(markdownHref('pl', '/ai/')).toBe('/ai/pl')
|
|
})
|
|
|
|
test('prefersMarkdown respects q-values', () => {
|
|
expect(prefersMarkdown('text/markdown')).toBe(true)
|
|
expect(prefersMarkdown('text/html,text/markdown;q=0.5')).toBe(false)
|
|
expect(prefersMarkdown(new Headers({ accept: 'text/markdown, text/html' }))).toBe(true)
|
|
expect(prefersMarkdown('text/html')).toBe(false)
|
|
expect(prefersMarkdown(undefined)).toBe(false)
|
|
})
|
|
|
|
test('lexicalToMarkdown renders the common nodes', () => {
|
|
const text = (t: string, format = 0) => ({ type: 'text', format, text: t })
|
|
const md = lexicalToMarkdown({
|
|
root: {
|
|
children: [
|
|
{ type: 'heading', children: [text('Tytuł')], tag: 'h2' },
|
|
{ type: 'paragraph', children: [text('Zwykły '), text('gruby', 1), text(' i '), text('kursywa', 2)] },
|
|
{ type: 'paragraph', children: [{ type: 'link', children: [text('link')], fields: { url: 'https://acme.pl' } }] },
|
|
{ type: 'paragraph', children: [] },
|
|
{ type: 'upload', value: { alt: 'Logo', url: '/media/logo.png' } },
|
|
],
|
|
},
|
|
} as never)
|
|
expect(md).toBe(
|
|
'## Tytuł\n\nZwykły **gruby** i _kursywa_\n\n[link](https://acme.pl)\n\n',
|
|
)
|
|
expect(lexicalToMarkdown(null)).toBe('')
|
|
})
|
|
})
|
|
|
|
describe('consent cookie', () => {
|
|
test('round-trips and always keeps necessary on', () => {
|
|
const raw = serializeConsent({ analytics: true, functional: false, marketing: false, necessary: false } as never)
|
|
expect(parseConsent(raw)).toMatchObject({ analytics: true, marketing: false, necessary: true })
|
|
})
|
|
|
|
test('garbage or an old version → null (ask again)', () => {
|
|
expect(parseConsent('%%%')).toBeNull()
|
|
expect(parseConsent(encodeURIComponent(JSON.stringify({ state: {}, version: 0 })))).toBeNull()
|
|
expect(parseConsent(undefined)).toBeNull()
|
|
})
|
|
})
|
|
|
|
describe('buildNavigationJsonLd', () => {
|
|
test('resolves page links per locale, keeps own-site links only, dedupes, walks submenus', async () => {
|
|
const { buildNavigationJsonLd } = await import('../src/modules/seo/buildSiteNavigationJsonLd.js')
|
|
const page = (slug: string) => ({ type: 'internal' as const, page: { slug } })
|
|
const nav = buildNavigationJsonLd({
|
|
baseUrl: 'https://acme.pl/',
|
|
config,
|
|
homeSlug: { en: 'home', pl: 'start' },
|
|
items: [
|
|
{ link: { ...page('start'), label: 'Start' } },
|
|
{ link: { ...page('uslugi'), label: 'Usługi' }, subItems: [{ link: { ...page('audyt'), label: 'Audyt' } }] },
|
|
{ link: { type: 'external', label: 'Blog firmy X', url: 'https://medium.com/x' } },
|
|
{ link: { ...page('uslugi'), label: 'Usługi (dup)' } },
|
|
{ link: { ...page('bez-etykiety') } },
|
|
],
|
|
locale: 'pl',
|
|
})
|
|
expect(nav?.itemListElement.map((i: { name: string; url: string }) => [i.name, i.url])).toEqual([
|
|
['Start', 'https://acme.pl/pl'],
|
|
['Usługi', 'https://acme.pl/pl/uslugi'],
|
|
['Audyt', 'https://acme.pl/pl/audyt'],
|
|
])
|
|
})
|
|
})
|
|
|
|
describe('buildCsp — googleMaps', () => {
|
|
test('covers Maps JS API domains in every needed directive, no duplicates', () => {
|
|
const { value } = buildCsp({ googleMaps: true })
|
|
const dir = (name: string) => value.split('; ').find((d) => d.startsWith(`${name} `)) ?? ''
|
|
for (const d of ['script-src', 'img-src', 'connect-src']) {
|
|
expect(dir(d)).toContain('https://*.googleapis.com')
|
|
expect(dir(d)).toContain('https://*.gstatic.com')
|
|
}
|
|
expect(dir('frame-src')).toContain('https://*.google.com')
|
|
expect(dir('worker-src')).toContain('blob:')
|
|
for (const d of value.split('; ')) {
|
|
const parts = d.split(' ').slice(1)
|
|
expect(new Set(parts).size).toBe(parts.length)
|
|
}
|
|
expect(buildCsp().value).toContain('https://fonts.gstatic.com')
|
|
})
|
|
})
|
|
|
|
describe('consent storage — version and id', () => {
|
|
test('a consent from another policy version is ignored; id round-trips', async () => {
|
|
const { readConsentRecord, serializeConsent } = await import('../src/modules/consent/storage.js')
|
|
const state = { analytics: true, functional: true, marketing: false, necessary: true }
|
|
const raw = serializeConsent(state, 2, 'abc123')
|
|
expect(readConsentRecord(raw, 2)).toMatchObject({ id: 'abc123', state, version: 2 })
|
|
expect(readConsentRecord(raw, 3)).toBeNull()
|
|
expect(readConsentRecord(raw)).toBeNull() // default version 1
|
|
})
|
|
})
|
|
|
|
describe('safeHref / resolveLinkHref', () => {
|
|
test('only safe schemes survive', async () => {
|
|
const { resolveLinkHref, safeHref } = await import('../src/modules/links/resolveLinkHref.js')
|
|
for (const ok of ['https://acme.pl', 'mailto:[email protected]', 'tel:+48123', '#kontakt', '/pl/o-nas']) {expect(safeHref(ok)).toBe(ok)}
|
|
for (const bad of ['javascript:alert(1)', ' JavaScript:alert(1)', 'java\tscript:alert(1)', 'data:text/html,x', '//evil.com', 'vbscript:x', '']) {
|
|
expect(safeHref(bad)).toBeNull()
|
|
}
|
|
expect(resolveLinkHref({ type: 'external', url: 'javascript:alert(1)' }, { config, locale: 'pl' })).toBeNull()
|
|
})
|
|
})
|
|
|
|
describe('buildUploadSecurityHeaders', () => {
|
|
test('sandboxes files served from upload routes', async () => {
|
|
const { buildUploadSecurityHeaders } = await import('../src/modules/security/buildSecurityHeaders.js')
|
|
const rules = buildUploadSecurityHeaders({ collections: ['media', 'documents'] })
|
|
// the upload routes, and the panel icon endpoint (it answers with a file's bytes too)
|
|
expect(rules.map((r) => r.source)).toEqual(['/api/media/file/:path*', '/api/documents/file/:path*', '/api/ipal/admin-icon'])
|
|
const csp = rules[0].headers.find((h) => h.key === 'Content-Security-Policy')?.value ?? ''
|
|
expect(csp).toContain('sandbox')
|
|
expect(csp).toContain("default-src 'none'")
|
|
expect(csp).not.toContain('script-src')
|
|
})
|
|
})
|
|
|
|
describe('site-wide noindex (IAPL_NOINDEX) and Markdown headers', () => {
|
|
test('staging blocks crawling everywhere', async () => {
|
|
const { vi } = await import('vitest')
|
|
vi.stubEnv('IAPL_NOINDEX', '1')
|
|
try {
|
|
expect(buildRobots({ baseUrl: 'https://staging.acme.pl' })).toEqual({ rules: { disallow: ['/'], userAgent: '*' } })
|
|
expect(buildSecurityHeaders().find((h) => h.key === 'X-Robots-Tag')?.value).toBe('noindex, nofollow')
|
|
const { buildMetadata } = await import('../src/modules/seo/buildMetadata.js')
|
|
expect(buildMetadata({ config, locale: 'pl', slugs: { pl: 'x' } }).robots).toEqual({ follow: false, index: false })
|
|
} finally {
|
|
vi.unstubAllEnvs()
|
|
}
|
|
expect(buildSecurityHeaders().some((h) => h.key === 'X-Robots-Tag')).toBe(false)
|
|
})
|
|
|
|
test('Markdown mirrors are noindex with a canonical link to the HTML page', async () => {
|
|
const { markdownResponse } = await import('../src/modules/content/createMarkdownRenderer.js')
|
|
const res = markdownResponse('# x', { canonical: 'https://acme.pl/pl/o-nas' })
|
|
expect(res.headers.get('x-robots-tag')).toBe('noindex')
|
|
expect(res.headers.get('link')).toBe('<https://acme.pl/pl/o-nas>; rel="canonical"')
|
|
})
|
|
})
|
|
|
|
describe('a development host is noindex without IAPL_NOINDEX (iapl({ developmentHosts, developmentNoindex }))', () => {
|
|
const DISALLOW_ALL = { rules: { disallow: ['/'], userAgent: '*' } }
|
|
const tag = (args?: Parameters<typeof buildSecurityHeaders>[0]) => buildSecurityHeaders(args).find((h) => h.key === 'X-Robots-Tag')?.value
|
|
const load = async () => ({
|
|
...(await import('../src/modules/seo/buildMetadata.js')),
|
|
...(await import('../src/modules/seo/siteNoindex.js')),
|
|
...(await import('../src/modules/shared/developmentHosts.js')),
|
|
vi: (await import('vitest')).vi,
|
|
})
|
|
const DEV = 'https://acme.dev.netscale.pl'
|
|
|
|
test('robots, the page meta and the header on the built-in development domain, with no variable; the real domain is untouched', async () => {
|
|
const { buildMetadata, configureDevelopmentHosts, isSiteNoindex, siteNoindexSignal, vi } = await load()
|
|
configureDevelopmentHosts()
|
|
vi.stubEnv('IAPL_NOINDEX', '')
|
|
vi.stubEnv('IPAL_NOINDEX', '')
|
|
try {
|
|
expect(buildRobots({ baseUrl: DEV })).toEqual(DISALLOW_ALL)
|
|
expect(buildRobots({ baseUrl: 'https://acme.pl' })).not.toEqual(DISALLOW_ALL)
|
|
expect(buildMetadata({ baseUrl: DEV, config, locale: 'pl', slugs: { pl: 'x' } }).robots).toEqual({ follow: false, index: false })
|
|
expect(buildMetadata({ baseUrl: 'https://acme.pl', config, locale: 'pl', slugs: { pl: 'x' } }).robots).toMatchObject({ index: true })
|
|
expect(tag({ serverUrl: DEV })).toBe('noindex, nofollow')
|
|
expect(tag({ serverUrl: 'https://acme.pl' })).toBeUndefined()
|
|
expect(siteNoindexSignal({ host: DEV })).toBe('development-host')
|
|
// helpers that are given no address read NEXT_PUBLIC_SERVER_URL
|
|
vi.stubEnv('NEXT_PUBLIC_SERVER_URL', DEV)
|
|
expect(tag()).toBe('noindex, nofollow')
|
|
expect(isSiteNoindex()).toBe(true)
|
|
expect(buildMetadata({ config, locale: 'pl', slugs: { pl: 'x' } }).robots).toEqual({ follow: false, index: false })
|
|
vi.stubEnv('NEXT_PUBLIC_SERVER_URL', 'https://acme.pl')
|
|
expect(tag()).toBeUndefined()
|
|
expect(isSiteNoindex()).toBe(false)
|
|
} finally {
|
|
vi.unstubAllEnvs()
|
|
}
|
|
})
|
|
|
|
test('the switches: IAPL_NOINDEX=0 for one environment, developmentNoindex: false, another list, an empty list', async () => {
|
|
const { configureDevelopmentHosts, isSiteNoindex, noindexDevelopmentHosts, siteNoindexSignal, vi } = await load()
|
|
vi.stubEnv('IAPL_NOINDEX', '')
|
|
vi.stubEnv('IPAL_NOINDEX', '')
|
|
try {
|
|
configureDevelopmentHosts()
|
|
for (const off of ['0', 'false', 'no', 'OFF']) {
|
|
vi.stubEnv('IAPL_NOINDEX', off)
|
|
expect(buildRobots({ baseUrl: DEV })).not.toEqual(DISALLOW_ALL)
|
|
expect(tag({ serverUrl: DEV })).toBeUndefined()
|
|
}
|
|
vi.stubEnv('IAPL_NOINDEX', '1') // the variable still works everywhere
|
|
expect(siteNoindexSignal({ host: 'https://acme.pl' })).toBe('env')
|
|
vi.stubEnv('IAPL_NOINDEX', 'maybe') // says nothing: the host decides
|
|
expect(isSiteNoindex({ host: DEV })).toBe(true)
|
|
vi.stubEnv('IAPL_NOINDEX', '')
|
|
|
|
configureDevelopmentHosts({ noindex: false }) // iapl({ developmentNoindex: false })
|
|
expect(noindexDevelopmentHosts()).toBe(false)
|
|
expect(buildRobots({ baseUrl: DEV })).not.toEqual(DISALLOW_ALL)
|
|
expect(isSiteNoindex({ host: DEV })).toBe(false)
|
|
|
|
configureDevelopmentHosts({ hosts: ['*.preview.agency-example.com'] }) // iapl({ developmentHosts: [...] })
|
|
expect(buildRobots({ baseUrl: 'https://x.preview.agency-example.com' })).toEqual(DISALLOW_ALL)
|
|
expect(buildRobots({ baseUrl: DEV })).not.toEqual(DISALLOW_ALL)
|
|
configureDevelopmentHosts({ hosts: [] })
|
|
expect(isSiteNoindex({ host: DEV })).toBe(false)
|
|
|
|
// next.config runs before the plugin: the header builder takes the list itself
|
|
expect(tag({ developmentHosts: ['*.preview.agency-example.com'], serverUrl: 'https://x.preview.agency-example.com' })).toBe('noindex, nofollow')
|
|
expect(tag({ developmentHosts: false, serverUrl: DEV })).toBeUndefined()
|
|
expect(tag({ developmentHosts: [], serverUrl: DEV })).toBeUndefined()
|
|
} finally {
|
|
configureDevelopmentHosts()
|
|
vi.unstubAllEnvs()
|
|
}
|
|
})
|
|
})
|
|
|
|
describe('createPageMetadata — siteDescription fallback', () => {
|
|
// Regresja 1.10.0: readSiteMetaConfig czytał siteDescription, ale nie trafiał do buildMetadata —
|
|
// strona bez meta.description nie miała <meta name="description"> (Lighthouse SEO).
|
|
const settings = { homepage: null, siteDescription: 'Opis firmy z Site Settings', siteName: 'Acme' }
|
|
const payload = {} as never
|
|
|
|
test('page without its own description gets Site Settings → siteDescription', async () => {
|
|
const pageMetadata = createPageMetadata({
|
|
baseUrl: 'https://acme.pl',
|
|
config,
|
|
loaders: { getSettings: async () => settings, resolveRoute: async () => null },
|
|
})
|
|
const metadata = await pageMetadata({ slug: ['o-nas'], locale: 'pl', payload })
|
|
expect(metadata.description).toBe('Opis firmy z Site Settings')
|
|
expect(metadata.openGraph?.description).toBe('Opis firmy z Site Settings')
|
|
})
|
|
|
|
test('no siteDescription → no description (field omitted, not invented)', async () => {
|
|
const pageMetadata = createPageMetadata({
|
|
baseUrl: 'https://acme.pl',
|
|
config,
|
|
loaders: { getSettings: async () => ({ ...settings, siteDescription: null }), resolveRoute: async () => null },
|
|
})
|
|
const metadata = await pageMetadata({ slug: ['o-nas'], locale: 'pl', payload })
|
|
expect(metadata.description).toBeUndefined()
|
|
})
|
|
})
|
|
|
|
describe('buildProductJsonLd', () => {
|
|
test('an Offer only for a real price; "from" is a minimum, not a price', async () => {
|
|
const { buildProductJsonLd } = await import('../src/modules/seo/buildProductJsonLd.js')
|
|
const base = { name: 'Pierścionek', url: 'https://acme.pl/pl/wyroby/p' }
|
|
expect(buildProductJsonLd(base)).not.toHaveProperty('offers')
|
|
expect(buildProductJsonLd({ ...base, price: { amount: 6900, currency: 'PLN', kind: 'exact' } }).offers).toMatchObject({ price: 6900, priceCurrency: 'PLN' })
|
|
expect(buildProductJsonLd({ ...base, availability: 'MadeToOrder', price: { amount: 6900, currency: 'PLN', kind: 'from' } }).offers).toMatchObject({
|
|
availability: 'https://schema.org/MadeToOrder',
|
|
priceSpecification: { minPrice: 6900 },
|
|
})
|
|
})
|
|
})
|
|
|
|
describe('meta description auto-fill', () => {
|
|
const layout = [
|
|
{ blockType: 'hero', heading: 'Car detailing in Opole', subheading: 'For drivers who expect more' },
|
|
{ blockType: 'content', body: 'We apply Gtechniq ceramic coatings and correct paint. Every car gets a written report.' },
|
|
{ blockType: 'content', body: 'Book a free consultation — we will advise on the scope. Opening hours are listed on the contact page.' },
|
|
]
|
|
// the hook ignores everything but data and originalDoc
|
|
const run = (data: Record<string, unknown>, originalDoc?: Record<string, unknown>, mapping = {}) =>
|
|
buildAutoFillMetaHook(mapping)({ data, operation: originalDoc ? 'update' : 'create', originalDoc } as never) as Record<string, unknown>
|
|
|
|
test('describeFromMarkdown skips headings and keeps whole sentences', () => {
|
|
const md = '## Title\n\nFirst sentence here. Second one.\n\n### Sub\n\nThird part without a stop'
|
|
expect(describeFromMarkdown(md)).toBe('First sentence here. Second one. Third part without a stop.')
|
|
const long = describeFromMarkdown('One short sentence. ' + 'word '.repeat(60), 155)
|
|
expect(long).toBe('One short sentence.')
|
|
expect(describeFromMarkdown('## Only a heading')).toBe('Only a heading.')
|
|
expect(describeFromMarkdown('')).toBe('')
|
|
})
|
|
|
|
test('fills an empty description from the page blocks', () => {
|
|
const out = run({ layout, title: 'Detailing' })
|
|
const meta = out.meta as Record<string, string>
|
|
expect(meta.title).toBe('Detailing')
|
|
expect(meta.description).toBe(
|
|
'We apply Gtechniq ceramic coatings and correct paint. Every car gets a written report. Book a free consultation — we will advise on the scope.',
|
|
)
|
|
expect(meta.description.length).toBeLessThanOrEqual(155)
|
|
})
|
|
|
|
test('never replaces a description — typed now or already stored', () => {
|
|
expect((run({ layout, meta: { description: 'Mine' } }).meta as Record<string, string>).description).toBe('Mine')
|
|
// partial update: data carries only the layout, the stored doc has a description
|
|
const out = run({ layout }, { meta: { description: 'Stored', title: 'T' } })
|
|
expect(out.meta).toBeUndefined()
|
|
})
|
|
|
|
test('mapped description field wins; content: false turns the fallback off', () => {
|
|
expect((run({ excerpt: 'Excerpt text', layout }, undefined, { description: 'excerpt' }).meta as Record<string, string>).description).toBe('Excerpt text')
|
|
expect((run({ layout, title: 'T' }, undefined, { content: false }).meta as Record<string, string>).description).toBeUndefined()
|
|
})
|
|
})
|