From bb10fb10fdaa83c7831f6dcd51d579870be1b405 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 29 Oct 2026 12:06:55 +0100 Subject: [PATCH] Fix /api/graphql 500: Site settings title separator values are GraphQL enum names MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The titleSeparator select stored '|', '–', '-', '·', '/'. Select values become GraphQL enum names; '|', '–', '·' are invalid and '-' and '/' collide on '_', so every project's /api/graphql answered 500 since 1.0.1 (admin/REST unaffected). - Values are now pipe/endash/hyphen/middot/slash (same labels); TITLE_SEPARATORS and titleSeparatorChar map them to the character; titles accept old characters and custom project values literally - Field afterRead/beforeChange turn an old stored character into its name - MongoDB: rewritten at start (migrateTitleSeparator); Postgres: titleSeparatorSql() for the generated migration (verified up/down/up against Postgres 16) - Test builds the full plugin GraphQL schema and fails on invalid or duplicate enum names; unit tests for the mapping, hooks, SQL and Mongo rewrite - CHANGELOG Unreleased (Fixed + upgrade step 5), seo.md, ipal-upgrade, api.md Co-Authored-By: Claude Opus 5.5 --- dev/payload-types.ts | 2 +- docs/CHANGELOG.md | 26 ++++ .../skills/ipal-reference/resources/api.md | 3 + docs/agent/skills/ipal-upgrade/SKILL.md | 11 ++ docs/seo.md | 9 +- src/globals/SiteSettings/fields/general.ts | 20 ++- src/index.ts | 3 + src/modules/seo/index.ts | 2 + src/modules/seo/readSiteMetaConfig.ts | 3 +- src/modules/seo/titleSeparator.ts | 91 ++++++++++++ src/plugin.ts | 2 + test/graphqlSchema.test.ts | 140 ++++++++++++++++++ test/titleSeparator.test.ts | 82 ++++++++++ 13 files changed, 385 insertions(+), 9 deletions(-) create mode 100644 src/modules/seo/titleSeparator.ts create mode 100644 test/graphqlSchema.test.ts create mode 100644 test/titleSeparator.test.ts diff --git a/dev/payload-types.ts b/dev/payload-types.ts index d1c9cd2..b3396a8 100644 --- a/dev/payload-types.ts +++ b/dev/payload-types.ts @@ -1238,7 +1238,7 @@ export interface SiteSetting { /** * Separates the page title from the site name in browser tabs. */ - titleSeparator?: ('|' | '–' | '-' | '·' | '/') | null; + titleSeparator?: ('pipe' | 'endash' | 'hyphen' | 'middot' | 'slash') | null; /** * Primary site logo. */ diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 27c5031..51fc405 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -13,6 +13,16 @@ once there are more than 20. The theme choice moves to the standard `theme` key, the cookie scanner declares the plugin's own browser-storage key, and the cookie list tells cookies from browser storage. A pasted `/admin` link now shows the site's own name, description and preview image instead of Payload's, and search engines are told not to index the panel. +`/api/graphql` works again: it answered 500 on every site since 1.0.1. + +### Fixed +- **`/api/graphql` returned 500 for every project** (`Names must start with [_a-zA-Z] but "|" does not.`). The values + of Site settings → **Title separator** became GraphQL enum names, and `|`, `–`, `·` are not valid names (`-` and + `/` both became `_`). Present since 1.0.1. The admin, REST and Local API were not affected, because they don't use + GraphQL. Stored values are now names: `pipe`, `endash`, `hyphen`, `middot`, `slash`. The labels are the same, and + `TITLE_SEPARATORS` / `titleSeparatorChar` map a name to its character. An old stored character still works: titles + use it, and the field reads and saves it as its name. A test now builds the full plugin's GraphQL schema and fails + on any invalid or duplicate enum name. ### Changed - **Theme key** `ipal-theme` → **`theme`** (`THEME_STORAGE_KEY`), the key and `light` / `dark` values next-themes uses. @@ -62,6 +72,22 @@ description and preview image instead of Payload's, and search engines are told Intecion.com"; `agency: false` or `whiteLabel: { credit: false }` to remove it. No new admin components (the import map is unchanged). **Check:** `curl -s $URL/admin/login | grep -E 'og:|robots'`, open `$URL/api/ipal/admin-og`, and paste an `/admin` link in Slack or Messenger. +5. **Title separator (Postgres):** `pnpm payload migrate:create title-separator`. The generated SQL turns the column + into text, recreates the enum with the new names and casts back, and that cast **fails on a stored `|`**. Add the + data update right after the first `SET DATA TYPE text;` in `up` (and the `'down'` variant in `down`): + ```ts + import { titleSeparatorSql } from '@intecion/ipal-kit' + // up: ALTER TABLE "site_settings" ALTER COLUMN "title_separator" SET DATA TYPE text; + // ${sql.raw(titleSeparatorSql())} + // down: ALTER TABLE "site_settings" ALTER COLUMN "title_separator" SET DATA TYPE text; + // ${sql.raw(titleSeparatorSql({ direction: 'down' }))} + ``` + **SQLite:** the column is plain text, so nothing fails. Optionally run `titleSeparatorSql()` in a migration to + store the names. **MongoDB:** nothing to do, because the plugin rewrites the stored character at start + (`[ipal] Site Settings: title separator … stored as …`). If you overrode the field's options (`globalOverrides`), + use GraphQL-safe values (`/^[_A-Za-z][_A-Za-z0-9]*$/`). **Check:** + `curl -s -X POST $URL/api/graphql -H 'content-type: application/json' -d '{"query":"{ SiteSetting { titleSeparator } }"}'` + returns 200, and the browser tab shows the same separator as before. ## 1.14.4 diff --git a/docs/agent/skills/ipal-reference/resources/api.md b/docs/agent/skills/ipal-reference/resources/api.md index 99851af..b2a6112 100644 --- a/docs/agent/skills/ipal-reference/resources/api.md +++ b/docs/agent/skills/ipal-reference/resources/api.md @@ -629,6 +629,9 @@ Most routes and metadata are already ready in `createContentHelpers` (`generateP | `buildSummaryField(args?)` | `@intecion/ipal-kit` | Localized `aiSummary` field (auto-filled from content when empty) — a description for AI; then `summaryField: 'aiSummary'` in llms/search/MCP. | | `buildAutoFillMetaHook(mapping?)` | `@intecion/ipal-kit` | `beforeChange` hook that fills empty `meta.title`/`meta.description` from content. The plugin wires it itself on the `seo.collections` collections (option `seo.autoFill`) — do not call. | | `injectAutoFillMeta(config, seo)` | `@intecion/ipal-kit` | Injects the hook above into the SEO collections. The plugin wires it itself — do not call. | +| `TITLE_SEPARATORS` | `@intecion/ipal-kit` | Site settings → Title separator: stored name → character (`{ pipe: '\|', endash: '–', hyphen: '-', middot: '·', slash: '/' }`). Type `TitleSeparatorName`. | +| `titleSeparatorChar(value)` | `@intecion/ipal-kit` | Stored separator value → the character in the title. A name maps through `TITLE_SEPARATORS`; an old stored character (≤ 1.14.4) or a project's own option is returned as is. For a custom title builder. `readSiteMetaConfig` already uses it. | +| `titleSeparatorSql({ table?, column?, direction? })` | `@intecion/ipal-kit` | SQL `UPDATE` that rewrites old separator characters to names (`'up'`) or back (`'down'`). Put it in the Postgres migration after `SET DATA TYPE text;` (ipal-upgrade, CHANGELOG). | | `SKIP_AUTO_FILL` | `@intecion/ipal-kit` | `'ipalSkipAutoFill'` — `context` key (`context: { [SKIP_AUTO_FILL]: true }`) that turns off meta auto-fill and the AI summary on save (migrations, scripts). | | `validateFaviconField` | `@intecion/ipal-kit` | `FieldHook` that logs a server warning when the favicon is < 48×48 or not square (never blocks the save). The plugin wires it itself on the favicon field in SiteSettings — call it only for your own favicon field. | | `DocumentTitle` | `@intecion/ipal-kit/admin` | Client component `{ title }`: sets the browser-tab title of a custom admin view after load, so it follows the admin language (Payload's view `meta.title` is one fixed string). Render it in your view with a translated title; the statistics view uses it. | diff --git a/docs/agent/skills/ipal-upgrade/SKILL.md b/docs/agent/skills/ipal-upgrade/SKILL.md index cadc205..d5c148f 100644 --- a/docs/agent/skills/ipal-upgrade/SKILL.md +++ b/docs/agent/skills/ipal-upgrade/SKILL.md @@ -164,6 +164,17 @@ the panel title, description, `openGraph` or `robots: noindex` — the plugin no (keep any key you really want: your `admin.meta` keys win). The credit reads "Technology support: Intecion.com". Check: `curl -s $URL/admin/login | grep -E 'og:|robots'` and paste an `/admin` link in Slack. +**→ title separator / GraphQL fix (CHANGELOG Unreleased, item 5):** Site settings → Title separator now stores +names (`pipe`, `endash`, `hyphen`, `middot`, `slash`) instead of `|`, `–`… (which broke `/api/graphql` with 500). +**Postgres:** `pnpm payload migrate:create title-separator`, then in the generated file add +`${sql.raw(titleSeparatorSql())}` right after the first `ALTER TABLE "site_settings" ALTER COLUMN "title_separator" +SET DATA TYPE text;` in `up` and `${sql.raw(titleSeparatorSql({ direction: 'down' }))}` at the same place in `down` +(`import { titleSeparatorSql } from '@intecion/ipal-kit'`). Without it the migration fails with `invalid input value +for enum` and rolls back. **SQLite / MongoDB:** nothing required. Old values keep working, and MongoDB is rewritten +at start. A project with its own separator options (`globalOverrides`): use values matching `/^[_A-Za-z][_A-Za-z0-9]*$/`. +Check: `curl -s -X POST $URL/api/graphql -H 'content-type: application/json' -d '{"query":"{ SiteSetting { titleSeparator } }"}'` → 200, +and the browser tab shows the same separator. + ## 2. Inventory (no code changes) For **every** item in the PROGRAMISTA §6 table show evidence (grep / file) of whether it applies to the project. Run the **ipal-audit** skill (`--quick`) and attach the result. diff --git a/docs/seo.md b/docs/seo.md index c086a23..0324e9f 100644 --- a/docs/seo.md +++ b/docs/seo.md @@ -61,7 +61,7 @@ are other fields there already (slug, roles), leaving an empty SEO tab. No code, per site (Site settings → General): - **Title Order** — `Page first` (O nas | Acme) or `Site first` (Acme | O nas) -- **Title Separator** — `|` `–` `-` `·` `/` +- **Title Separator** — `|` `–` `-` `·` `/`, stored as `pipe`, `endash`, `hyphen`, `middot`, `slash` Per page (SEO tab): @@ -70,6 +70,13 @@ Per page (SEO tab): Default: `Title | Site name`. +The stored values are names, not the characters, because select values become GraphQL enum names and `|` is not a +valid one. Up to 1.14.4 the character itself was stored, which made `/api/graphql` answer 500. An old character is +still understood. For a custom title builder, `titleSeparatorChar(settings.titleSeparator)` returns the character +(`TITLE_SEPARATORS` is the map; any other value is used literally, so a project can add its own options with +GraphQL-safe values). For the Postgres upgrade, the migration needs `titleSeparatorSql()`: see the CHANGELOG +(Unreleased → What projects must update). + ### Where the "Title" comes from (source priority) The page title (the part before the site name) comes from, in order: diff --git a/src/globals/SiteSettings/fields/general.ts b/src/globals/SiteSettings/fields/general.ts index a78f4de..cf9f6f2 100644 --- a/src/globals/SiteSettings/fields/general.ts +++ b/src/globals/SiteSettings/fields/general.ts @@ -1,6 +1,7 @@ import type { Field } from 'payload' import { validateFaviconField } from '../../../modules/seo/index.js' +import { titleSeparatorName } from '../../../modules/seo/titleSeparator.js' /** * General site identity fields. @@ -121,14 +122,21 @@ export const generalFields: Field[] = [ { name: 'titleSeparator', type: 'select', - defaultValue: '|', + defaultValue: 'pipe', + // Values are GraphQL enum names (TITLE_SEPARATORS maps them to the character). + // Up to 1.14.4 the character itself was stored ('|') and broke /api/graphql; + // such a value still reads and saves as its name. + hooks: { + afterRead: [({ value }) => titleSeparatorName(value)], + beforeChange: [({ value }) => titleSeparatorName(value)], + }, label: { en: 'Title separator', pl: 'Separator w tytule' }, options: [ - { label: { en: 'Pipe — Page | Site', pl: 'Kreska pionowa — Strona | Witryna' }, value: '|' }, - { label: { en: 'Dash — Page – Site', pl: 'Półpauza — Strona – Witryna' }, value: '–' }, - { label: { en: 'Hyphen — Page - Site', pl: 'Dywiz — Strona - Witryna' }, value: '-' }, - { label: { en: 'Bullet — Page · Site', pl: 'Kropka — Strona · Witryna' }, value: '·' }, - { label: { en: 'Slash — Page / Site', pl: 'Ukośnik — Strona / Witryna' }, value: '/' }, + { label: { en: 'Pipe — Page | Site', pl: 'Kreska pionowa — Strona | Witryna' }, value: 'pipe' }, + { label: { en: 'Dash — Page – Site', pl: 'Półpauza — Strona – Witryna' }, value: 'endash' }, + { label: { en: 'Hyphen — Page - Site', pl: 'Dywiz — Strona - Witryna' }, value: 'hyphen' }, + { label: { en: 'Bullet — Page · Site', pl: 'Kropka — Strona · Witryna' }, value: 'middot' }, + { label: { en: 'Slash — Page / Site', pl: 'Ukośnik — Strona / Witryna' }, value: 'slash' }, ], }, ], diff --git a/src/index.ts b/src/index.ts index 2af11aa..448b979 100644 --- a/src/index.ts +++ b/src/index.ts @@ -360,6 +360,9 @@ export { buildBreadcrumbJsonLd, buildNavigationJsonLd, buildSiteNavigationJsonLd export { buildFaqJsonLd, buildLocalBusinessJsonLd, buildServiceJsonLd } from './modules/seo/index.js' export { buildArticleJsonLd, buildProductJsonLd, buildWebPageJsonLd, formatOpeningHours } from './modules/seo/index.js' export { buildLlmsTxt } from './modules/seo/index.js' +// Site Settings → Title separator: stored name → character; SQL for the 1.14.x → GraphQL-safe values migration. +export { TITLE_SEPARATORS, titleSeparatorChar, titleSeparatorSql } from './modules/seo/index.js' +export type { TitleSeparatorName } from './modules/seo/index.js' // Site Settings → Search & AI: verification codes and AI crawler rules, for custom metadata/robots routes. export { robotsOptionsFrom, verificationFrom } from './modules/seo/index.js' export type { AiBotRule, AiBotsPolicy, VerificationMetadata } from './modules/seo/index.js' diff --git a/src/modules/seo/index.ts b/src/modules/seo/index.ts index a963e5a..0bda95c 100644 --- a/src/modules/seo/index.ts +++ b/src/modules/seo/index.ts @@ -56,5 +56,7 @@ export { buildSitemapCss, DEFAULT_SITEMAP_CREDIT, SITEMAP_STYLE_PARAM } from './ export type { SitemapStyleOptions } from './sitemapStyle.js' export { SKIP_AUTO_FILL } from './skipAutoFill.js' export { slugsAcrossLocales } from './slugsAcrossLocales.js' +export { TITLE_SEPARATORS, titleSeparatorChar, titleSeparatorSql } from './titleSeparator.js' +export type { TitleSeparatorName } from './titleSeparator.js' export type { SeoMeta, SeoOption } from './types.js' export { validateFaviconField } from './validateFavicon.js' diff --git a/src/modules/seo/readSiteMetaConfig.ts b/src/modules/seo/readSiteMetaConfig.ts index 89d3bb7..82e7ad6 100644 --- a/src/modules/seo/readSiteMetaConfig.ts +++ b/src/modules/seo/readSiteMetaConfig.ts @@ -4,6 +4,7 @@ import type { TitleOrder } from './composeTitle.js' import type { VerificationMetadata } from './searchSettings.js' import { verificationFrom } from './searchSettings.js' +import { titleSeparatorChar } from './titleSeparator.js' type SettingsShape = { [key: string]: unknown @@ -116,6 +117,6 @@ export async function readSiteMetaConfig({ // The panel stores '|'; titles need it padded. homeSlug, order: settings.titleOrder ?? undefined, - separator: settings.titleSeparator ? ` ${settings.titleSeparator} ` : undefined, + separator: titleSeparatorChar(settings.titleSeparator) ? ` ${titleSeparatorChar(settings.titleSeparator)} ` : undefined, } } diff --git a/src/modules/seo/titleSeparator.ts b/src/modules/seo/titleSeparator.ts new file mode 100644 index 0000000..a9815ad --- /dev/null +++ b/src/modules/seo/titleSeparator.ts @@ -0,0 +1,91 @@ +import type { BasePayload } from 'payload' + +/** + * Site Settings → Title separator: stored value → the character in the title. + * + * Stored values are names, not the characters: select values become GraphQL + * enum names, and '|', '–', '·' are not valid ones ('-' and '/' both turn into + * '_'), which made /api/graphql answer 500 for every site up to 1.14.4. Those + * releases stored the character itself; it is still understood everywhere. + */ +export const TITLE_SEPARATORS = { + endash: '–', + hyphen: '-', + middot: '·', + pipe: '|', + slash: '/', +} as const + +export type TitleSeparatorName = keyof typeof TITLE_SEPARATORS + +const NAME_OF_CHAR: Record = Object.fromEntries( + Object.entries(TITLE_SEPARATORS).map(([name, char]) => [char, name as TitleSeparatorName]), +) + +/** + * Stored value → separator character. Names map to their character, a legacy + * stored character is returned as is, and any other value (a project's own + * option) is used literally. Empty → undefined. + */ +export function titleSeparatorChar(value: unknown): string | undefined { + if (typeof value !== 'string' || !value.trim()) {return undefined} + return (TITLE_SEPARATORS as Record)[value] ?? value +} + +/** + * Legacy stored character → its name; everything else unchanged. The field's + * afterRead/beforeChange hooks use it, so documents saved before the rename open + * and save without "invalid selection" before anyone touches them. + */ +export function titleSeparatorName(value: unknown): unknown { + return typeof value === 'string' && NAME_OF_CHAR[value] ? NAME_OF_CHAR[value] : value +} + +type MongoGlobals = { + collection?: { + updateOne: (filter: Record, update: Record) => Promise<{ modifiedCount?: number }> + } +} + +/** + * MongoDB: rewrites a legacy stored character to its name, once per start (a + * no-op once done). SQL adapters change the column in a migration — see + * TITLE_SEPARATOR_SQL and docs/seo.md. + */ +export async function migrateTitleSeparator(payload: BasePayload, settingsSlug = 'site-settings'): Promise { + if (payload.db.name !== 'mongoose') {return} + const globals = (payload.db as unknown as { globals?: MongoGlobals }).globals + if (!globals?.collection) {return} + try { + for (const [char, name] of Object.entries(NAME_OF_CHAR)) { + const result = await globals.collection.updateOne({ globalType: settingsSlug, titleSeparator: char }, { $set: { titleSeparator: name } }) + if (result.modifiedCount) { + payload.logger.info(`[ipal] Site Settings: title separator '${char}' stored as '${name}' (GraphQL-safe value).`) + } + } + } catch (error) { + payload.logger.error({ err: error, msg: '[ipal] Site Settings: could not migrate the title separator' }) + } +} + +/** + * SQL that rewrites legacy separator characters to names (`direction: 'up'`) or + * back (`'down'`), for a Postgres or SQLite migration. Postgres: the generated + * migration turns the column into text, recreates the enum and casts back — + * insert this right after `SET DATA TYPE text;`, or the cast fails on '|': + * + * ALTER TABLE "site_settings" ALTER COLUMN "title_separator" SET DATA TYPE text; + * ${sql.raw(titleSeparatorSql())} + * + * Table/column default to Payload's names for the plugin's Site Settings. + */ +export function titleSeparatorSql({ + column = 'title_separator', + direction = 'up', + table = 'site_settings', +}: { column?: string; direction?: 'down' | 'up'; table?: string } = {}): string { + const pairs = Object.entries(NAME_OF_CHAR).map(([char, name]) => (direction === 'up' ? [char, name] : [name, char])) + const cases = pairs.map(([from, to]) => `WHEN '${from}' THEN '${to}'`).join(' ') + const from = pairs.map(([f]) => `'${f}'`).join(', ') + return `UPDATE "${table}" SET "${column}" = CASE "${column}" ${cases} ELSE "${column}" END WHERE "${column}" IN (${from});` +} diff --git a/src/plugin.ts b/src/plugin.ts index e234cf5..fc8fd9d 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -33,6 +33,7 @@ import { buildSystemPagesFields } from './modules/pages/index.js' import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo/index.js' import { buildIndexNowHook } from './modules/seo/indexNow.js' import { searchSettingsFields } from './modules/seo/searchSettings.js' +import { migrateTitleSeparator } from './modules/seo/titleSeparator.js' import { applyCollectionOverride } from './modules/shared/collectionOverride.js' import { buildStatsCollection, buildStatsEndpoint } from './modules/stats/index.js' @@ -563,6 +564,7 @@ export const ipalKit = (options: IpalOptions): Plugin => { config.onInit = async (payload) => { if (incomingOnInit) {await incomingOnInit(payload)} await migrateCookieSettingsSaveButton(payload) + await migrateTitleSeparator(payload, settingsSlug) if (adminMeta) {await syncAdminMeta(payload, adminMeta, { nameField: brandFields.nameField, settingsSlug })} payload.logger.info('[ipal] Plugin initialized.') } diff --git a/test/graphqlSchema.test.ts b/test/graphqlSchema.test.ts new file mode 100644 index 0000000..b4084ce --- /dev/null +++ b/test/graphqlSchema.test.ts @@ -0,0 +1,140 @@ +import type { Config, SanitizedConfig } from 'payload' + +import { sqliteAdapter } from '@payloadcms/db-sqlite' +import { lexicalEditor } from '@payloadcms/richtext-lexical' +import { realpathSync } from 'node:fs' +import path from 'node:path' +import { pathToFileURL } from 'node:url' +import { getPayload } from 'payload' +import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest' + +import type { I18nConfig } from '../src/modules/i18n/types.js' + +import { ipalKit } from '../src/plugin.js' +import { buildTestConfig } from './helpers.js' + +vi.mock('server-only', () => ({})) + +/** + * GraphQL is built from every collection and global the plugin adds — select and + * radio option VALUES become enum names, which must match /^[_a-zA-Z][_a-zA-Z0-9]*$/. + * A bad one (e.g. '|') makes /api/graphql answer 500 for the whole site, and the + * admin never notices because it doesn't use GraphQL. This builds the schema from + * the plugin with every module on and validates it. + * + * `@payloadcms/graphql` and `graphql` are loaded next to `@payloadcms/next` — the + * same copies a project's /api/graphql route uses. + */ +async function loadGraphql() { + // pnpm: dependencies of a package sit next to it in .pnpm//node_modules. + const next = realpathSync(path.resolve(import.meta.dirname, '../node_modules/@payloadcms/next')) + const payloadGraphql = realpathSync(path.join(next, '..', 'graphql')) + const graphqlDir = realpathSync(path.join(payloadGraphql, '..', '..', 'graphql')) + const { configToSchema } = (await import(pathToFileURL(path.join(payloadGraphql, 'dist/index.js')).href)) as { + configToSchema: (config: SanitizedConfig) => { schema: unknown } + } + const graphql = (await import(pathToFileURL(path.join(graphqlDir, 'index.js')).href)) as { + validateSchema: (schema: unknown) => readonly { message: string }[] + } + const { formatName } = (await import(pathToFileURL(path.join(payloadGraphql, 'dist/utilities/formatName.js')).href)) as { + formatName: (value: string) => string + } + return { configToSchema, formatName, validateSchema: graphql.validateSchema } +} + +const i18n: I18nConfig = { + defaultLocale: 'pl', + locales: [ + { code: 'pl', label: 'Polski' }, + { code: 'en', label: 'English' }, + ], +} + +const project = (): Omit => + ({ + collections: [ + { slug: 'users', auth: true, fields: [] }, + { slug: 'pages', fields: [{ name: 'title', type: 'text' }, { name: 'slug', type: 'text', localized: true }], versions: { drafts: true } }, + { slug: 'posts', fields: [{ name: 'title', type: 'text' }, { name: 'slug', type: 'text', localized: true }], versions: { drafts: true } }, + { slug: 'media', fields: [], upload: true }, + ], + db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }), + editor: lexicalEditor(), + secret: 'graphql-schema-test', + telemetry: false, + }) as unknown as Config + +const fullConfig = () => + buildTestConfig({ + ...project(), + plugins: [ + ipalKit({ + access: { authCollection: 'users' }, + consentLog: true, + content: { collections: [{ slug: 'posts' }] }, + cookieScanner: { crawl: { serviceUrl: 'http://crawler.test', siteUrl: 'http://site.test', token: 'x' } }, + forms: { emailLayout: true }, + i18n, + indexNow: true, + lightbox: true, + pages: { slug: 'pages' }, + seo: { collections: ['pages', 'posts'] }, + stats: true, + twoFactor: false, + whiteLabel: true, + } as never), + ], + }) + +type AnyField = { blocks?: { fields: AnyField[]; slug: string }[]; fields?: AnyField[]; name?: string; options?: unknown[]; tabs?: { fields: AnyField[] }[]; type: string } + +/** Every select/radio in a field tree, with a readable path. */ +function* optionFields(fields: AnyField[], where: string): Generator<{ field: AnyField; where: string }> { + for (const f of fields) { + const here = f.name ? `${where}.${f.name}` : where + if ((f.type === 'select' || f.type === 'radio') && f.options) {yield { field: f, where: here }} + if (f.fields) {yield* optionFields(f.fields, here)} + for (const tab of f.tabs ?? []) {yield* optionFields(tab.fields, here)} + for (const block of f.blocks ?? []) {yield* optionFields(block.fields, `${here}[${block.slug}]`)} + } +} + +const VALID_NAME = /^[_a-z]\w*$/i + +describe('GraphQL schema of the full plugin config', () => { + let payload: Awaited> + beforeAll(async () => { + payload = await getPayload({ config: fullConfig() }) + }, 60_000) + afterAll(async () => { + await payload?.destroy() + }) + + test('no select/radio value becomes an invalid or duplicate enum name', async () => { + const { formatName } = await loadGraphql() + const problems: string[] = [] + const roots = [ + ...payload.config.collections.map((c) => ({ fields: c.fields as AnyField[], where: c.slug })), + ...payload.config.globals.map((g) => ({ fields: g.fields as AnyField[], where: g.slug })), + ] + for (const root of roots) { + for (const { field, where } of optionFields(root.fields, root.where)) { + const seen = new Map() + for (const option of field.options ?? []) { + const value = typeof option === 'string' ? option : String((option as { value: unknown }).value) + const name = formatName(value) + if (!VALID_NAME.test(name)) {problems.push(`${where}: '${value}' → '${name}'`)} + else if (seen.has(name)) {problems.push(`${where}: '${value}' and '${seen.get(name)}' → '${name}'`)} + seen.set(name, value) + } + } + } + expect(problems).toEqual([]) + }) + + test('/api/graphql schema builds and validates', async () => { + const { configToSchema, validateSchema } = await loadGraphql() + const { schema } = configToSchema(payload.config) + expect(validateSchema(schema).map((e) => e.message)).toEqual([]) + }) +}) diff --git a/test/titleSeparator.test.ts b/test/titleSeparator.test.ts new file mode 100644 index 0000000..d9d39f8 --- /dev/null +++ b/test/titleSeparator.test.ts @@ -0,0 +1,82 @@ +import { describe, expect, test, vi } from 'vitest' + +import { generalFields } from '../src/globals/SiteSettings/fields/general.js' +import { readSiteMetaConfig } from '../src/modules/seo/readSiteMetaConfig.js' +import { + migrateTitleSeparator, + TITLE_SEPARATORS, + titleSeparatorChar, + titleSeparatorName, + titleSeparatorSql, +} from '../src/modules/seo/titleSeparator.js' + +type SelectField = { + defaultValue: string + hooks: { afterRead: ((a: { value: unknown }) => unknown)[]; beforeChange: ((a: { value: unknown }) => unknown)[] } + name: string + options: { value: string }[] +} + +const separatorField = (): SelectField => { + const find = (fields: unknown[]): SelectField | undefined => { + for (const f of fields as { fields?: unknown[]; name?: string }[]) { + if (f.name === 'titleSeparator') {return f as unknown as SelectField} + const inner = f.fields && find(f.fields) + if (inner) {return inner} + } + return undefined + } + return find(generalFields)! +} + +describe('Site Settings → Title separator (GraphQL-safe values)', () => { + test('stored values are names; each maps to its character', () => { + const field = separatorField() + expect(field.defaultValue).toBe('pipe') + expect(field.options.map((o) => o.value)).toEqual(['pipe', 'endash', 'hyphen', 'middot', 'slash']) + expect(field.options.map((o) => titleSeparatorChar(o.value))).toEqual(['|', '–', '-', '·', '/']) + }) + + test('legacy characters (≤ 1.14.4) still work; unknown values are used literally', () => { + for (const char of Object.values(TITLE_SEPARATORS)) {expect(titleSeparatorChar(char)).toBe(char)} + expect(titleSeparatorChar('»')).toBe('»') + expect(titleSeparatorChar('')).toBeUndefined() + expect(titleSeparatorChar(null)).toBeUndefined() + expect(titleSeparatorName('|')).toBe('pipe') + expect(titleSeparatorName('endash')).toBe('endash') + expect(titleSeparatorName('»')).toBe('»') + }) + + test('the field reads and saves a legacy character as its name (no "invalid selection")', () => { + const { hooks } = separatorField() + expect(hooks.afterRead[0]({ value: '·' })).toBe('middot') + expect(hooks.beforeChange[0]({ value: '/' })).toBe('slash') + expect(hooks.beforeChange[0]({ value: 'hyphen' })).toBe('hyphen') + }) + + test('titles use the character, for names and legacy values', async () => { + const read = (titleSeparator: string) => + readSiteMetaConfig({ locale: 'pl', payload: {} as never, settings: { homepage: null, siteName: 'Acme', titleSeparator } }) + expect((await read('endash')).separator).toBe(' – ') + expect((await read('|')).separator).toBe(' | ') + }) + + test('migration SQL maps both ways and leaves other values alone', () => { + expect(titleSeparatorSql()).toBe( + `UPDATE "site_settings" SET "title_separator" = CASE "title_separator" WHEN '–' THEN 'endash' WHEN '-' THEN 'hyphen' WHEN '·' THEN 'middot' WHEN '|' THEN 'pipe' WHEN '/' THEN 'slash' ELSE "title_separator" END WHERE "title_separator" IN ('–', '-', '·', '|', '/');`, + ) + expect(titleSeparatorSql({ direction: 'down', table: 'settings' })).toContain(`UPDATE "settings" SET "title_separator" = CASE "title_separator" WHEN 'endash' THEN '–'`) + }) + + test('MongoDB: legacy character rewritten at start; other adapters untouched', async () => { + const updateOne = vi.fn(async (filter: { titleSeparator: string }) => ({ modifiedCount: filter.titleSeparator === '|' ? 1 : 0 })) + const logger = { error: vi.fn(), info: vi.fn() } + await migrateTitleSeparator({ db: { name: 'mongoose', globals: { collection: { updateOne } } }, logger } as never) + expect(updateOne).toHaveBeenCalledWith({ globalType: 'site-settings', titleSeparator: '|' }, { $set: { titleSeparator: 'pipe' } }) + expect(logger.info).toHaveBeenCalledOnce() + + const sql = vi.fn() + await migrateTitleSeparator({ db: { name: 'postgres', globals: { collection: { updateOne: sql } } }, logger } as never) + expect(sql).not.toHaveBeenCalled() + }) +})