Files
ipal-kit/src/modules/seo/createPageMetadata.ts
T
Radosław SmolińskiandClaude Opus 5.5 a6eda2e3a3 Pass siteDescription to page metadata; document media cache rule
createPageMetadata read Site Settings → siteDescription but never passed it to
buildMetadata, so pages without their own meta description had no
<meta name="description"> or og:description. Regression test in seo.test.ts.

storage.md: Cloudflare Cache Rule for the media domain (R2 objects carry no
Cache-Control; storage-s3 cannot set it, Cloudflare defaults to 4 h).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 00:07:28 +02:00

208 lines
6.8 KiB
TypeScript

import type { BasePayload } from 'payload'
import type { ContentOption, ResolvedRoute } from '../content/index.js'
import type { I18nConfig } from '../i18n/index.js'
import type { OgImage, PageMetadata } from './buildMetadata.js'
import type { SeoMeta } from './types.js'
import { resolveRoute } from '../content/index.js'
import { buildMetadata } from './buildMetadata.js'
import { readSiteMetaConfig } from './readSiteMetaConfig.js'
import { slugsAcrossLocales } from './slugsAcrossLocales.js'
type CreatePageMetadataArgs = {
/** Absolute site origin, e.g. 'https://example.com'. */
baseUrl?: string
/** Collection holding pages. Defaults to 'pages'. */
collection?: string
config: I18nConfig
/**
* Archive-backed collections, same value as the plugin option. Pass it and
* entry URLs (/pl/artykuly/moj-post) get correct canonical and hreflang;
* omit it and only pages are handled.
*/
content?: ContentOption
/**
* Request-cached loaders (createContentHelpers passes its own), so metadata
* reuses the SAME settings read and route resolution as the layout and the
* page component instead of querying again. Omit → plain queries.
*/
loaders?: {
getSettings?: (locale: string) => Promise<null | Record<string, unknown>>
resolveRoute?: (
locale: string,
segments: string[] | undefined,
page: number,
) => Promise<null | ResolvedRoute>
}
/** SiteSettings global slug. Defaults to 'site-settings'. */
settingsSlug?: string
/** Field on SiteSettings holding the site name. Defaults to 'siteName'. */
siteNameField?: string
}
type PageMetadataContext = {
locale: string
/**
* Page number from ?page= on an archive listing. Pass it and page 2 gets a
* canonical to itself; leave it out and every page claims to be page 1.
*/
page?: number
payload: BasePayload
/** Route slug segments; empty/undefined means the locale root. */
slug?: string[]
}
type DocShape = {
createdAt?: string
id: number | string
meta?: null | SeoMeta
/** Top-level noindex checkbox (buildNoindexField) — the field that persists. */
noindex?: boolean | null
publishedAt?: null | string
/** The document's own title (page name), used as the fallback page title. */
title?: null | string
updatedAt?: string
}
/** An upload relationship (populated) → OG image with its size and alt. */
function toOgImage(image: unknown): null | OgImage {
if (!image || typeof image !== 'object') {return null}
const m = image as { alt?: unknown; height?: unknown; url?: unknown; width?: unknown }
if (typeof m.url !== 'string' || !m.url) {return null}
return {
url: m.url,
...(typeof m.width === 'number' ? { width: m.width } : {}),
...(typeof m.height === 'number' ? { height: m.height } : {}),
...(typeof m.alt === 'string' && m.alt ? { alt: m.alt } : {}),
}
}
/** plugin-seo stores the OG image on the meta group; Site Settings has the fallback. */
function resolveOgImage(doc: DocShape, fallback: unknown): null | OgImage {
return toOgImage((doc.meta as { image?: unknown } | null | undefined)?.image) ?? toOgImage(fallback)
}
/**
* Metadata for the page route, with every resolver already wired.
*
* `createMetadataGenerator` asks the client for resolvers because it can't know
* their collections. But for the plugin's own conventions it does know: pages
* live in one collection, the site name sits on SiteSettings, the OG image sits
* on the plugin-seo `meta` group, the home page is whatever System Pages points
* at, and — with `content` — entries live under their collection's archive page.
* Re-declaring all that in every project is copy-paste, so this resolves it.
*
* Reach for `createMetadataGenerator` instead when a route doesn't follow those
* conventions — custom image logic, a different global, hand-rolled paths.
*
* The plugin never calls getPayload, and Next calls generateMetadata without a
* payload, so the client keeps a small wrapper:
*
* ```ts
* const pageMetadata = createPageMetadata({ config: i18nConfig, baseUrl, content })
*
* export async function generateMetadata({ params }) {
* const { locale, slug } = await params
* return pageMetadata({ payload: await getPayload({ config }), locale, slug })
* }
* ```
*/
export function createPageMetadata(args: CreatePageMetadataArgs) {
const {
baseUrl,
collection = 'pages',
config,
content,
loaders,
settingsSlug = 'site-settings',
siteNameField = 'siteName',
} = args
return async function pageMetadata({
slug,
locale,
page,
payload,
}: PageMetadataContext): Promise<PageMetadata> {
const settings = loaders?.getSettings ? await loaders.getSettings(locale) : undefined
const site = await readSiteMetaConfig({
locale,
pagesSlug: collection,
payload,
settings,
settingsSlug,
siteNameField,
})
const base = {
baseUrl,
config,
homeSlug: site.homeSlug,
locale,
order: site.order,
separator: site.separator,
// fallback opisu: strona bez meta.description dostaje Site Settings → siteDescription (seo.md)
siteDescription: site.siteDescription,
siteName: site.siteName,
}
const route = loaders?.resolveRoute
? await loaders.resolveRoute(locale, slug, page ?? 1)
: await resolveRoute({
content,
locale,
page,
pagesSlug: collection,
payload,
segments: slug,
settings,
settingsSlug,
})
// Unknown route (the page component will 404) — still return something
// coherent rather than throwing during metadata generation.
if (!route) {
return buildMetadata({ ...base, meta: null, slugs: {} })
}
const doc = route.doc as DocShape
// An entry sits under its archive, so its URLs need that segment — and the
// segment differs per locale, since it's the archive page's own slug.
const prefix =
route.type === 'entry'
? await slugsAcrossLocales({
id: (route.archive as DocShape).id,
collection,
config,
payload,
})
: undefined
const slugs = await slugsAcrossLocales({
id: doc.id,
collection: route.type === 'entry' ? route.collection : collection,
config,
payload,
})
// Page 2 of a listing is its own URL, not a variant of page 1.
const query = route.type === 'archive' && route.page > 1 ? `?page=${route.page}` : undefined
return buildMetadata({
...base,
...(route.type === 'entry'
? { article: { modifiedTime: doc.updatedAt, publishedTime: doc.publishedAt ?? doc.createdAt } }
: {}),
image: resolveOgImage(doc, site.defaultShareImage),
meta: doc.meta,
noindex: doc.noindex,
pageTitle: doc.title,
prefix,
query,
slugs,
})
}
}