Files
ipal-kit/src/modules/seo/autoFillMeta.ts
T
Radosław SmolińskiandClaude Opus 5.5 e1431a7c49 Stable admin import map without R2 env, read-only media, Cookie Settings save-button migration
buildR2Storage registered nothing without R2_* env, so `pnpm dev` / generate:importmap in dev
wrote an importMap.js without S3ClientUploadHandler — committed, the production admin (R2 on)
rendered a blank page with no console error (hit vanstev.pl). The injected s3Storage is now
always registered (enabled: false without R2 → local disk); storage-s3 still adds its client
handler, so the import map is identical in every environment. ipal-audit flags an import map
without the handler.

R2_PUBLIC_URL alone (absolute, outside production) = read-only media: URLs from the media
domain, upload/delete refused with 403 — local dev against a production database without
bucket keys. ipalEnvRules allows it in development.

Cookie Settings (MongoDB): the 1.11.1 rename buttons.save → savePreferences lost the texts on
the first save; onInit copies the old value (all locales) when the new field is missing.
getConsentTexts read the old field as a string, Mongo returns the raw { pl, en } map.

Also: context.ipalSkipAutoFill (SKIP_AUTO_FILL) — save without meta / aiSummary auto-fill;
createPageRoute redirects the homepage under its own slug (homeAlias, default 'redirect');
ipal-audit: multi-line tsconfig exclude, numeronyms (a11y) not "numbered fields",
`${prefix}/${slug}` links and slugs typed into links detected, clearer panel-language message.
Docs: fallback-on-save in i18n.md, `pnpm up --latest` and the stale-token 401 in PROGRAMISTA §1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 16:45:03 +02:00

87 lines
3.7 KiB
TypeScript

import type { CollectionBeforeChangeHook } from 'payload'
import { blocksToMarkdown } from '../content/blocksToMarkdown.js'
import { describeFromMarkdown } from './plainText.js'
import { isAutoFillSkipped } from './skipAutoFill.js'
/**
* Maps document fields to SEO meta fields for auto-fill.
* Defaults match the Payload website template (title → meta.title).
*/
export type AutoFillMapping = {
/**
* Block layout field to derive meta.description from when it's empty and the
* `description` field gives nothing. Default 'layout'; false turns it off.
*/
content?: false | string
/** Document field used to fill meta.description when empty. Tried before `content`. */
description?: string
/** Target length of a description derived from `content`. Default 155. */
descriptionLength?: number
/** Document field used to fill meta.title when empty. Default: 'title'. */
title?: string
}
/**
* Reads a possibly-localized field value into a plain string.
* With localized fields at this hook stage the value is the active-locale
* string, so we just coerce defensively.
*/
function readString(value: unknown): string | undefined {
if (typeof value === 'string' && value.trim()) {return value.trim()}
return undefined
}
/**
* Builds a beforeChange hook that fills empty SEO meta fields from document
* content. Only fills when the meta field is blank — never overwrites what an
* editor typed. This runs server-side on every create/update, so editors get
* sensible meta without clicking "auto-generate".
*
* Every page gets its own description: from the `description` field when one
* is mapped, otherwise from the page's own blocks. Without it, pages fall back
* to the one site-wide description, and Google — seeing the same text on every
* page — ignores it and quotes the footer instead.
*
* The plugin doesn't know the client's collection shape, so the field mapping
* is configurable; defaults follow the website template.
*/
export function buildAutoFillMetaHook(mapping: AutoFillMapping = {}): CollectionBeforeChangeHook {
const titleField = mapping.title ?? 'title'
const descriptionField = mapping.description
const contentField = mapping.content === undefined ? 'layout' : mapping.content
const descriptionLength = mapping.descriptionLength ?? 155
return ({ context, data, originalDoc }) => {
if (!data || isAutoFillSkipped(context)) {return data}
// plugin-seo stores meta as a group under `meta`
const meta = (data.meta as Record<string, unknown> | undefined) ?? {}
// A partial update (REST PATCH, payload.update with a few fields) carries
// only what changed — read the rest from the stored document, so a saved
// description isn't treated as empty and replaced.
const stored = (originalDoc?.meta as Record<string, unknown> | undefined) ?? {}
const current = (key: string) => (key in meta ? meta[key] : stored[key])
const source = (field: string) => (field in data ? data[field] : originalDoc?.[field])
// Fill meta.title from the document title when empty
if (!readString(current('title'))) {
const sourceTitle = readString(source(titleField))
if (sourceTitle) {meta.title = sourceTitle}
}
// Fill meta.description from a configured field, else from the page content
if (!readString(current('description'))) {
const sourceDescription =
(descriptionField && readString(source(descriptionField))) ||
(contentField &&
describeFromMarkdown(blocksToMarkdown(source(contentField)), descriptionLength)) ||
undefined
if (sourceDescription) {meta.description = sourceDescription}
}
if (data.meta !== undefined || Object.keys(meta).length) {data.meta = meta}
return data
}
}