Compare commits

..
5 Commits
Author SHA1 Message Date
radoslaw.smolinski f88c342be5 1.9.2
CI / check (push) Canceled after 0s
2026-10-16 11:52:43 +02:00
radoslaw.smolinskiandClaude Opus 5.5 293cd9a541 Merge 1.9.2: import instead of code
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 11:52:42 +02:00
radoslaw.smolinskiandClaude Opus 5.5 81e864bde9 Docs for 1.9.2: import instead of code; docs↔code consistency test; audit accepts one-line routes
- AGENT.md: §7 full capability catalog (need → import), §0b/§3/§6 on RenderForm, SiteProviders,
  createPageRoute, re-exported routes, plugin section fields, resolveLink/resolveNav
- PROGRAMISTA §2.4, §2.7–2.8 rewritten; §6 items 28–33 (28: FormRenderer leaked the Emails tab)
- forms, links, blocks, pages, consent, turnstile, notifications, seo, mcp, i18n, deployment docs
- ipal-form: RenderForm block, formClasses, CustomForm example (FormRenderer template removed),
  seed template handles steps and option labels per language
- ipal-nav, ipal-block, ipal-setup, ipal-upgrade, ipal-seo-check, ipal-consent-check, vibe.md
- ipal-audit: re-export routes and SiteProviders satisfy the mandatory set; flags form-engine copies,
  project section fields / navigation, server entries in client components
- test/docsConsistency: docs imports exist in code; every public export is documented
- CHANGELOG 1.9.2

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 11:52:29 +02:00
radoslaw.smolinskiandClaude Opus 5.5 412bf953a8 Import instead of code: panel forms (steps, choice lists, dates), layout, page route, GEO routes, links, section fields
- Forms: step and checkboxGroup field types (radio, date on), server validation for them,
  useBuilderForm (logic) + BuilderForm (unstyled default) + RenderForm (/rsc: rich text,
  bound action, public part of the form only — the Emails tab never reaches the browser)
- Notifications: next / back / stepOf texts
- createContentHelpers: getSiteShell, getFormTexts, getLinkOptions, resolveLink, resolveNav,
  resolvePageRedirect, one-line route handlers (llms, llms-full, md, mcp, health, indexnow, manifest)
- /rsc: SiteProviders, createPageRoute, createNotFoundPage
- resolveLink / resolveNav / homeSlugFrom, buildSectionHeaderField / buildSectionSettingsField
- Dev sandbox frontend built on these imports; tests (unit + real Payload)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 11:32:46 +02:00
radoslaw.smolinskiandClaude Opus 5.5 0cfd846dd1 Changelog: history back to 1.7.4, keep at least 20 versions
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 10:59:38 +02:00
77 changed files with 3280 additions and 618 deletions
@@ -0,0 +1,18 @@
import { notFound, permanentRedirect } from 'next/navigation.js'
import { createPageRoute } from '@intecion/ipal-kit/rsc'
import { FormBlock } from '../../../../blocks/FormBlock.js'
import * as content from '../../../../lib/content.js'
import { sendForm } from '../actions.js'
export const revalidate = 3600
const route = createPageRoute(content, {
blockProps: async ({ locale }) => ({ formTexts: await content.getFormTexts(locale), sendForm }),
blocks: { formBlock: FormBlock },
notFound,
permanentRedirect,
})
export default route.Page
export const generateMetadata = route.generateMetadata
export const generateStaticParams = route.generateStaticParams
+7
View File
@@ -0,0 +1,7 @@
'use server'
import { headers } from 'next/headers.js'
import { createSubmitAction } from '@intecion/ipal-kit/server'
import { getCachedPayload } from '../../../lib/content.js'
export const sendForm = createSubmitAction({ getCachedPayload, headers })
+22
View File
@@ -0,0 +1,22 @@
import { notFound } from 'next/navigation.js'
import { CookieBanner } from '@intecion/ipal-kit/client'
import { SiteProviders } from '@intecion/ipal-kit/rsc'
import { getConfiguredLocales, getSiteShell } from '../../../lib/content.js'
import './styles.css'
type Props = { children: React.ReactNode; params: Promise<{ locale: string }> }
export default async function LocaleLayout({ children, params }: Props) {
const { locale } = await params
if (!(await getConfiguredLocales()).includes(locale)) notFound()
return (
<html lang={locale}>
<body>
<SiteProviders banner={<CookieBanner equalChoice />} logEndpoint="/api/ipal/consent" shell={await getSiteShell(locale)}>
<main>{children}</main>
</SiteProviders>
</body>
</html>
)
}
@@ -0,0 +1,6 @@
import { createNotFoundPage } from '@intecion/ipal-kit/rsc'
import { FormBlock } from '../../../blocks/FormBlock.js'
import * as content from '../../../lib/content.js'
export default createNotFoundPage(content, { blocks: { formBlock: FormBlock }, fallback: <h1>404</h1> })
+10
View File
@@ -0,0 +1,10 @@
/* Sandbox look — in a project this is the design system. */
body { font-family: system-ui, sans-serif; margin: 0 auto; max-width: 40rem; padding: 1rem; }
.grid { display: grid; gap: 1rem; grid-template-columns: repeat(2, 1fr); }
.field { grid-column: span 2; } .half { grid-column: span 1; }
.label, legend { display: block; font-weight: 600; margin-bottom: .25rem; }
.input { border: 1px solid #999; border-radius: 6px; box-sizing: border-box; padding: .5rem; width: 100%; }
.choices { border: 0; display: grid; gap: .25rem; margin: 0; padding: 0; } .choice { display: flex; gap: .5rem; }
.error { color: #b00020; } .progress { color: #555; } .step-title { font-size: 1.25rem; font-weight: 700; }
.actions { display: flex; gap: .5rem; margin-top: 1rem; } .btn { background: #111; border: 0; border-radius: 6px; color: #fff; padding: .6rem 1rem; }
.btn-secondary { background: #ddd; color: #111; } .success { background: #e7f7ec; padding: 1rem; }
+2
View File
@@ -0,0 +1,2 @@
export { mcpGET as GET, mcpPOST as POST } from '../../../lib/content.js'
export const dynamic = 'force-dynamic'
+2
View File
@@ -0,0 +1,2 @@
export { llmsRoute as GET } from '../../lib/content.js'
export const dynamic = 'force-dynamic'
+16
View File
@@ -0,0 +1,16 @@
import type { FormNotificationTexts } from '@intecion/ipal-kit'
import { RenderForm, type SendFormAction } from '@intecion/ipal-kit/rsc'
// Classes set once per project — here plain names the sandbox CSS styles.
const formClasses = {
actions: 'actions', back: 'btn btn-secondary', choice: 'choice', choices: 'choices', error: 'error', field: 'field',
fieldHalf: 'half', fields: 'grid', form: 'form', formError: 'error', input: 'input', label: 'label', progress: 'progress',
select: 'input', stepTitle: 'step-title', submit: 'btn', success: 'success', textarea: 'input',
}
type Props = { form?: unknown; formTexts?: FormNotificationTexts; locale: string; sendForm?: SendFormAction }
export function FormBlock({ form, formTexts, locale, sendForm }: Props) {
if (!formTexts || !sendForm) return null
return <RenderForm action={sendForm} classNames={formClasses} form={form as never} locale={locale} requiredMark=" *" texts={formTexts} />
}
+7
View File
@@ -0,0 +1,7 @@
export const i18nConfig = {
defaultLocale: 'pl',
locales: [
{ code: 'pl', label: 'Polski' },
{ code: 'en', label: 'English' },
],
} as const
+11
View File
@@ -0,0 +1,11 @@
// Sandbox data layer — the same one line every project has (PROGRAMISTA §2.7).
import config from '@payload-config'
import { createContentHelpers } from '@intecion/ipal-kit'
import { i18nConfig } from '../i18n.config.js'
export const {
generatePageMetadata, generateStaticParams, getCachedPayload, getConfiguredLocales, getFormTexts, getLinkOptions,
getNotFoundPage, getPageJsonLd, getSettings, getSiteShell, healthRoute, i18n, llmsRoute, mcpGET, mcpPOST,
resolveNav, resolvePageRedirect, resolveRoute,
} = createContentHelpers({ baseUrl: 'http://localhost:3000', config, i18n: i18nConfig, mcp: { serverName: 'ipal-sandbox' } })
+239 -40
View File
@@ -73,6 +73,7 @@ export interface Config {
media: Media;
forms: Form;
'form-submissions': FormSubmission;
'consent-records': ConsentRecord;
'payload-kv': PayloadKv;
'payload-locked-documents': PayloadLockedDocument;
'payload-preferences': PayloadPreference;
@@ -86,6 +87,7 @@ export interface Config {
media: MediaSelect<false> | MediaSelect<true>;
forms: FormsSelect<false> | FormsSelect<true>;
'form-submissions': FormSubmissionsSelect<false> | FormSubmissionsSelect<true>;
'consent-records': ConsentRecordsSelect<false> | ConsentRecordsSelect<true>;
'payload-kv': PayloadKvSelect<false> | PayloadKvSelect<true>;
'payload-locked-documents': PayloadLockedDocumentsSelect<false> | PayloadLockedDocumentsSelect<true>;
'payload-preferences': PayloadPreferencesSelect<false> | PayloadPreferencesSelect<true>;
@@ -172,46 +174,15 @@ export interface User {
export interface Page {
id: number;
title?: string | null;
meta?: {
title?: string | null;
description?: string | null;
/**
* Maximum upload file size: 12MB. Recommended file size for images is <500KB.
*/
image?: (number | null) | Media;
/**
* Use this exact text as the browser-tab title — no site name, no separator. Leave empty to compose the title automatically.
*/
titleOverride?: string | null;
};
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "media".
*/
export interface Media {
id: number;
updatedAt: string;
createdAt: string;
url?: string | null;
thumbnailURL?: string | null;
filename?: string | null;
mimeType?: string | null;
filesize?: number | null;
width?: number | null;
height?: number | null;
focalX?: number | null;
focalY?: number | null;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "posts".
*/
export interface Post {
id: number;
title?: string | null;
slug?: string | null;
layout?:
| {
form?: (number | null) | Form;
id?: string | null;
blockName?: string | null;
blockType: 'formBlock';
}[]
| null;
meta?: {
title?: string | null;
description?: string | null;
@@ -341,6 +312,70 @@ export interface Form {
blockName?: string | null;
blockType: 'textarea';
}
| {
/**
* Technical name, e.g. "services" — no spaces.
*/
name: string;
label?: string | null;
width?: number | null;
required?: boolean | null;
options?:
| {
label: string;
value: string;
id?: string | null;
}[]
| null;
/**
* Empty = no minimum (Required = at least one).
*/
minSelected?: number | null;
/**
* Empty = no limit.
*/
maxSelected?: number | null;
id?: string | null;
blockName?: string | null;
blockType: 'checkboxGroup';
}
| {
name: string;
label?: string | null;
width?: number | null;
required?: boolean | null;
defaultValue?: string | null;
id?: string | null;
blockName?: string | null;
blockType: 'date';
}
| {
name: string;
label?: string | null;
width?: number | null;
defaultValue?: string | null;
options?:
| {
label: string;
value: string;
id?: string | null;
}[]
| null;
required?: boolean | null;
id?: string | null;
blockName?: string | null;
blockType: 'radio';
}
| {
/**
* Starts a new step: the fields below it (until the next Step) are shown together, with Next / Back buttons. Leave the form without Steps for a single-screen form.
*/
title?: string | null;
description?: string | null;
id?: string | null;
blockName?: string | null;
blockType: 'step';
}
)[]
| null;
submitButtonLabel?: string | null;
@@ -392,6 +427,46 @@ export interface Form {
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "media".
*/
export interface Media {
id: number;
updatedAt: string;
createdAt: string;
url?: string | null;
thumbnailURL?: string | null;
filename?: string | null;
mimeType?: string | null;
filesize?: number | null;
width?: number | null;
height?: number | null;
focalX?: number | null;
focalY?: number | null;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "posts".
*/
export interface Post {
id: number;
title?: string | null;
meta?: {
title?: string | null;
description?: string | null;
/**
* Maximum upload file size: 12MB. Recommended file size for images is <500KB.
*/
image?: (number | null) | Media;
/**
* Use this exact text as the browser-tab title — no site name, no separator. Leave empty to compose the title automatically.
*/
titleOverride?: string | null;
};
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "form-submissions".
@@ -409,6 +484,25 @@ export interface FormSubmission {
updatedAt: string;
createdAt: string;
}
/**
* Proof of cookie consent: random id (also in the visitor cookie), choices, policy version, time. No personal data.
*
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "consent-records".
*/
export interface ConsentRecord {
id: number;
consentId: string;
version: number;
choices?: {
necessary?: boolean | null;
functional?: boolean | null;
analytics?: boolean | null;
marketing?: boolean | null;
};
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "payload-kv".
@@ -456,6 +550,10 @@ export interface PayloadLockedDocument {
| ({
relationTo: 'form-submissions';
value: number | FormSubmission;
} | null)
| ({
relationTo: 'consent-records';
value: number | ConsentRecord;
} | null);
globalSlug?: string | null;
user: {
@@ -529,6 +627,18 @@ export interface UsersSelect<T extends boolean = true> {
*/
export interface PagesSelect<T extends boolean = true> {
title?: T;
slug?: T;
layout?:
| T
| {
formBlock?:
| T
| {
form?: T;
id?: T;
blockName?: T;
};
};
meta?:
| T
| {
@@ -683,6 +793,62 @@ export interface FormsSelect<T extends boolean = true> {
id?: T;
blockName?: T;
};
checkboxGroup?:
| T
| {
name?: T;
label?: T;
width?: T;
required?: T;
options?:
| T
| {
label?: T;
value?: T;
id?: T;
};
minSelected?: T;
maxSelected?: T;
id?: T;
blockName?: T;
};
date?:
| T
| {
name?: T;
label?: T;
width?: T;
required?: T;
defaultValue?: T;
id?: T;
blockName?: T;
};
radio?:
| T
| {
name?: T;
label?: T;
width?: T;
defaultValue?: T;
options?:
| T
| {
label?: T;
value?: T;
id?: T;
};
required?: T;
id?: T;
blockName?: T;
};
step?:
| T
| {
title?: T;
description?: T;
id?: T;
blockName?: T;
};
};
submitButtonLabel?: T;
confirmationType?: T;
@@ -723,6 +889,24 @@ export interface FormSubmissionsSelect<T extends boolean = true> {
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "consent-records_select".
*/
export interface ConsentRecordsSelect<T extends boolean = true> {
consentId?: T;
version?: T;
choices?:
| T
| {
necessary?: T;
functional?: T;
analytics?: T;
marketing?: T;
};
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "payload-kv_select".
@@ -986,6 +1170,18 @@ export interface Notification {
*/
consent?: string | null;
notFound?: string | null;
/**
* Step-by-step forms: button to the next step.
*/
next?: string | null;
/**
* Step-by-step forms: button to the previous step.
*/
back?: string | null;
/**
* Progress — {current} and {total} are replaced.
*/
stepOf?: string | null;
};
updatedAt?: string | null;
createdAt?: string | null;
@@ -1112,6 +1308,9 @@ export interface NotificationsSelect<T extends boolean = true> {
validation?: T;
consent?: T;
notFound?: T;
next?: T;
back?: T;
stepOf?: T;
};
updatedAt?: T;
createdAt?: T;
+11 -8
View File
@@ -7,6 +7,7 @@ import sharp from 'sharp'
import { fileURLToPath } from 'url'
import { testEmailAdapter } from './helpers/testEmailAdapter.js'
import { i18nConfig } from './i18n.config.js'
import { seed } from './seed.js'
const filename = fileURLToPath(import.meta.url)
@@ -30,7 +31,15 @@ export default buildConfig({
},
{
slug: 'pages',
fields: [{ name: 'title', type: 'text' }],
fields: [
{ name: 'title', type: 'text', localized: true },
{ name: 'slug', type: 'text', index: true, localized: true },
{
name: 'layout',
type: 'blocks',
blocks: [{ slug: 'formBlock', fields: [{ name: 'form', type: 'relationship', relationTo: 'forms' }] }],
},
],
},
{
slug: 'posts',
@@ -56,13 +65,7 @@ export default buildConfig({
plugins: [
ipalKit({
access: { authCollection: 'users' },
i18n: {
defaultLocale: 'pl',
locales: [
{ code: 'pl', label: 'Polski' },
{ code: 'en', label: 'English' },
],
},
i18n: i18nConfig,
consentLog: true,
forms: {},
seo: { collections: ['posts', 'pages'] },
+46
View File
@@ -22,4 +22,50 @@ export const seed = async (payload: Payload) => {
},
})
}
await seedContactPage(payload)
}
const text = (t: string) => ({
root: {
children: [{ children: [{ detail: 0, format: 0, mode: 'normal', style: '', text: t, type: 'text', version: 1 }], direction: null, format: '', indent: 0, type: 'paragraph', version: 1 }],
direction: null,
format: '',
indent: 0,
type: 'root',
version: 1,
},
})
/** A step-by-step quote form on /pl/kontakt — exercises RenderForm, steps, choice lists, dates. */
async function seedContactPage(payload: Payload) {
const { totalDocs } = await payload.count({ collection: 'pages', where: { slug: { equals: 'kontakt' } } })
if (totalDocs) {return}
const form = await payload.create({
collection: 'forms',
data: {
confirmationMessage: text('Dziękujemy! Odezwiemy się w ciągu 24 godzin.'),
confirmationType: 'message',
fields: [
{ blockType: 'step', title: 'Kontakt' },
{ name: 'name', blockType: 'text', label: 'Imię i nazwisko', required: true, width: 50 },
{ name: 'email', blockType: 'email', label: 'E-mail', required: true, width: 50 },
{ blockType: 'step', description: 'Zaznacz, czego potrzebujesz.', title: 'Projekt' },
{ name: 'services', blockType: 'checkboxGroup', label: 'Usługi', options: [{ label: 'Strona WWW', value: 'www' }, { label: 'SEO', value: 'seo' }, { label: 'Kampanie', value: 'ads' }], required: true },
{ name: 'budget', blockType: 'radio', label: 'Budżet', options: [{ label: 'do 10 tys.', value: 's' }, { label: 'powyżej 10 tys.', value: 'l' }], required: true },
{ name: 'deadline', blockType: 'date', label: 'Termin' },
{ blockType: 'message', message: text('Dane przetwarzamy wyłącznie w celu przygotowania wyceny.') },
{ name: 'consent', blockType: 'checkbox', label: 'Zgadzam się na przetwarzanie danych.', required: true },
],
submitButtonLabel: 'Wyślij zapytanie',
title: 'Wycena',
} as never,
})
const page = await payload.create({
collection: 'pages',
data: { layout: [{ blockType: 'formBlock', form: form.id }], slug: 'kontakt', title: 'Kontakt' } as never,
})
await payload.updateGlobal({ slug: 'site-settings' as never, data: { siteName: 'Sandbox' } as never })
payload.logger.info(`[seed] /pl/kontakt (page ${page.id}, form ${form.id})`)
}
+242
View File
@@ -3,6 +3,62 @@
Zmiany ważne dla projektów na ipal-kit. Jak przejść na nową wersję: skill
**ipal-upgrade** i [PROGRAMISTA.md §6](./dev/PROGRAMISTA.md).
Trzymamy tu co najmniej **20 ostatnich wersji** — przy aktualizacji projektu o kilka
wersji naraz przejdź po kolei wszystkie sekcje „Wymaga zmian w projekcie” od
wersji, którą masz. Nowe wydanie = nowa sekcja na górze; najstarsze usuwamy
dopiero powyżej 20.
## 1.9.2
Import zamiast kodu: to, co każdy projekt pisał tak samo, jest w pluginie — logika i
szkielet. Wygląd zostaje w projekcie (klasy, własny markup na hookach). Wszystko opcjonalne:
dotychczasowy kod projektów działa bez zmian.
### Wymaga zmian w projekcie
- **Bezpieczeństwo — własny `FormRenderer`:** szablon z `ipal-form` przekazywał do komponentu
klienckiego cały dokument formularza. Local API czyta z `overrideAccess`, więc w HTML/RSC
lądowała zakładka **Emails** (adresy firmy, szablony). Zamień blok na `<RenderForm>` (niżej) albo
przekazuj do klienta tylko pola, etykiety i potwierdzenie. PROGRAMISTA §6 poz. 28.
- **Postgres:** `pnpm payload migrate:create` — nowe typy pól formularza (Step, Checkbox group,
Radio, Date) i teksty `next` / `back` / `stepOf` w Notifications. MongoDB/SQLite (push) bez zmian.
### Nowe
- **Formularze z panelu w jednej linii:** `<RenderForm form action locale texts classNames>` (`/rsc`) —
rich text, wiązanie akcji, redirect, tylko publiczna część formularza w przeglądarce. Pod spodem
`BuilderForm` (`/client`, czysty dostępny HTML bez stylów, `classNames`, `renderField`) i
`useBuilderForm` (cała logika dla własnego markupu). Szablony: `ipal-form/resources/FormBlock.tsx`,
`formClasses.ts`, `CustomForm.example.tsx` (stary `FormRenderer.tsx` usunięty).
- **Formularze krokowe i listy wyboru:** w panelu bloki **Step** (podział na ekrany, tytuł i opis per
język), **Checkbox group** (wiele wyborów, min/max), **Radio**, **Date** — domyślnie włączone
(`forms.fields.<typ>: false` wyłącza). Serwer sprawdza wartości z panelu, liczbę wyborów i daty;
wybory zapisane czytelnie („www, seo”). Dalej waliduje bieżący krok, błąd z serwera wraca na krok z
polem, fokus na nowym kroku. Teksty: Notifications → `next`, `back`, `stepOf`.
- **Layout:** `getSiteShell(locale)` (zgoda, analityka, klucz Turnstile, teksty formularzy, JSON-LD
WebSite + Organization, Site Settings) + `<SiteProviders shell>` (`/rsc`) — providery, baner,
przycisk cookies, Analytics, JSON-LD i preconnect w dobrej kolejności; każda część do podmiany
albo wyłączenia. `siteJsonLd` w `createContentHelpers` dla LocalBusiness.
- **Strona i 404:** `createPageRoute(content, { blocks, notFound, permanentRedirect, blockProps, render })`
i `createNotFoundPage(content, { blocks, fallback })` (`/rsc`).
- **Trasy z jednej linii:** `createContentHelpers` zwraca `llmsRoute`, `llmsFullRoute`,
`markdownRoute`, `mcpGET`/`mcpPOST`, `healthRoute`, `indexNowKeyRoute`, `manifest`; opcje
`summaryField`, `mcp`, `markdown`, `redirectCollections` raz w `lib/content.ts`.
- **Linki i menu:** `resolveLink` (href, `internal`, `targetProps`, `appearance`), `resolveNav`
(dowolna głębokość, martwe linki pominięte), `homeSlugFrom`; w `lib/content`: `resolveLink(link, locale)`,
`resolveNav(items, locale)`, `getLinkOptions`, `getHomeSlug`, `resolvePageRedirect`, `getFormTexts`.
- **Pola sekcji:** `buildSectionHeaderField`, `buildSectionSettingsField({ backgrounds, anchor, fields })`
— ten sam kształt danych co dawne `src/fields/section*.ts` (bez migracji).
- `useOptionalTurnstile()` — bez providera zwraca `enabled: false` zamiast rzucać.
### Dokumentacja i audyt
- AGENT.md §7 to pełny katalog „potrzeba → import”; §0b, §3, §6 i PROGRAMISTA §2.7–2.8, §6
(poz. 28–33) opisują nowy sposób; skille ipal-form, ipal-nav, ipal-block, ipal-setup, ipal-upgrade
zaktualizowane.
- `ipal-audit` przyjmuje trasy-re-eksporty i `SiteProviders`; nowe reguły: kopia silnika formularza,
`src/fields/section*.ts` / `lib/navigation.ts` (WARNING), import roota / `/rsc` / `/server` w
komponencie klienckim (ERROR).
- Test `docsConsistency`: każdy import z dokumentacji istnieje w kodzie, każdy publiczny eksport jest opisany.
- Sandbox (`dev/`) ma front zbudowany na tych importach (formularz krokowy na `/pl/kontakt`).
## 1.9.1
### Wymaga zmian w projekcie
@@ -93,3 +149,189 @@ Zmiany ważne dla projektów na ipal-kit. Jak przejść na nową wersję: skill
przy instalacji z gita. CI w `.gitea/workflows/ci.yml`.
- 79 testów (vitest), w tym integracyjne na prawdziwym Payloadzie (SQLite w pamięci).
- `pnpm typecheck`, `pnpm lint` (0 błędów), `pnpm test:int`.
## 1.8.14
### Wymaga zmian w projekcie
- **2FA: w Next `twoFactor.plugin` trzeba wstrzyknąć** (`plugin: payloadTotp`).
`serverExternalPackages` nie jest obejściem — pakiet importuje własne `.css`,
którego Node nie załaduje. Usuń wpis z `next.config` i adapter z rzutowaniem.
### Poprawki
- `collection` w typie 2FA to `CollectionSlug` (wcześniej `string`) —
`plugin: payloadTotp` przechodzi typecheck bez rzutowania (`TS2322`).
- Paczka publikuje `bin` — działa `ipal-skills`.
## 1.8.13
### Nowe
- **Status wysyłki maili w panelu:** `mailAdapter()` zapisuje wynik w Site
Integrations; błąd → alert na dashboardzie i baner w zakładce SMTP. Formularz
działa dalej (zgłoszenie zapisane). Po aktualizacji: `generate:importmap`,
Postgres: `migrate:create`.
- Formularze w panelu w grupie **Forms** z etykietami (`forms.adminGroup`);
Notifications w grupie Settings — bez nadpisań w projekcie.
### Wymaga zmian w projekcie
- **`POST /api/form-submissions` zamknięty dla anonimów** (403). Front wysyła przez
server action + `submitForm` (skill `ipal-form`). Świadomie publiczny REST →
`formSubmissionOverrides.access.create`.
## 1.8.12
### Nowe
- **Turnstile: awaria po naszej stronie nie blokuje formularzy.** `checkTurnstile`
(`/server`) rozróżnia `pass` / `reject` (zły token odwiedzającego) / `degraded`
(brak lub zły sekret, Cloudflare nieosiągalny). `degraded` → zgłoszenie przyjęte,
alert na dashboardzie (`IntegrationAlerts`) i baner w Site Integrations →
Turnstile. Twardo: `submitForm({ turnstileOnConfigError: 'reject' })`.
- Sekret Turnstile z panelu albo env `TURNSTILE_SECRET_KEY`; przyczyna odrzucenia
w logu serwera. `remoteip` domyślnie nie jest wysyłany (`sendRemoteIp: true`).
- Po aktualizacji: `generate:importmap`, Postgres: `migrate:create` (`turnstileStatus`).
## 1.8.11
### Nowe
- Limit zapytań na IP: wyszukiwarka (`createSearchRoute`, 120/min) i MCP
(`createMcpRoute`, 60 wiadomości/min, batch maks. 10) → `429` z `Retry-After`.
`rateLimit: { max, windowMs }` albo `false` (limiter z przodu, np. Cloudflare WAF).
- Wspólny moduł limitera (`shared/rateLimit`) dla formularzy, wyszukiwarki i MCP.
## 1.8.10
### Zmiany
- Nagłówek stylowanej sitemapy to stałe „XML Sitemap” (bez nazwy strony z Site
Settings); usunięta opcja `siteNameField`. Własny tytuł: `sitemapStyle: { title }`.
## 1.8.9
### Nowe
- **`@intecion/ipal-kit/env`** — walidacja env bez Payload i Node, bezpieczna w
`instrumentation.ts` (root paczki wywracał Edge/Turbopack).
- **`fluid.css`** — płynna skala typografii i odstępów 360→1280 px (same zmienne,
opt-in, mapowanie w `@theme`).
- `R2_PUBLIC_URL` poza produkcją może być ścieżką (`/media`) — prefiksowana
`NEXT_PUBLIC_SERVER_URL`; CSP nie dopisuje jej do `img-src`.
- `ipal-audit`: `html-check.mjs` — inline JSON-LD bez escapowania `<` = ERROR (XSS).
### Poprawki
- `createSitemapRouteHandler` wymaga `req` — Next 16 sprawdza typ pierwszego
argumentu route handlera (`Request | undefined` wywracał build).
## 1.8.8
- Przywrócony opcjonalny `req` w handlerze sitemapy (cofnięte w 1.8.9).
## 1.8.7
- Poprawki typów `routeHandlers` (handler sitemapy).
## 1.8.6
### Poprawki
- `buildLinkField` importował `src/…` zamiast ścieżki względnej — błąd w projekcie.
## 1.8.5
### Nowe
- **`sitemapRoute`** z `createContentHelpers`: XML dla crawlerów, a w przeglądarce
wygląd serwowany przez plugin (`/sitemap.xml?style`, CSS na XML, nie XSLT).
`sitemapStyle: { accent, credit, title } | false`.
### Wymaga zmian w projekcie
- Jedna sitemapa: `app/sitemap.xml/route.ts` (`export { sitemapRoute as GET }`);
usuń `app/sitemap.ts` i `public/sitemap.css` (`ipal-audit` to zgłasza).
## 1.8.4
### Nowe
- **`rowLabel()`** (`/admin`) — wiersze tablic w panelu pokazują treść („Kontakt”)
zamiast „Item 01”. Po dodaniu: `generate:importmap`.
- **`buildOptimizeUploadHook`** — optymalizacja obrazów przy uploadzie.
- Skille agenta: `ipal-site` (strona od briefu do raportu), seed treści, `ipal-upgrade` i inne.
- Baner cookies: atrybuty `data-ipal` na przyciskach (testy), etykiety z tekstów panelu.
## 1.8.3
### Nowe
- **Moduł Links:** `buildLinkField`, `buildLinksField`, `resolveLinkHref` — link do
strony / URL / pliku, przyciski sekcji jako tablica (zamiast `cta1`, `cta2`).
- `createContentHelpers`: `generatePageMetadata` (współdzieli cache z trasą) i opcja
`robots`; jeden odczyt Site Settings na język na żądanie.
- Szablony kodu sekcji i nawigacji dla agenta (`ipal-block`, `ipal-nav`).
## 1.8.2
### Poprawki
- Brakujący eksport `LocaleView` w `/client`.
## 1.8.1
### Poprawki
- Przywrócone zmiany z 1.7.14, które wydanie 1.8.0 przypadkiem cofnęło
(`LocaleView`, 404 bez `headers()`, poprawki R2). **Nie używaj 1.8.0.**
## 1.8.0
- Wydanie wadliwe: cofało zmiany z 1.7.14 — zaktualizuj do 1.8.1 lub nowszej.
- Dokumentacja agenta przeniesiona do `docs/agent/AGENT.md` + skille.
## 1.7.14
### Wymaga zmian w projekcie
- **`not-found.tsx` bez `headers()`** — Next 16 zamieniał stronę SSG/ISR na
dynamiczną. Serwer renderuje 404 dla każdego języka, `<LocaleView>` wybiera
wersję z URL (pages.md).
### Poprawki
- `buildR2Storage`: poprawki konfiguracji R2.
- Skille dla agentów (`ipal-audit` i inne).
## 1.7.12
### Nowe
- Link do polityki prywatności w banerze cookies brany automatycznie z Site
Settings → System Pages; tekst linku w panelu (`privacyLinkLabel`, per język).
Stare `privacyPolicy.label` w kodzie — przestarzałe.
- Nowa struktura dokumentacji: `docs/dev/PROGRAMISTA.md`, AGENT.md, `vibe.md`.
## 1.7.10
### Poprawki
- White-label: branding czyta Site Settings przez `payload` przekazany przez Payload
(bez `import('@payload-config')`, którego Next nie bundlował); nazwa
zlokalizowana wg języka panelu.
## 1.7.9
### Nowe
- `<Analytics defer>` — tagi ładują się przy pierwszej interakcji albo po
`deferTimeoutMs` (domyślnie 3500 ms) od `load`; Consent Mode bez zmian.
- Eksport loaderów `loadMetaPixel`, `loadClarity`, `loadLinkedIn`, `loadTikTok`.
## 1.7.8
### Nowe
- **Meta Pixel, Microsoft Clarity, LinkedIn Insight, TikTok Pixel** w Site
Integrations — ładowane dopiero po zgodzie na właściwą kategorię.
- Strona 404 z panelu (Site Settings → System Pages, `resolveNotFoundPage`).
### Wymaga zmian w projekcie
- `<Analytics>` musi być wewnątrz `<ConsentProvider>`.
## 1.7.7
### Bezpieczeństwo
- `/api/health` i MCP nie zwracają treści błędów (host bazy, schemat) — tylko
ogólny komunikat; szczegóły w logu serwera.
## 1.7.6
### Poprawki
- **noindex:** pole `buildNoindexField` jest top-level (`doc.noindex`) — wcześniejszy
zapis do `meta.noindex` był wycinany przez plugin-seo, więc strony noindex
trafiały do sitemapy. Sitemap, llms.txt, wyszukiwarka i metadata czytają `noindex`.
## 1.7.4
### Nowe
- 2FA: `twoFactor.plugin` — wstrzyknięcie `payloadTotp` zamiast dynamicznego importu.
- White-label: kredyt „Technology supported by Intecion.com” pod nawigacją i na
ekranie logowania; większe logo na logowaniu.
+130 -67
View File
@@ -52,20 +52,20 @@ strona), **P** = test w panelu. Pełny kod: PROGRAMISTA.md §2.
| # | Obszar | Co musi być (plik) | API pluginu | Kontrola |
|---|---|---|---|---|
| 1 | i18n + routing | `src/proxy.ts`, `[locale]/[[...slug]]/page.tsx` z ISR + `generateStaticParams`, `not-found.tsx` | `createProxy`, `createContentHelpers`, `resolveRoute`, `resolveRedirect` | A, S |
| 1 | i18n + routing | `src/proxy.ts`, `[locale]/[[...slug]]/page.tsx` = `createPageRoute(content, {…})` + literał `revalidate`, `not-found.tsx` = `createNotFoundPage(content, {…})` | `createProxy`, `createContentHelpers`, `createPageRoute`, `createNotFoundPage` (`/rsc`) | A, S |
| 2 | **SEO** — meta | `generateMetadata` w każdej trasie stron; favicon i OG z Site Settings; `htmlLimitedBots` w `next.config.ts`; tab SEO + `buildNoindexField` w Pages | `generatePageMetadata`, `buildIconsMetadata`, `buildNoindexField` | A, S |
| 3 | **SEO** — mapy | `src/app/sitemap.xml/route.ts`, `src/app/robots.ts`, `src/app/manifest.ts` (wszystkie z `force-dynamic` poza robots) | `sitemapRoute`, `robots`, `createManifestHandler` | A, S |
| 4 | **SEO** — dane strukturalne | layout: `<JsonLdGraph>` z `WebSite` + `Organization` (`sameAs: sameAsUrls(settings)`) lub `LocalBusiness` (`type`, godziny tekstem z panelu → `formatOpeningHours`) + nawigacja `buildNavigationJsonLd(header)`; strona: `<JsonLdGraph schemas={await getPageJsonLd(locale, slug, { faq })} />` (WebPage/BlogPosting, okruszki, FAQ) | `build*JsonLd`, `getPageJsonLd`, `JsonLdGraph` (`/rsc`) | A, S |
| 5 | **GEO** — llms | `src/app/llms.txt/route.ts` i `src/app/llms-full.txt/route.ts` (`full: true`); pole `buildSummaryField()` w Pages, `summaryField: 'aiSummary'` w trasach AI | `createLlmsTxtRoute`, `buildSummaryField` | A, S |
| 6 | **GEO** — Markdown | `src/app/md/[locale]/[[...slug]]/route.ts` = `export const { GET } = createMarkdownRoute({…})`; `createContentHelpers({ markdownAlternate: true })` (link w `<head>`); `createProxy(…, { NextResponse, markdown: true })` (bez tego `/md/…` dostaje redirect na język) | `createMarkdownRoute`, `markdownAlternate`, `createProxy({ markdown })` | A, S |
| 7 | **GEO** — MCP | `src/app/api/mcp/route.ts` (publiczny — AI przegląda stronę: `get_site_info`, `list_pages`, `search_content`, `get_page`) | `createMcpRoute` | A, S |
| 8 | **GEO** — boty AI + IndexNow | robots **wpuszcza** boty AI (domyślne `aiBots: 'allow'`; blokada tylko z decyzji klienta); `ipalKit({ indexNow: true })` + `src/app/indexnow-key.txt/route.ts` (publikacja → Bing/ChatGPT Search w minuty) | `buildRobots`, `createIndexNowKeyRoute` | A, S |
| 3 | **SEO** — mapy | `src/app/sitemap.xml/route.ts`, `src/app/robots.ts`, `src/app/manifest.ts` — każdy to re-eksport z `lib/content` (`sitemapRoute`, `robots`, `manifest`) + `force-dynamic` poza robots | `sitemapRoute`, `robots`, `manifest` | A, S |
| 4 | **SEO** — dane strukturalne | layout: `<SiteProviders shell={…}>` daje `WebSite` + `Organization` (`sameAs`) z Site Settings; firma lokalna → `createContentHelpers({ siteJsonLd })` z `buildLocalBusinessJsonLd` (`type`, godziny → `formatOpeningHours`); nawigacja: `<SiteProviders jsonLd={[buildNavigationJsonLd(…)]}>`; strona: `createPageRoute` dokłada `getPageJsonLd` (WebPage/BlogPosting, okruszki, FAQ — `pageJsonLd: { faq }`) | `getSiteShell`, `SiteProviders`, `build*JsonLd`, `getPageJsonLd` | A, S |
| 5 | **GEO** — llms | `src/app/llms.txt/route.ts` (`llmsRoute`) i `src/app/llms-full.txt/route.ts` (`llmsFullRoute`) z `lib/content`; pole `buildSummaryField()` w Pages, `summaryField: 'aiSummary'` w `createContentHelpers` | `llmsRoute`, `llmsFullRoute`, `buildSummaryField` | A, S |
| 6 | **GEO** — Markdown | `src/app/md/[locale]/[[...slug]]/route.ts` = `export { markdownRoute as GET } from '@/lib/content'`; `createContentHelpers({ markdownAlternate: true })` (link w `<head>`); `createProxy(…, { NextResponse, markdown: true })` (bez tego `/md/…` dostaje redirect na język) | `markdownRoute`, `markdownAlternate`, `createProxy({ markdown })` | A, S |
| 7 | **GEO** — MCP | `src/app/api/mcp/route.ts` = `export { mcpGET as GET, mcpPOST as POST } from '@/lib/content'` (publiczny — AI przegląda stronę: `get_site_info`, `list_pages`, `search_content`, `get_page`); nazwa: `createContentHelpers({ mcp: { serverName } })` | `mcpGET`, `mcpPOST` | A, S |
| 8 | **GEO** — boty AI + IndexNow | robots **wpuszcza** boty AI (domyślne `aiBots: 'allow'`; blokada tylko z decyzji klienta); `ipalKit({ indexNow: true })` + `src/app/indexnow-key.txt/route.ts` (`indexNowKeyRoute`; publikacja → Bing/ChatGPT Search w minuty) | `buildRobots`, `indexNowKeyRoute` | A, S |
| 9 | **Media / R2 / szybkość** | `Media` z `focalPoint`, `normalizeFilenameHook`, `buildOptimizeUploadHook`, `buildMediaPlaceholderHook` + pole; **zawsze** `buildR2Storage(['media'], { s3Storage })` + `@payloadcms/storage-s3`; `R2_*` w `.env.example`; `<MediaPreconnect/>`; `images: buildImagesConfig()` i `buildUploadSecurityHeaders()` w `next.config.ts`; `<Media>` projektu przez `mediaImageProps`/`videoProps` (§6.11b) | `buildR2Storage`, `mediaImageProps`, `videoProps`, `buildImagesConfig` | A, S |
| 10 | **Formularze** | każdy formularz z **seeda** (`scripts/seed-form-*.ts`: pola, potwierdzenie, mail do firmy **i** potwierdzenie do klienta, każdy język); jeden `FormRenderer`; `actions.ts` = `createSubmitAction({ getCachedPayload, headers })`; `forms: {…}` w `ipalKit`; `email: mailAdapter()` | `createSubmitAction`, `useForm`, `mailAdapter` | A, P |
| 11 | **Turnstile** | `<TurnstileProvider siteKey={…}>` w `[locale]/layout.tsx`, `siteKey` z `getTurnstileConfig(payload)`; widget w `FormRenderer` (`useTurnstile`); klucze w Site Integrations | `getTurnstileConfig`, `TurnstileProvider`, `useTurnstile` | A, P |
| 12 | Zgoda + analityka | `ConsentProvider` (`logEndpoint` przy `consentLog: true`), `CookieBanner equalChoice`, `CookieButton`, `Analytics` w layoutcie; ID narzędzi w panelu; lista ciasteczek ze skanu (cookie-scan → import) + `<CookieTable>` na stronie polityki cookies | consent.md, analytics.md | A, `ipal-consent-check` |
| 10 | **Formularze** | każdy formularz z **seeda** (`scripts/seed-form-*.ts`: pola, potwierdzenie, mail do firmy **i** potwierdzenie do klienta, każdy język); blok z `<RenderForm>` + `formClasses.ts` (wygląd, raz); `actions.ts` = `createSubmitAction({ getCachedPayload, headers })`; `forms: {…}` w `ipalKit`; `email: mailAdapter()` | `RenderForm` (`/rsc`), `createSubmitAction`, `mailAdapter` | A, P |
| 11 | **Turnstile** | `<SiteProviders>` w `[locale]/layout.tsx` (wpina `TurnstileProvider` z kluczem z panelu); widget renderuje `RenderForm`; klucze w Site Integrations | `SiteProviders`, `getTurnstileConfig`, `TurnstileProvider` | A, P |
| 12 | Zgoda + analityka | `<SiteProviders logEndpoint="/api/ipal/consent" banner={<CookieBanner equalChoice />}>` (ConsentProvider, baner, CookieButton, Analytics w dobrej kolejności); ID narzędzi w panelu; lista ciasteczek ze skanu (cookie-scan → import) + `<CookieTable>` na stronie polityki cookies | consent.md, analytics.md | A, `ipal-consent-check` |
| 13 | Bezpieczeństwo | `buildSecurityHeaders` w `next.config.ts`; `twoFactor: { issuer, plugin: payloadTotp }`; CSP `report-only` → `enforce`; `IPAL_IP_HEADER` na produkcji | security.md, forms.md | A |
| 14 | Operacje | `src/app/api/health/route.ts`; `src/instrumentation.ts` z `assertEnv(ipalEnvRules({ storage: true, ipHeader: true }))`; staging z `IPAL_NOINDEX=1`; testy smoke (§8a) | `createHealthRoute`, `assertEnv`, `ipalEnvRules` | A |
| 14 | Operacje | `src/app/api/health/route.ts` (`healthRoute`); `src/instrumentation.ts` z `assertEnv(ipalEnvRules({ storage: true, ipHeader: true }))`; staging z `IPAL_NOINDEX=1`; testy smoke (§8a) | `healthRoute`, `assertEnv`, `ipalEnvRules` | A |
| 15 | Strony systemowe | Site Settings → System Pages: homepage, 404, polityka prywatności, cookies; linki prawne w stopce przez rolę | `getSystemPagePath`, `getNotFoundPage` | P |
| 16 | **Zero hardkodów** | każdy tekst, link, obraz, plik, dane firmy z panelu; domeny i klucze z `.env` (§2) | — | A, P |
| 17 | **Treść** | jedno h1, odpowiedź na początku sekcji, fakty, linki wewnętrzne, FAQ z prawdziwych pytań, `aiSummary`, sameAs, spójne dane firmy (§0c) | — | S, P |
@@ -83,7 +83,7 @@ Nie warunkujesz providera ani widgetu w kodzie — wpinasz zawsze.
| Zamiast pluginu | Dlaczego nie | Użyj |
|---|---|---|
| własny formularz z polami w JSX, `react-hook-form`, `formik` | klient nie zmieni pól; brak Turnstile, rate limitu, zgody RODO | builder w panelu + `FormRenderer` + `submitForm` |
| własny formularz z polami w JSX, `react-hook-form`, `formik`, własny renderer formularzy | klient nie zmieni pól; brak Turnstile, rate limitu, zgody RODO; kopia silnika przekazuje adresy z zakładki Emails do HTML | builder w panelu + `<RenderForm>` (wygląd: `formClasses`, nietypowe: `useBuilderForm`) |
| własna trasa `api/contact` / `api/send` / `api/form`, `nodemailer` / `resend` / `@sendgrid` w projekcie | omija walidację i bramki `submitForm`, drugi transport maili | server action `sendForm` → `submitForm`, maile z Forms → Emails przez `mailAdapter()` |
| reCAPTCHA, hCaptcha, własna captcha | drugi mechanizm, brak statusu w panelu | Turnstile z pluginu |
| ręczny `<script type="application/ld+json">` | brak escapowania, rozjazd z panelem | `JsonLdGraph` |
@@ -281,23 +281,23 @@ src/
(frontend)/
styles.css # Tailwind + @source na node_modules/@intecion/ipal-kit/dist
[locale]/ # jednojęzyczny: bez [locale] (patrz i18n.md)
layout.tsx # bez <head>; JsonLdGraph, TurnstileProvider, ConsentProvider + Analytics
actions.ts # sendForm → submitForm (jedyna droga wysyłki formularzy)
not-found.tsx # 404 z panelu (getNotFoundPage)
[[...slug]]/page.tsx # PODWÓJNE nawiasy; RenderBlocks
layout.tsx # bez <head>; <SiteProviders shell={await getSiteShell(locale)}> + Header/Footer
actions.ts # sendForm = createSubmitAction(…) (jedyna droga wysyłki formularzy)
not-found.tsx # createNotFoundPage(content, { blocks }) — 404 z panelu
[[...slug]]/page.tsx # PODWÓJNE nawiasy; createPageRoute(content, { blocks, … }) + revalidate
(payload)/ # panel (generowany)
manifest.ts # createManifestHandler + force-dynamic
sitemap.xml/route.ts # sitemapRoute z lib/content + force-dynamic (wygląd z pluginu)
robots.ts # z lib/content (boty AI wpuszczone)
llms.txt/route.ts # createLlmsTxtRoute (GEO)
llms-full.txt/route.ts # createLlmsTxtRoute({ full: true }) (GEO)
md/[locale]/[[...slug]]/route.ts # createMarkdownRenderer — strona jako Markdown (GEO)
api/mcp/route.ts # createMcpRoute — publiczny serwer MCP (GEO)
api/health/route.ts # createHealthRoute
manifest.ts # export { manifest as default } from lib/content + force-dynamic
sitemap.xml/route.ts # export { sitemapRoute as GET } + force-dynamic (wygląd z pluginu)
robots.ts # export { robots as default } (boty AI wpuszczone)
llms.txt/route.ts # export { llmsRoute as GET } (GEO)
llms-full.txt/route.ts # export { llmsFullRoute as GET } (GEO)
md/[locale]/[[...slug]]/route.ts # export { markdownRoute as GET } — strona jako Markdown (GEO)
api/mcp/route.ts # export { mcpGET as GET, mcpPOST as POST } — publiczny MCP (GEO)
api/health/route.ts # export { healthRoute as GET }
indexnow-key.txt/route.ts # export { indexNowKeyRoute as GET }
instrumentation.ts # assertEnv(ipalEnvRules({...})) z '@intecion/ipal-kit/env'
fields/ # sectionHeader.ts, sectionSettings.ts (linki: z pluginu)
components/
forms/FormRenderer.tsx # jedyny renderer formularzy z panelu (ipal-form)
forms/formClasses.ts # JEDYNE miejsce wyglądu formularzy (RenderForm classNames)
ui/ # prymitywy: CMSLink, Button, Media, Section, SectionHeader
layout/ # Header, Footer, MobileNav (§6.8)
icons/ # names.ts + Icon.tsx (§6.10)
@@ -305,13 +305,17 @@ src/
blocks/registry.ts # blockType → komponent
collections/ # Pages.ts, Media.ts (+ treść tylko gdy wymagana)
globals/ # Header.ts, Footer.ts, Company.ts
lib/content.ts # createContentHelpers — JEDYNY dostęp do Payloada
lib/navigation.ts # resolveNav → dane dla menu
lib/content.ts # createContentHelpers — JEDYNY dostęp do Payloada, trasy, linki, nawigacja
i18n.config.ts # locale — jedno źródło
payload.config.ts
proxy.ts # NIE middleware.ts
```
Trasy w `app/` to **re-eksporty** z `lib/content` — konfiguracja (domena, `summaryField`,
nazwa MCP) jest raz, w `createContentHelpers`. Pola sekcji (`buildSectionHeaderField`,
`buildSectionSettingsField`), linki (`resolveLink`) i menu (`resolveNav`) są w pluginie —
nie twórz `src/fields/sectionHeader.ts` ani `lib/navigation.ts`.
| Element | Konwencja | Przykład |
|---|---|---|
| Folder bloku, kolekcja, global | PascalCase | `blocks/FeatureGrid/`, `collections/Pages.ts` |
@@ -322,7 +326,7 @@ src/
| Komponent | nazwana funkcja, typy z `@/payload-types` | `export function Hero(...)` |
Bez skrótów (`HeroSection`, nie `HeroSec`). Nie twórz `lib/pages.ts`,
`lib/locales.ts` — plugin ma `resolveRoute`, `getConfiguredLocales`.
`lib/locales.ts`, `lib/navigation.ts` — plugin ma `resolveRoute`, `getConfiguredLocales`, `resolveNav`.
---
@@ -433,8 +437,8 @@ Trzy problemy, których nie wolno powtarzać: **zoo pól CTA** (`ctaLabel`,
### 6.1 Trzy warstwy
```
WARSTWA 1 — wspólne pola: linki z pluginu (buildLinkField, buildLinksField)
+ src/fields/ projektu (sectionHeader, sectionSettings)
WARSTWA 1 — wspólne pola: z pluginu (buildLinkField, buildLinksField,
buildSectionHeaderField, buildSectionSettingsField)
src/components/ui/ WARSTWA 2 — prymitywy UI (CMSLink, Button, Media, Section, SectionHeader)
src/blocks/X/ WARSTWA 3 — sekcja = kompozycja warstw 1 i 2
```
@@ -460,10 +464,11 @@ pobrania = link typu `file`, nigdy pole `pdfUrl`. W `payload-types.ts`: `CmsLink
pliki `buildOptimizeUploadHook` + `buildOptimizeUploadField` (storage.md). Pliki przygotowujesz
przed wgraniem — hook tylko łapie wpadki i pyta o zgodę.
**W projekcie (`src/fields/`)** — dwa małe helpery, kod w [kod-sekcji.md](./skills/ipal-block/resources/kod-sekcji.md):
- `sectionHeaderField()` → grupa `header`: `eyebrow`, `heading`, `intro` (localized),
- `sectionSettingsField()` → grupa `settings` (sidebar): `anchor`, `background`.
Każda sekcja ma `sectionSettingsField()` — żadnych `bgColor`, `sectionId` per blok.
**Nagłówek i ustawienia sekcji — z pluginu** ([blocks.md](../blocks.md)):
- `buildSectionHeaderField()` → grupa `header`: `eyebrow`, `heading`, `intro` (localized),
- `buildSectionSettingsField()` → grupa `settings` (sidebar): `anchor`, `background`
(tła projektu: `buildSectionSettingsField({ backgrounds: [{ label, value }] })`, dodatkowe pola: `fields`).
Każda sekcja ma `buildSectionSettingsField()` — żadnych `bgColor`, `sectionId` per blok.
Etykiety pól po angielsku (panel jest EN).
### 6.3 Warstwa 2 — prymitywy UI
@@ -472,16 +477,16 @@ Kod 1:1: [kod-sekcji.md](./skills/ipal-block/resources/kod-sekcji.md). Każdy ma
| Prymityw | Robi | Zamiast |
|---|---|---|
| `CMSLink` (async, serwer) | każdy link z panelu: `resolveLinkHref` z pluginu + styl z `Button` + `newTab`/plik | `<a href>`, `<Link href>` w sekcjach |
| `CMSLink` (async, serwer) | każdy link z panelu: `resolveLink(link, locale)` z `lib/content` (href, `internal`, `targetProps`, `appearance`) + klasy z `Button` | `<a href>`, `<Link href>` w sekcjach |
| `Button.tsx` | `Record<LinkAppearance, string>` z klasami wariantów | łańcuchy ternary, style przycisków w sekcjach |
| `Media` | każdy obraz/wideo z panelu (`next/image`, alt z dokumentu) | `<img src={x.url}>` |
| `Section` | `id` z anchora, tło z mapy, kontener | ręczne `<section className=…>` |
| `SectionHeader` | eyebrow + nagłówek (`h1`/`h2`) + intro | luźne nagłówki w każdej sekcji |
**`locale` dla bloków — raz, w trasie strony** (nigdy `headers()` w komponentach):
```tsx
const enhanceProps = () => ({ locale }) // Turnstile: <TurnstileProvider> w layoucie, nie props
```
`createPageRoute` podaje każdemu blokowi `locale` + to, co zwróci `blockProps`
(np. `{ formTexts, sendForm }`). Własna strona: `enhanceProps={() => ({ locale })}`.
Turnstile i zgoda są w `<SiteProviders>` w layoucie, nie w propsach.
### 6.4 Warstwa 3 — sekcja = kompozycja
@@ -528,11 +533,11 @@ Podkomponent jednej sekcji → w jej folderze; używany w 2+ sekcjach → `src/c
| Pojedynczy link (karta, element) | `link` (`buildLinkField()`) | `href`, `url`, `target`, `linkTo`, `readMoreUrl` |
| Obraz / wideo | `media` | `image`, `img`, `imageUrl`, `photo`, `bgImage`, `heroImage` |
| Plik do pobrania | `link` typu `file` | osobne `pdf`, `pdfUrl`, `file`, `download`, `attachment` |
| Nagłówek sekcji | `header` (`sectionHeaderField()`) | luźne `title`, `headline`, `sectionTitle`, `subheading`, `subtitle` |
| Nagłówek sekcji | `header` (`buildSectionHeaderField()`) | luźne `title`, `headline`, `sectionTitle`, `subheading`, `subtitle` |
| Tekst elementu | `heading` + `text` | `title`/`desc`/`description` naprzemiennie |
| Tekst sformatowany | `content` (richText) | `body`, `html`, `richText` |
| Lista elementów | `items` | `cards`, `features`, `list`, `boxes` |
| Anchor / tło | `settings` (`sectionSettingsField()`) | `sectionId`, `bgColor`, `dark`, `theme` per blok |
| Anchor / tło | `settings` (`buildSectionSettingsField()`) | `sectionId`, `bgColor`, `dark`, `theme` per blok |
| Zgoda RODO w formularzu | `consent` (checkbox) | — |
Wyjątek tylko przy dwóch rzeczach tego samego rodzaju o różnej roli
@@ -584,12 +589,12 @@ pustych pól, bez zgadywania, bez numerowanych slotów. Schemat projektujesz dla
{ name: 'bgColor', type: 'text', admin: { description: 'Kolor tła sekcji w hex, używany w className komponentu' } },
// DOBRZE — 4 pozycje w panelu, rośnie przyciskiem „+ Add …”
sectionHeaderField(), // Eyebrow / Heading / Intro
buildSectionHeaderField(), // Eyebrow / Heading / Intro
{ name: 'items', type: 'array', labels: { singular: 'Feature', plural: 'Features' }, maxRows: 6,
admin: { initCollapsed: true, components: rowLabel('heading', 'Feature') },
fields: [{ name: 'heading', type: 'text', localized: true, required: true }, { name: 'text', type: 'textarea', localized: true }] },
buildLinksField(), // „+ Add Button”
sectionSettingsField(), // sidebar: anchor, background
buildSectionSettingsField(), // sidebar: anchor, background
```
**Test pustego bloku** (po każdym nowym bloku, w panelu): dodaj blok na stronie →
@@ -634,7 +639,7 @@ className={v === 'a' ? 'x' : v === 'b' ? 'y' : 'z'}
### 6.8 Header i Footer (globale nawigacji)
Kod (globale, `resolveNav`, `Header`, `Footer`, `MobileNav`): [kod-nawigacji.md](./skills/ipal-nav/resources/kod-nawigacji.md).
Kod (globale, `Header`, `Footer`, `MobileNav`; `resolveNav` z pluginu): [kod-nawigacji.md](./skills/ipal-nav/resources/kod-nawigacji.md).
Skill: **ipal-nav**.
- Nawigacja, stopka, dane firmy = **globale projektu** (`header`, `footer`, `company`),
@@ -642,8 +647,9 @@ Skill: **ipal-nav**.
- Menu: jeden poziom podmenu, nie głębiej. CTA w nagłówku = `links`.
- Logo i nazwa z Site Settings — nie duplikuj pól w Header.
- **Linki prawne w stopce** z ról System Pages (`getSystemPagePath`), nie ręcznie.
- Linki rozwiązuj **na serwerze** (`resolveNav` → `{ href, label, newTab }`); do
komponentu klienckiego idą tylko proste dane — `CMSLink` jest serwerowy.
- Linki rozwiązuj **na serwerze**: `await resolveNav(header.navItems, locale)` z `lib/content`
→ `{ href, label, internal, newTab, targetProps, children }[]` (martwe linki pominięte); do
komponentu klienckiego (MobileNav) idą tylko te dane — `CMSLink` jest serwerowy.
- Etykiety a11y (przycisk menu) — pola w panelu.
- Global zmieniany na każdej stronie → `afterChange` z `revalidatePath('/', 'layout')`.
- Globale pobiera tylko `[locale]/layout.tsx` i podaje jako props.
@@ -748,30 +754,87 @@ Kontrole: `ipal-audit` (img/video poza Media, wiele `priority`, `h-screen`, sta
## 7. WZORCE PLUGINU — UŻYWAJ, NIE PISZ OD NOWA
Katalog: **potrzeba → import**. Zanim napiszesz helper, hook, komponent logiki albo trasę —
znajdź ją tutaj. Wejścia: `@intecion/ipal-kit` (serwer/config), `/client` (`'use client'`),
`/rsc` (komponenty serwerowe), `/server` (server actions), `/admin` (panel), `/env`
(`instrumentation.ts`). Plugin daje **logikę i szkielet**; wygląd zostaje w projekcie
(klasy, `classNames`, własny markup na hooku). Nie ma czegoś, co powtórzy się w innym
projekcie → **ipal-plugin-gap**, nie kopia.
**Strona i dane** (`lib/content.ts` = `createContentHelpers`, PROGRAMISTA §2.7)
| Potrzeba | Użyj | Doc |
|---|---|---|
| Link / CTA / plik do pobrania | `buildLinkField`, `buildLinksField`, `resolveLinkHref` | links.md |
| Payload, ustawienia, języki (cache na żądanie) | `getCachedPayload`, `getSettings`, `getConfiguredLocales` | content.md |
| Strona catch-all (route, 308, 404, meta, static params, JSON-LD, bloki) | `createPageRoute(content, { blocks, notFound, permanentRedirect, blockProps, render })` (`/rsc`) | pages.md |
| 404 z panelu w każdym języku | `createNotFoundPage(content, { blocks, fallback })` (`/rsc`) | pages.md |
| Layout: zgoda, baner, Turnstile, analityka, JSON-LD strony, preconnect | `getSiteShell(locale)` + `<SiteProviders shell>` (`/rsc`) | consent.md |
| Własna strona / archiwum | `resolveRoute`, `getEntries`, `resolvePageRedirect`, `generatePageMetadata`, `getPageJsonLd`, `generateStaticParams` | content.md, pages.md |
| Render bloków | `RenderBlocks` + mapa `registry` (nigdy `switch`) | blocks.md |
| Rich text | `RenderRichText` (`/rsc`), styl przez `converters` | richtext.md |
| Wartość zlokalizowana | `resolveLocalized(value, locale)` (nie `getSafeString`) | forms.md |
| Formularz | builder w panelu + `FormRenderer` + akcja `sendForm` → `submitForm`; logika `useForm`; IP: `clientIp(await headers())` | forms.md |
| Turnstile | `TurnstileProvider siteKey={(await getTurnstileConfig(payload)).siteKey}` w layoutcie + `useTurnstile()` — przy obu kluczach token jest wymagany | turnstile.md |
| Slug | `buildSlugField({ from: 'title' })` | slug.md |
| noindex | `buildNoindexField()` | seo.md |
| Ścieżki językowe | `getLocalizedSlugs`, `switchLocalePath`, `LanguageSwitcher` | i18n.md |
| Strony systemowe, 404 | `getSystemPagePath`, `getNotFoundPage` | pages.md |
| Routing, archiwa | `resolveRoute`, `getEntries`, `resolveRedirect` | content.md |
| ISR po zapisie | `buildRevalidateHook` (wstrzyknięty `revalidatePath`) | hooks.md |
| Stary slug → 308 | `trackSlugHistoryHook` + `resolveRedirect` | hooks.md |
| Obrazy między językami | `buildCrossLocaleFieldSync` (języki z configu) | hooks.md |
| Ochrona stron systemowych | `buildPreventDeleteSystemPage`, `buildValidateUniqueRole` | hooks.md |
| Metadata, sitemap, JSON-LD | `generatePageMetadata` (z `createContentHelpers`), `sitemapRoute`, `build*JsonLd` + `JsonLdGraph` | seo.md |
| GEO (AI) | `createLlmsTxtRoute` (+ `full: true`), `createMarkdownRenderer` + `markdownResponse`, `markdownAlternate: true`, `createProxy({ markdown: true })`, `createMcpRoute`, `buildSummaryField` | seo.md, content.md, mcp.md |
| Consent, analytics, pixele | `ConsentProvider`, `CookieBanner`, `Analytics` (wewnątrz providera) | consent.md, analytics.md |
| Nagłówki, CSP, 2FA | `buildSecurityHeaders`, `buildCsp`, `twoFactor` (wstrzyknięty `payloadTotp`) | security.md |
| Media, R2 | `buildR2Storage(['media'], { s3Storage })` (adapter wstrzyknięty), `normalizeFilenameHook`, `buildOptimizeUploadHook` + `buildOptimizeUploadField`, `MediaPreconnect` | storage.md |
| Email | `email: mailAdapter()` | email.md |
| Walidacja env | `assertEnv(ipalEnvRules({ storage: true, ipHeader: true }))` z `@intecion/ipal-kit/env` | env.md |
| Rich text / Lexical → Markdown | `RenderRichText` (`/rsc`, styl przez `converters`), `lexicalToMarkdown` | richtext.md |
| Wartość zlokalizowana | `resolveLocalized(value, locale)` (nie `getSafeString`) | i18n.md |
**Pola i panel**
| Potrzeba | Użyj | Doc |
|---|---|---|
| Link / CTA / plik do pobrania | `buildLinkField`, `buildLinksField` | links.md |
| Nagłówek i ustawienia sekcji | `buildSectionHeaderField`, `buildSectionSettingsField({ backgrounds })` | blocks.md |
| Czytelne wiersze tablic | `rowLabel(['heading'], 'Feature')` (+ `generate:importmap`) | links.md |
| Slug / noindex / opis dla AI | `buildSlugField`, `buildNoindexField`, `buildSummaryField` | slug.md, seo.md |
| Strony systemowe i ich ochrona | `getSystemPagePath`, `buildPreventDeleteSystemPage`, `buildValidateUniqueRole` | pages.md, hooks.md |
| ISR po zapisie, stary slug → 308, obrazy między językami | `buildRevalidateHook`, `trackSlugHistoryHook`, `buildCrossLocaleFieldSync` | hooks.md |
| Role i dostęp | `adminOnly`, `adminOrEditor`, `adminOrSelf`, `authenticated`, `requireRole`, `hasMinimumRole` (+ `…Field`) | access.md |
| Dane z globali | `getGlobal`, `getSiteSettings`, `getSiteIntegrations` | payload-helpers.md |
**Linki i nawigacja**
| Potrzeba | Użyj | Doc |
|---|---|---|
| href + nowa karta + rel + internal dla linku z panelu | `resolveLink(link, locale)` (`lib/content`) / `resolveLink(link, opts)` | links.md |
| Menu z globala (dowolna głębokość, martwe linki pominięte) | `resolveNav(items, locale)` | links.md |
| Ścieżki językowe, przełącznik, hreflang | `getLocalizedSlugs`, `switchLocalePath`, `LanguageSwitcher`, `buildLocalizedPath` | i18n.md |
| Bezpieczny URL (bez `javascript:`) | `safeHref` | links.md |
**Formularze**
| Potrzeba | Użyj | Doc |
|---|---|---|
| Formularz z panelu w bloku (kroki, radio, listy, daty) | `<RenderForm form action locale texts classNames>` (`/rsc`) | forms.md |
| Wygląd formularzy | `formClasses.ts` (`BuilderFormClassNames`) — raz na projekt | forms.md |
| Nietypowy markup formularza | `BuilderForm renderField` / `useBuilderForm` (`/client`) | forms.md |
| Wysyłka | `createSubmitAction({ getCachedPayload, headers })` (`/server`) | forms.md |
| Teksty komunikatów i przycisków kroków | Notifications → `getFormTexts(locale)` | notifications.md |
| Formularz w bazie | seed `ipal-form/resources/seed-form.template.ts` | forms.md |
| Antyspam / limit / IP | honeypot w `BuilderForm`, Turnstile z `SiteProviders`, `clientIp`, `setRateLimitStore` | forms.md, turnstile.md |
| Zdarzenie GTM po wysłaniu | `buildFormAnalyticsFields` (panel) — `RenderForm` wysyła je sam | forms.md |
| Formularz spoza buildera (np. filtry) | `useForm` + `buildValidator`, `required`, `email`… | forms.md |
**SEO i GEO** (trasy = re-eksport z `lib/content`)
| Potrzeba | Użyj | Doc |
|---|---|---|
| Metadata, kanoniczne, hreflang, OG, X | `generatePageMetadata` (`createPageRoute` robi to sam) | seo.md |
| sitemap / robots / manifest | `sitemapRoute`, `robots`, `manifest` | seo.md |
| JSON-LD | `getSiteShell().jsonLd`, `getPageJsonLd`, `build*JsonLd`, `formatOpeningHours`, `sameAsUrls`, `<JsonLdGraph>` | seo.md |
| llms.txt / llms-full / Markdown / MCP | `llmsRoute`, `llmsFullRoute`, `markdownRoute`, `mcpGET`/`mcpPOST`; `markdownAlternate: true`; `createProxy({ markdown: true })` | seo.md, content.md, mcp.md |
| IndexNow | `ipalKit({ indexNow: true })` + `indexNowKeyRoute` | seo.md |
| Wyszukiwarka | `createSearchRoute` | content.md |
**Media, wygląd, szybkość**
| Potrzeba | Użyj | Doc |
|---|---|---|
| R2, nazwy plików, optymalizacja, podgląd | `buildR2Storage`, `normalizeFilenameHook`, `buildOptimizeUploadHook`, `buildMediaPlaceholderHook` | storage.md |
| Obraz / wideo w `<Media>` | `mediaImageProps`, `videoProps`, `MEDIA_SIZES` | storage.md |
| YouTube bez ciasteczek przed kliknięciem | `<YouTubeEmbed>` (`/client`) | storage.md |
| `next.config` | `buildImagesConfig`, `buildSecurityHeaders`, `buildCsp`, `buildUploadSecurityHeaders` | storage.md, security.md |
| Płynna typografia i odstępy | `fluid.css` / `fluid-wide.css` (zmienne `--ipal-*`) | PROGRAMISTA §2.5 |
**Zgoda, analityka, operacje**
| Potrzeba | Użyj | Doc |
|---|---|---|
| Baner, ustawienia, przycisk cookies | `<SiteProviders banner={<CookieBanner …/>}>`, `CookieButton`, `useConsent` | consent.md |
| Skrypt zależny od zgody | `ConsentScript` | consent.md |
| Tabela ciasteczek na polityce | `<CookieTable>` (`/rsc`), `getCookieTable` | consent.md |
| GA4, GTM, Pixel, Clarity, LinkedIn, TikTok | ID w panelu — `SiteProviders` ładuje `Analytics` (`analytics={{ defer: true }}`) | analytics.md |
| Mail | `email: mailAdapter()`, `sendEmail` | email.md |
| Walidacja env, health | `assertEnv(ipalEnvRules({…}))` (`/env`), `healthRoute` | env.md |
| 2FA, white-label, nagłówki | `twoFactor: { issuer, plugin: payloadTotp }`, `whiteLabel`, `buildSecurityHeaders` | security.md, white-label.md |
| Rate limit (formularze, MCP, wyszukiwarka) | wbudowany; IP z `IPAL_IP_HEADER`; kilka instancji → `setRateLimitStore` | forms.md |
**Compliance (PL/EU) — mechanizm z pluginu, treść od klienta:** strony polityk
+28 -16
View File
@@ -216,31 +216,31 @@ APP=$(dirs src/app)
if [ -n "$APP" ]; then
# SEO
need ERROR '' "page metadata" "generatePageMetadata (lib/content) in generateMetadata of the page routes" 'generatePageMetadata|createPageMetadata|createMetadataGenerator' src/app
need ERROR '' "page metadata" "generatePageMetadata (lib/content) in generateMetadata of the page routes" 'generatePageMetadata|createPageMetadata|createMetadataGenerator|createPageRoute' src/app
need ERROR '' "sitemap.xml route" "src/app/sitemap.xml/route.ts → sitemapRoute" 'sitemapRoute|createSitemapRouteHandler|buildSitemapEntries|sitemap' src/app/sitemap.xml src/app/sitemap.ts
need ERROR '' "robots" "src/app/robots.ts → robots from lib/content" 'robots|buildRobots' src/app/robots.ts
need ERROR '' "manifest" "src/app/manifest.ts → createManifestHandler" 'createManifestHandler|buildManifest' src/app/manifest.ts
need ERROR '' "manifest" "src/app/manifest.ts → export { manifest as default } from '@/lib/content'" 'manifest|createManifestHandler|buildManifest' src/app/manifest.ts
need ERROR '' "htmlLimitedBots" "next.config.ts — metadata must reach crawlers in <head>" 'htmlLimitedBots' next.config.ts next.config.mjs next.config.js
need ERROR jsonld "structured data" "<JsonLdGraph> with WebSite + Organization/LocalBusiness in [locale]/layout.tsx" 'JsonLdGraph' src
need ERROR jsonld "structured data" "<SiteProviders shell={await getSiteShell(locale)}> (WebSite + Organization) or <JsonLdGraph> in [locale]/layout.tsx" 'JsonLdGraph|SiteProviders' src
# GEO
need ERROR llms "llms.txt" "src/app/llms.txt/route.ts → createLlmsTxtRoute" 'createLlmsTxtRoute|buildLlmsTxt' src/app
need ERROR llms-full "llms-full.txt" "src/app/llms-full.txt/route.ts → createLlmsTxtRoute({ full: true })" 'full: *true' src/app/llms-full.txt
need ERROR markdown "Markdown route" "src/app/md/[locale]/[[...slug]]/route.ts → createMarkdownRoute" 'createMarkdownRoute|createMarkdownRenderer' src/app
need WARNING jsonld "page structured data" "[[...slug]]/page.tsx → <JsonLdGraph schemas={await getPageJsonLd(locale, slug)} />" 'getPageJsonLd|buildWebPageJsonLd|buildBreadcrumbJsonLd' src/app
need ERROR llms "llms.txt" "src/app/llms.txt/route.ts → export { llmsRoute as GET } from '@/lib/content'" 'llmsRoute|createLlmsTxtRoute|buildLlmsTxt' src/app
need ERROR llms-full "llms-full.txt" "src/app/llms-full.txt/route.ts → export { llmsFullRoute as GET } from '@/lib/content'" 'llmsFullRoute|full: *true' src/app/llms-full.txt
need ERROR markdown "Markdown route" "src/app/md/[locale]/[[...slug]]/route.ts → export { markdownRoute as GET } from '@/lib/content'" 'markdownRoute|createMarkdownRoute|createMarkdownRenderer' src/app
need WARNING jsonld "page structured data" "[[...slug]]/page.tsx → createPageRoute (adds getPageJsonLd) or <JsonLdGraph schemas={await getPageJsonLd(locale, slug)} />" 'createPageRoute|getPageJsonLd|buildWebPageJsonLd|buildBreadcrumbJsonLd' src/app
need ERROR markdown "Markdown in proxy" "proxy.ts → createProxy(i18nConfig, { NextResponse, markdown: true }) — without it /md/… is redirected to /<locale>/md/…" 'markdown: *(true|['"'"'"])|prefersMarkdown' src/proxy.ts proxy.ts
need WARNING markdown "Markdown alternate link" "createContentHelpers({ markdownAlternate: true }) or markdownHref in metadata" 'markdownAlternate|markdownHref' src
need ERROR mcp "MCP server" "src/app/api/mcp/route.ts → createMcpRoute (public: AI browses the site)" 'createMcpRoute' src/app
need WARNING '' "AI summary field" "buildSummaryField() in Pages + summaryField: 'aiSummary' in llms/MCP routes" 'buildSummaryField' src
need ERROR mcp "MCP server" "src/app/api/mcp/route.ts → export { mcpGET as GET, mcpPOST as POST } from '@/lib/content' (public: AI browses the site)" 'mcpPOST|createMcpRoute' src/app
need WARNING '' "AI summary field" "buildSummaryField() in Pages + createContentHelpers({ summaryField: 'aiSummary' })" 'buildSummaryField' src
# Ops
need ERROR '' "health route" "src/app/api/health/route.ts → createHealthRoute" 'createHealthRoute' src/app
need ERROR '' "health route" "src/app/api/health/route.ts → export { healthRoute as GET } from '@/lib/content'" 'healthRoute|createHealthRoute' src/app
need ERROR '' "env validation" "src/instrumentation.ts → assertEnv(ipalEnvRules({...})) from @intecion/ipal-kit/env" 'assertEnv' src/instrumentation.ts instrumentation.ts
need ERROR '' "security headers" "next.config.ts → buildSecurityHeaders" 'buildSecurityHeaders' next.config.ts next.config.mjs next.config.js
# Consent, analytics, Turnstile (layout)
need ERROR '' "cookie consent" "ConsentProvider + CookieBanner + CookieButton in [locale]/layout.tsx" 'CookieBanner' src/app
need ERROR analytics "analytics" "<Analytics> inside ConsentProvider (IDs from the panel)" '<Analytics' src/app
need ERROR turnstile "Turnstile provider" "<TurnstileProvider siteKey> in [locale]/layout.tsx — always, it hides itself without keys" 'TurnstileProvider' src
need WARNING turnstile "getTurnstileConfig" "siteKey from getTurnstileConfig(payload) — off unless BOTH keys are set" 'getTurnstileConfig' src
need WARNING '' "MediaPreconnect" "<MediaPreconnect/> in the layout (R2 CDN preconnect from env)" 'MediaPreconnect' src/app
need ERROR '' "cookie consent" "<SiteProviders> (or ConsentProvider + CookieBanner + CookieButton) in [locale]/layout.tsx" 'SiteProviders|CookieBanner' src/app
need ERROR analytics "analytics" "<SiteProviders> (loads Analytics) or <Analytics> inside ConsentProvider" 'SiteProviders|<Analytics' src/app
need ERROR turnstile "Turnstile provider" "<SiteProviders> or <TurnstileProvider siteKey> in [locale]/layout.tsx — always, it hides itself without keys" 'SiteProviders|TurnstileProvider' src
need WARNING turnstile "Turnstile site key" "getSiteShell(locale) (or getTurnstileConfig(payload)) — off unless BOTH keys are set" 'getSiteShell|getTurnstileConfig' src
need WARNING '' "MediaPreconnect" "<SiteProviders> (adds it) or <MediaPreconnect/> in the layout" 'SiteProviders|MediaPreconnect' src/app
# Forms
need ERROR '' "form submission via the plugin" "actions.ts → export const sendForm = createSubmitAction({ getCachedPayload, headers }) (ipal-form)" 'createSubmitAction|submitForm' src
need WARNING '' "upload sandbox headers" "next.config.ts → ...buildUploadSecurityHeaders() (uploaded SVG can't run script)" 'buildUploadSecurityHeaders' next.config.ts next.config.mjs next.config.js
@@ -271,9 +271,21 @@ report ERROR "hand-written JSON-LD script" "§0b — <JsonLdGraph> escapes and w
"$(g 'application/ld\+json' src --include=*.tsx | grep -v 'JsonLdGraph')"
report ERROR "static SEO files in public/" "§0b — sitemap, robots and llms are generated from the panel" \
"$(ls public/sitemap.xml public/robots.txt public/llms.txt public/llms-full.txt 2>/dev/null)"
report WARNING "<form> outside the form renderer" "§0b — forms render from the panel via FormRenderer (a search box is fine)" \
report WARNING "<form> outside the form renderer" "§0b — panel forms render via <RenderForm> (a search box is fine)" \
"$(g '<form[ >]' src --include=*.tsx | grep -v 'components/forms/')"
# Project copies of what the plugin now ships (import instead of code)
report WARNING "own form engine" "ipal-form §3 — <RenderForm> / useBuilderForm (steps, choices, Turnstile, honeypot; Emails tab never reaches the browser)" \
"$(g 'buildValidator|useForm\(' src --include=*.tsx | grep -v 'useBuilderForm')"
report WARNING "project copy of section fields / navigation" "blocks.md, links.md — buildSectionHeaderField, buildSectionSettingsField, resolveNav (lib/content)" \
"$(ls src/fields/sectionHeader.ts src/fields/sectionSettings.ts src/lib/navigation.ts 2>/dev/null)"
if [ -n "$UI" ]; then
for c in $(grep -rlE "^['\"]use client['\"]" $UI 2>/dev/null); do
report ERROR "server entry in client component" "§6.9 '@intecion/ipal-kit' (root), '/rsc', '/server' pull Payload into the browser — client code imports '/client' (types: import type)" \
"$(grep -nE "from '@intecion/ipal-kit(/rsc|/server)?'" "$c" | grep -v 'import type' | sed "s|^|$c:|")"
done
fi
# --- Compile & build ---
if [ "$QUICK" -eq 0 ]; then
echo
+5 -5
View File
@@ -1,6 +1,6 @@
---
name: ipal-block
description: Builds or refactors one page section (Payload block + React component) in an ipal-kit project the correct way — a clean editor panel (repeatable things as "+ Add …" arrays with rowLabel, never cta1/cta2 slots, short English labels, no empty spare fields), shared fields (sectionHeaderField, buildLinksField, buildLinkField, sectionSettingsField), UI primitives (Section, SectionHeader, Media, CMSLink), fixed field vocabulary, max ~80 lines of JSX, subcomponents for repeated items, registry wiring. Use when creating a new section/block (hero, features, CTA, FAQ, gallery, pricing, testimonials…), changing a block's fields, or fixing a block with ctaLabel/buttonUrl/pdfUrl fields or a monolithic component.
description: Builds or refactors one page section (Payload block + React component) in an ipal-kit project the correct way — a clean editor panel (repeatable things as "+ Add …" arrays with rowLabel, never cta1/cta2 slots, short English labels, no empty spare fields), shared fields from the plugin (buildSectionHeaderField, buildLinksField, buildLinkField, buildSectionSettingsField), UI primitives (Section, SectionHeader, Media, CMSLink), fixed field vocabulary, max ~80 lines of JSX, subcomponents for repeated items, registry wiring. Use when creating a new section/block (hero, features, CTA, FAQ, gallery, pricing, testimonials…), changing a block's fields, or fixing a block with ctaLabel/buttonUrl/pdfUrl fields or a monolithic component.
---
# ipal-block
@@ -9,9 +9,9 @@ Jedna sekcja na jedno użycie skilla. Szczegóły i gotowy kod:
`node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` §6.
## 0. Warunki wstępne
Sprawdź, czy istnieją: `src/fields/sectionHeader.ts`,
`sectionSettings.ts`, `src/components/ui/{CMSLink,Button,Media,Section,SectionHeader}.tsx`.
Linki (`buildLinkField`, `buildLinksField`, `resolveLinkHref`) są w pluginie — nie twórz ich w projekcie.
Sprawdź, czy istnieją: `src/components/ui/{CMSLink,Button,Media,Section,SectionHeader}.tsx`.
Stare `src/fields/sectionHeader.ts` / `sectionSettings.ts` → zamień na import z pluginu i usuń (blocks.md, bez migracji).
Linki (`buildLinkField`, `buildLinksField`, `resolveLink`) i pola sekcji (`buildSectionHeaderField`, `buildSectionSettingsField`) są w pluginie — nie twórz ich w projekcie.
Brakuje → najpierw utwórz je 1:1 z `resources/kod-sekcji.md` (ten skill)
(i powiedz o tym użytkownikowi). Nie pisz własnych wersji.
@@ -27,7 +27,7 @@ Brakuje → najpierw utwórz je 1:1 z `resources/kod-sekcji.md` (ten skill)
Wzorce plików (Hero, FeatureGrid + FeatureCard): `resources/kod-sekcji.md`.
1. `src/blocks/<Nazwa>/config.ts` — `interfaceName: '<Nazwa>Block'`, pola z planu,
zawsze `sectionSettingsField()`. CTA = `buildLinksField()`, nigdy pola `cta*`/`button*`.
zawsze `buildSectionSettingsField()`. CTA = `buildLinksField()`, nigdy pola `cta*`/`button*`.
Plik do pobrania = link typu `file`. **Panel wg AGENT.md §6.5a:**
- powtarzalne → tablica z `labels: { singular, plural }` + `admin: { initCollapsed: true, components: rowLabel('heading', '<Singular>') }`, `maxRows` z designu;
- zero numerowanych pól (`cta1`, `feature2Title`, `image3`) i pól „na zapas”;
@@ -3,7 +3,8 @@
> Zasoby skilla **ipal-block**. Reguły (dlaczego tak, czego nie robić) są w
> `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` §6 — ten plik to tylko kod
> do utworzenia w projekcie **1:1**. Linki (`buildLinkField`, `buildLinksField`,
> `resolveLinkHref`) są w pluginie — nie twórz ich kopii.
> `resolveLink`), pola sekcji (`buildSectionHeaderField`, `buildSectionSettingsField`) i menu
> (`resolveNav`) są w pluginie — nie twórz ich kopii.
## Warstwa 1 — wspólne pola
@@ -29,53 +30,17 @@ Kolekcja `media` dopuszcza PDF (`upload.mimeTypes: ['image/*', 'application/pdf'
'video/mp4']`), ma `alt` (required, localized) i `normalizeFilenameHook`.
„Pobierz cennik (PDF)” to **link typu `file`**, nie osobne pole `pdf`/`pdfUrl`.
`src/fields/sectionHeader.ts` i `src/fields/sectionSettings.ts`:
**Nagłówek i ustawienia sekcji — z pluginu, nie kopiuj kodu** (`docs/blocks.md`):
```ts
import type { GroupField } from 'payload'
import { buildSectionHeaderField, buildSectionSettingsField } from '@intecion/ipal-kit'
export function sectionHeaderField(name = 'header'): GroupField {
return {
name,
type: 'group',
interfaceName: 'SectionHeaderData',
fields: [
{ name: 'eyebrow', type: 'text', localized: true, admin: { description: 'Small line above the heading. Optional.' } },
{ name: 'heading', type: 'text', localized: true },
{ name: 'intro', type: 'textarea', localized: true, admin: { rows: 3 } },
],
}
}
export function sectionSettingsField(): GroupField {
return {
name: 'settings',
type: 'group',
label: 'Section settings',
interfaceName: 'SectionSettings',
admin: { position: 'sidebar' },
fields: [
{
name: 'anchor',
type: 'text',
admin: { description: 'Section id for #links and section nav, e.g. "pricing".' },
},
{
name: 'background',
type: 'select',
defaultValue: 'default',
options: [
{ label: 'Default', value: 'default' },
{ label: 'Muted', value: 'muted' },
{ label: 'Inverted (dark)', value: 'inverted' },
],
},
],
}
}
buildSectionHeaderField() // grupa `header`: eyebrow, heading, intro (localized) — typ SectionHeaderData
buildSectionSettingsField() // sidebar `settings`: anchor, background (default/muted/inverted) — typ SectionSettings
buildSectionSettingsField({ backgrounds: [{ label: 'Default', value: 'default' }, { label: 'Brand', value: 'brand' }] })
```
Każda sekcja ma `sectionSettingsField()` — żadnych `bgColor`, `darkMode`,
Każda sekcja ma `buildSectionSettingsField()` — żadnych `bgColor`, `darkMode`,
`sectionId` w poszczególnych blokach. Etykiety pól po angielsku (panel jest EN).
## Warstwa 2 — prymitywy UI
@@ -85,11 +50,10 @@ Każda sekcja ma `sectionSettingsField()` — żadnych `bgColor`, `darkMode`,
```tsx
import Link from 'next/link'
import type { ReactNode } from 'react'
import { resolveLinkHref } from '@intecion/ipal-kit'
import type { CmsLink } from '@/payload-types'
import { i18nConfig } from '@/i18n.config'
import { getSettings } from '@/lib/content'
import { resolveLink } from '@/lib/content'
import { buttonClass } from './Button'
import type { LinkAppearance } from '@intecion/ipal-kit'
type Props = {
link: CmsLink | null | undefined
@@ -99,25 +63,15 @@ type Props = {
children?: ReactNode
}
// href, new tab, rel, internal/external — from the plugin. Here: the element and the classes.
export async function CMSLink({ link, locale, className, children }: Props) {
const settings = await getSettings(locale) // react cache → one query per request
const home = settings?.homepage
const homeSlug = home && typeof home === 'object' && typeof home.slug === 'string' ? home.slug : undefined
const href = resolveLinkHref(link, { locale, config: i18nConfig, homeSlug })
const content = children ?? link?.label
if (!link || !href || !content) return null
const cls = [link.appearance ? buttonClass(link.appearance) : '', className]
.filter(Boolean)
.join(' ')
const newTab = link.newTab || link.type === 'file'
const targetProps = newTab ? { target: '_blank', rel: 'noopener noreferrer' } : {}
if (link.type === 'internal') {
return <Link href={href} className={cls} {...targetProps}>{content}</Link>
}
return <a href={href} className={cls} {...targetProps}>{content}</a>
const l = await resolveLink(link, locale)
const content = children ?? l?.label
if (!l || !content) return null
const cls = [l.appearance ? buttonClass(l.appearance as LinkAppearance) : '', className].filter(Boolean).join(' ') || undefined
return l.internal
? <Link href={l.href} className={cls} {...l.targetProps}>{content}</Link>
: <a href={l.href} className={cls} {...l.targetProps}>{content}</a>
}
```
@@ -225,18 +179,17 @@ const enhanceProps = () => ({ locale }) // Turnstile: <TurnstileProvider> w la
// src/blocks/Hero/config.ts
import type { Block } from 'payload'
import { buildLinksField } from '@intecion/ipal-kit'
import { sectionHeaderField } from '@/fields/sectionHeader'
import { sectionSettingsField } from '@/fields/sectionSettings'
import { buildSectionHeaderField, buildSectionSettingsField } from '@intecion/ipal-kit'
export const HeroBlock: Block = {
slug: 'hero',
interfaceName: 'HeroBlock',
labels: { singular: 'Hero', plural: 'Heroes' },
fields: [
sectionHeaderField(),
buildSectionHeaderField(),
{ name: 'media', type: 'upload', relationTo: 'media' },
buildLinksField(),
sectionSettingsField(),
buildSectionSettingsField(),
],
}
```
@@ -272,7 +225,7 @@ Sekcja z powtarzalnymi elementami — element tablicy to podkomponent:
```ts
// src/blocks/FeatureGrid/config.ts (fields) — import { buildLinkField, buildLinksField, rowLabel } from '@intecion/ipal-kit'
sectionHeaderField(),
buildSectionHeaderField(),
{
name: 'items',
type: 'array',
@@ -289,7 +242,7 @@ sectionHeaderField(),
],
},
buildLinksField({ maxRows: 1 }),
sectionSettingsField(),
buildSectionSettingsField(),
```
```tsx
@@ -26,7 +26,7 @@ się załadować wcześniej tylko z sygnałem Consent Mode „denied” i bez ci
|---|---|
| piksel loaded without consent | skrypt wpięty ręcznie / skopiowany `Analytics` → ID w Site Integrations, `<Analytics>` z pluginu (analytics.md) |
| tracking cookie set without consent | to samo; albo GTM odpala tag bez warunku `ad_storage` (analytics.md → GTM) |
| GA hit with consent GRANTED | `setDefaultConsent` nie przed tagiem — `<Analytics>` musi być wewnątrz `<ConsentProvider>` |
| GA hit with consent GRANTED | `setDefaultConsent` nie przed tagiem — `<Analytics>` musi być wewnątrz `<ConsentProvider>` (`SiteProviders` robi to sam) |
| YouTube / Maps before consent (warning) | `ConsentScript` (consent.md), `youtube-nocookie.com` albo „kliknij, aby załadować” |
4. Sekcja „after accept” mówi, co startuje po zgodzie — porównaj z ID w Site
+49 -34
View File
@@ -5,8 +5,8 @@ description: Wires forms the ipal-kit way — forms built by the editor in the p
# ipal-form
**Formularz buduje redaktor w panelu. Ty piszesz raz: renderer + akcję.** Każdy
kolejny formularz to tylko panel. Ręcznie wpisane pola/etykiety w JSX = błąd
**Formularz buduje redaktor w panelu. Projekt ma akcję, blok z `<RenderForm>` i klasy.** Każdy
kolejny formularz — także krokowy, z listami wyboru — to tylko panel. Ręcznie wpisane pola/etykiety w JSX = błąd
(ipal-audit to złapie). Szczegóły API: `docs/forms.md`, `turnstile.md`, `notifications.md`, `email.md`.
## 1. Config (raz na projekt)
@@ -29,42 +29,60 @@ export default buildConfig({
`generate:importmap`, restart.
## 2. Layout — Turnstile raz
`<TurnstileProvider siteKey={(await getTurnstileConfig(payload)).siteKey}>` w
`[locale]/layout.tsx` (turnstile.md) — **zawsze**, nie warunkuj providera ani widgetu.
`<SiteProviders shell={await getSiteShell(locale)}>` w `[locale]/layout.tsx` (PROGRAMISTA §2.8)
wpina `TurnstileProvider` z kluczem z panelu — **zawsze**, nie warunkuj providera ani widgetu.
Własny layout bez SiteProviders: `<TurnstileProvider siteKey={shell.turnstileSiteKey}>` (turnstile.md).
Zachowanie z pluginu: **oba klucze** (panel lub env) → widget widoczny, a `submitForm`
**wymaga** tokenu (bot nie ominie, nie wysyłając go); brak kluczy → widgetu nie ma,
weryfikacji nie ma, formularz działa; jeden klucz → wyłączony + alert na dashboardzie.
## 3. Kod (skopiuj z `resources/`, dostosuj tylko klasy)
## 3. Kod — import, nie kopia
Renderer, kroki, walidacja, Turnstile, honeypot, przekierowanie i zdarzenie GTM są w
pluginie. W projekcie zostają **trzy krótkie pliki**:
| Plik | Do projektu | Rola |
|---|---|---|
| `actions.ts` | `src/app/(frontend)/[locale]/actions.ts` | `export const sendForm = createSubmitAction({ getCachedPayload, headers })` — honeypot → IP → `submitForm` → tekst z Notifications |
| `seed-form.template.ts` | `scripts/seed-form-<nazwa>.ts` | formularz w bazie: pola, potwierdzenie, mail do firmy + do klienta, każdy język |
| `FormBlock.tsx` | `src/blocks/FormBlock/Component.tsx` | serwer: RichText (potwierdzenie, pola „message”), bind akcji |
| `FormRenderer.tsx` | `src/components/forms/FormRenderer.tsx` | klient: dowolny formularz z panelu przez `useForm` |
| `resources/actions.ts` | `src/app/(frontend)/[locale]/actions.ts` | `export const sendForm = createSubmitAction({ getCachedPayload, headers })` |
| `resources/FormBlock.tsx` | `src/blocks/FormBlock/Component.tsx` | `<RenderForm>` z `/rsc` + klasy projektu, w `<Section>`/`<SectionHeader>` |
| `resources/formClasses.ts` | `src/components/forms/formClasses.ts` | **jedyne** miejsce wyglądu formularzy (klasy z DESIGN.md) |
| `resources/seed-form.template.ts` | `scripts/seed-form-<nazwa>.ts` | formularz w bazie: pola, potwierdzenie, mail do firmy + do klienta, każdy język |
Renderer obsługuje typy buildera `text, email, textarea, number, select, checkbox,
message` (`country/state` jako tekst), `width` ≤ 50 → pół szerokości, `required`,
potwierdzenie albo redirect, a11y (`label for`, `aria-invalid`, `role="alert"`),
honeypot, Turnstile, zdarzenie GTM z panelu. Nie dopisuj własnej walidacji
„na sztywno” — reguły wynikają z definicji pola.
`RenderForm` (serwer) renderuje bloki „message” i potwierdzenie przez `RenderRichText`,
wiąże akcję z formularzem i językiem, rozwiązuje redirect i **wysyła do przeglądarki tylko
publiczną część formularza** (zakładka Emails z adresami firmy nigdy nie trafia do HTML).
Pod spodem `BuilderForm` (klient) — czysty, dostępny HTML **bez stylów**: wygląd = `classNames`
(+ atrybuty `data-ipal`, `data-type`, `data-width`, `data-step`).
## 4. Strona — dane do bloku przez enhanceProps (bloki nie importują `lib/*`)
**Typy pól w panelu:** text, email, textarea, number, **date**, select, **radio** (jeden wybór),
checkbox, **Checkbox group** (wiele wyborów, min/max), message, **Step** (podział na kroki).
- **Formularz krokowy:** redaktor wstawia blok **Step** (tytuł, opis) — pola pod nim to jeden
ekran. Przyciski Dalej/Wstecz i „Krok 1 z 3” z **Notifications → Form messages** (next, back,
stepOf). Dalej waliduje tylko bieżący krok; błąd z serwera wraca na krok z polem; fokus
przechodzi na nowy krok. Bez Step = jeden ekran.
- `width` ≤ 50 → klasa `fieldHalf`, inaczej `fieldFull`.
**Formularz nietypowy** (karty do wyboru zamiast radio, podsumowanie przed wysłaniem,
własny typ pola, suwak): nie kopiuj silnika — w kolejności:
1. `renderField` w `BuilderForm` (plik `'use client'`): podmieniasz wybrane pola, reszta domyślna
(`defaultRender()` daje oryginał do owinięcia);
2. własny komponent na `useBuilderForm` — pełna kontrola nad markupem, ta sama logika
(`resources/CustomForm.example.tsx`): `steps`, `step`, `next/back/goTo`, `submit`,
`getInputProps / getTextareaProps / getSelectProps / getOptionProps`, `errors`, `TurnstileWidget`.
Własny typ pola w panelu: `forms.fields: { mojTyp: { slug, fields } }` (blok form-buildera)
+ `renderField`; serwer przyjmie go jako tekst — potrzebujesz innej walidacji → **ipal-plugin-gap**.
## 4. Strona — dane do bloku raz (bloki nie importują `lib/*`)
Z `createPageRoute` (PROGRAMISTA §2.8):
```tsx
// [locale]/[[...slug]]/page.tsx
import { getNotificationTexts } from '@intecion/ipal-kit'
import { sendForm } from '../actions'
const formTexts = doc.layout?.some((b) => b.blockType === 'formBlock')
? (await getNotificationTexts({ payload: await getCachedPayload(), locale })).form
: undefined
const enhanceProps = ({ block }: { block: { blockType: string } }) => ({
locale,
...(block.blockType === 'formBlock' ? { formTexts, sendForm } : {}),
const route = createPageRoute(content, {
blocks: blockRegistry, notFound, permanentRedirect,
blockProps: async ({ locale }) => ({ formTexts: await content.getFormTexts(locale), sendForm }),
})
```
Własna strona: to samo w `enhanceProps` (`formTexts` z `getFormTexts(locale)`, `sendForm` z `actions.ts`).
Zapytanie strony: `depth` ≥ 1 (relacja `form` jako obiekt). Rejestr bloków:
`formBlock: FormBlock`. Formularz poza blokiem (stopka, modal) = ten sam
`FormRenderer` z formularzem pobranym po ID z globalu (relacja w Footer), nigdy kopia.
`formBlock: FormBlock`. Formularz poza blokiem (stopka, modal) = ten sam `<RenderForm>`
z formularzem z relacji w globalu, nigdy kopia.
## 5. Formularz w bazie — ZAWSZE seedem (`resources/seed-form.template.ts`)
Każdy formularz z briefu powstaje skryptem, nie ręcznie: wtedy jest powtarzalny (dev → produkcja),
@@ -108,7 +126,8 @@ Szczegóły, które seed już spełnia, a które sprawdzasz po każdej ręcznej
- [ ] Turnstile bez kluczy → brak widgetu, formularz przechodzi;
- [ ] drugi język → etykiety i komunikaty w tym języku;
- [ ] GTM Preview → zdarzenie z nazwą z panelu po sukcesie;
- [ ] `ipal-audit --quick` → zero hardkodów w FormRenderer/FormBlock;
- [ ] formularz krokowy: Dalej z pustym krokiem → błędy, krok zostaje; Wstecz zachowuje wpisane wartości;
- [ ] `ipal-audit --quick` → zero hardkodów w FormBlock, brak kopii silnika formularza;
- [ ] `ipal-consent-check` → nadal 0 naruszeń (Turnstile to niezbędny, nie śledzący).
## Diagnostyka
@@ -116,14 +135,10 @@ Szczegóły, które seed już spełnia, a które sprawdzasz po każdej ręcznej
|---|---|
| brak kolekcji Forms w panelu | rozjazd wersji form-buildera vs payload → ta sama wersja, `pnpm.overrides` |
| blok renderuje nic | `form` to ID (za małe `depth`) albo brak `formTexts`/`sendForm` w enhanceProps |
| `reason: 'validation'`, `kind: 'unknown_fields'` | front wysyła pole, którego formularz nie ma (honeypot nieusunięty w akcji, literówka w `name`) |
| `reason: 'validation'`, `kind: 'unknown_fields'` | front wysyła pole, którego formularz nie ma (własny renderer z dodatkowym polem, literówka w `name`) |
| przyciski „Next/Back” po angielsku | puste Notifications → Form messages → next / back / stepOf w tym języku |
| `reason: 'not_found'` | `formId` z innej bazy (seed na dev, prod inny ID) — relacja z panelu, nie stałe ID w kodzie |
| zgłoszenie jest, maila brak | brak `email: mailAdapter()`, pusta zakładka Emails, transport w panelu; logi serwera |
| zawsze `turnstile` | token jednorazowy — `ts.reset()` po błędzie (jest w rendererze); zła para kluczy / domena w Cloudflare |
| zawsze `turnstile` | zła para kluczy / domena w Cloudflare (reset tokenu po błędzie robi BuilderForm) |
| strona stała się dynamiczna (`ƒ`) | `headers()` w komponencie zamiast w akcji |
| komunikaty po angielsku | puste Notifications w tym języku |
## Znane ograniczenie pluginu
`useForm` trzyma własny stan tokenu, `useTurnstile` swój — renderer synchronizuje je
`useEffect`em. Jeśli w kolejnym projekcie to przeszkadza, zgłoś przez **ipal-plugin-gap**
(propozycja: `useForm` czyta token z `TurnstileProvider`, gdy jest w drzewie).
@@ -0,0 +1,50 @@
// Only for a form that looks or behaves unlike the default (option cards, a
// summary step, a custom field type). Same engine as BuilderForm — you write the
// markup only. Ordinary forms: RenderForm in FormBlock, no file like this.
//
// Lighter option first: <BuilderForm renderField={…}> replaces chosen fields only.
'use client'
import { honeypotInputProps, useBuilderForm, type UseBuilderFormOptions } from '@intecion/ipal-kit/client'
export function QuoteCardsForm(props: UseBuilderFormOptions) {
const f = useBuilderForm(props)
if (f.isSuccess) return <div role="status">{f.resultMessage}</div>
return (
<form onSubmit={f.submit} noValidate>
<input {...honeypotInputProps()} />
{f.total > 1 && <p aria-live="polite">{props.texts.stepOf?.replace('{current}', String(f.stepIndex + 1)).replace('{total}', String(f.total))}</p>}
{f.step.fields.map(({ field }) => {
if (!field.name) return null
if (field.blockType === 'radio') {
// options as clickable cards — still a real radio group (keyboard, screen readers)
return (
<fieldset key={field.name} id={f.fieldId(field)} aria-invalid={f.getFieldProps(field)['aria-invalid']} aria-describedby={f.getFieldProps(field)['aria-describedby']}>
<legend>{field.label}</legend>
{(field.options ?? []).map((o, i) => (
<label key={o.value} className="card">
<input {...f.getOptionProps(field, o, i)} className="sr-only" />
{o.label}
</label>
))}
{f.errors[field.name] && <p id={f.errorId(field)}>{f.errors[field.name]}</p>}
</fieldset>
)
}
return (
<div key={field.name}>
<label htmlFor={f.fieldId(field)}>{field.label}</label>
{field.blockType === 'textarea' ? <textarea {...f.getTextareaProps(field)} /> : <input {...f.getInputProps(field)} />}
{f.errors[field.name] && <p id={f.errorId(field)}>{f.errors[field.name]}</p>}
</div>
)
})}
{f.isLast && <f.TurnstileWidget />}
{f.errorMessage && <p role="alert">{f.errorMessage}</p>}
{!f.isFirst && <button type="button" onClick={f.back}>{props.texts.back}</button>}
<button type="submit" disabled={f.isSubmitting}>{f.isLast ? props.form.submitButtonLabel : props.texts.next}</button>
</form>
)
}
@@ -1,39 +1,26 @@
// src/blocks/FormBlock/Component.tsx — SERVER part: rich text from the panel + bound action.
// src/blocks/FormBlock/Component.tsx — a panel form inside a section. Logic, steps,
// validation, Turnstile, honeypot and rich text come from ipal-kit; the look is
// formClasses (one file for every form on the site).
// Block config (src/blocks/FormBlock/config.ts): slug 'formBlock', fields
// { name: 'form', type: 'relationship', relationTo: 'forms', required: true } + the
// shared section fields (eyebrow/heading/intro, anchor, background) — ipal-block.
// Page query depth ≥ 1, otherwise `form` is just an ID. Wrap the output in the
// project's <Section>/<SectionHeader> like every other block.
// Blocks never import lib/* or app/* (AGENT.md §4.10) — texts and the server action
// come in through enhanceProps from the page route (SKILL.md, step 4).
import type { ReactNode } from 'react'
// buildSectionHeaderField(), { name: 'form', type: 'relationship', relationTo: 'forms', required: true },
// buildSectionSettingsField()
// Page query depth ≥ 1, otherwise `form` is just an ID (RenderForm renders nothing).
// `formTexts` and `sendForm` arrive via createPageRoute blockProps (ipal-form SKILL §4).
import type { FormNotificationTexts } from '@intecion/ipal-kit'
import { RichText } from '@/components/RichText'
import { FormRenderer, type BuilderForm, type FormAction } from '@/components/forms/FormRenderer'
import { RenderForm, type SendFormAction } from '@intecion/ipal-kit/rsc'
import type { FormBlock as FormBlockData } from '@/payload-types'
import { formClasses } from '@/components/forms/formClasses'
import { Section } from '@/components/ui/Section'
import { SectionHeader } from '@/components/ui/SectionHeader'
type Props = {
form?: BuilderForm | string | number | null
locale: string
formTexts?: FormNotificationTexts
sendForm?: (formId: string, locale: string, values: Record<string, unknown>, token?: string) => ReturnType<FormAction>
}
export function FormBlock({ form, locale, formTexts, sendForm }: Props) {
if (!form || typeof form !== 'object' || !formTexts || !sendForm) return null // never a fake/hardcoded form
const messages: Record<number, ReactNode> = {}
form.fields?.forEach((f, i) => {
if (f.blockType === 'message' && f.message) messages[i] = <RichText data={f.message as never} />
})
const confirmation = form.confirmationMessage ? <RichText data={form.confirmationMessage as never} /> : null
type Props = FormBlockData & { locale: string; formTexts?: FormNotificationTexts; sendForm?: SendFormAction }
export function FormBlock({ form, header, settings, locale, formTexts, sendForm }: Props) {
if (!formTexts || !sendForm) return null // never a fake/hardcoded form
return (
<FormRenderer
form={form}
messages={messages}
confirmation={confirmation}
validationText={formTexts.validation}
action={sendForm.bind(null, String(form.id), locale)}
/>
<Section settings={settings}>
<SectionHeader header={header} />
<RenderForm form={form} action={sendForm} locale={locale} texts={formTexts} classNames={formClasses} />
</Section>
)
}
@@ -1,138 +0,0 @@
// src/components/forms/FormRenderer.tsx — CLIENT part: renders ANY form built in the panel.
// Logic from ipal-kit, markup + classes are the project's (restyle freely, keep the wiring).
'use client'
import { useEffect, useMemo, type ReactNode } from 'react'
import { useRouter } from 'next/navigation'
import {
useForm, buildValidator, required, email, checked, honeypotInputProps,
useTurnstile, formAnalyticsOnSuccess, type FormAnalyticsConfig,
} from '@intecion/ipal-kit/client'
type Option = { label?: string | null; value: string }
export type BuilderField = {
blockType: 'text' | 'textarea' | 'email' | 'number' | 'select' | 'checkbox' | 'country' | 'state' | 'message' | string
name?: string | null
label?: string | null
required?: boolean | null
width?: number | null
defaultValue?: unknown
options?: Option[] | null
message?: unknown
}
export type BuilderForm = {
id: string | number
fields?: BuilderField[] | null
submitButtonLabel?: string | null
confirmationType?: 'message' | 'redirect' | null
confirmationMessage?: unknown
redirect?: { url?: string | null } | null
analytics?: FormAnalyticsConfig
}
export type FormAction = (values: Record<string, unknown>, turnstileToken?: string) => Promise<{ success: boolean; message?: string }>
type Props = {
form: BuilderForm
action: FormAction
messages: Record<number, ReactNode>
confirmation: ReactNode
/** Notifications → form.validation, may contain {field}. */
validationText: string
}
export function FormRenderer({ form, action, messages, confirmation, validationText }: Props) {
const router = useRouter()
const ts = useTurnstile() // needs <TurnstileProvider> in the layout (siteKey may be empty → disabled)
const fields = (form.fields ?? []).filter((f) => f.blockType !== 'message' && f.name)
const msg = (f: BuilderField) => validationText.replace('{field}', f.label || f.name || '')
const initialValues = useMemo(
() => Object.fromEntries(fields.map((f) => [f.name as string, f.blockType === 'checkbox' ? Boolean(f.defaultValue) : (f.defaultValue as string) ?? ''])),
// eslint-disable-next-line react-hooks/exhaustive-deps
[form.id],
)
const validate = useMemo(
() =>
buildValidator<Record<string, unknown>>(
Object.fromEntries(
fields.map((f) => {
const rules = []
if (f.required) rules.push(f.blockType === 'checkbox' ? checked(msg(f)) : required(msg(f)))
if (f.blockType === 'email') rules.push(email(msg(f)))
return [f.name as string, rules]
}),
),
),
// eslint-disable-next-line react-hooks/exhaustive-deps
[form.id, validationText],
)
const f = useForm({
initialValues,
validate,
submitAction: action,
requireTurnstile: ts.enabled,
onSuccess: (result, values) => {
formAnalyticsOnSuccess(form.analytics)(result, values)
if (form.confirmationType === 'redirect' && form.redirect?.url) router.push(form.redirect.url)
},
})
// Turnstile token lives in the provider; the form engine needs it too.
useEffect(() => f.setTurnstileToken(ts.token), [ts.token]) // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => { if (f.errorMessage) ts.reset() }, [f.errorMessage]) // eslint-disable-line react-hooks/exhaustive-deps
if (f.isSuccess && form.confirmationType !== 'redirect') return <div role="status">{confirmation}</div>
return (
<form onSubmit={f.handleSubmit} noValidate className="grid grid-cols-12 gap-4">
<input {...honeypotInputProps()} />
{(form.fields ?? []).map((field, i) => {
if (field.blockType === 'message') return <div key={i} className="col-span-12">{messages[i]}</div>
const name = field.name as string
const id = `f-${String(form.id)}-${name}`
const error = f.errors[name]
const span = field.width && field.width <= 50 ? 'col-span-12 md:col-span-6' : 'col-span-12'
const common = {
id, name, required: Boolean(field.required),
'aria-invalid': Boolean(error) || undefined,
'aria-describedby': error ? `${id}-err` : undefined,
}
const value = f.values[name]
return (
<div key={name} className={span}>
{field.blockType === 'checkbox' ? (
<label htmlFor={id} className="flex items-start gap-2">
<input type="checkbox" {...common} checked={Boolean(value)} onChange={(e) => f.setField(name, e.target.checked)} />
<span>{field.label}</span>
</label>
) : (
<>
<label htmlFor={id} className="mb-1 block">{field.label}</label>
{field.blockType === 'textarea' ? (
<textarea {...common} rows={5} value={String(value ?? '')} onChange={(e) => f.setField(name, e.target.value)} />
) : field.blockType === 'select' ? (
<select {...common} value={String(value ?? '')} onChange={(e) => f.setField(name, e.target.value)}>
<option value="" />
{(field.options ?? []).map((o) => <option key={o.value} value={o.value}>{o.label ?? o.value}</option>)}
</select>
) : (
<input
{...common}
type={field.blockType === 'email' ? 'email' : field.blockType === 'number' ? 'number' : 'text'}
autoComplete={field.blockType === 'email' ? 'email' : undefined}
value={String(value ?? '')}
onChange={(e) => f.setField(name, e.target.value)}
/>
)}
</>
)}
{error && <p id={`${id}-err`} className="mt-1 text-sm text-red-600">{error}</p>}
</div>
)
})}
<div className="col-span-12"><ts.TurnstileWidget /></div>
{f.errorMessage && <p role="alert" className="col-span-12 text-red-600">{f.errorMessage}</p>}
<div className="col-span-12">
<button type="submit" disabled={f.isSubmitting}>{form.submitButtonLabel}</button>
</div>
</form>
)
}
@@ -0,0 +1,29 @@
// src/components/forms/formClasses.ts — the ONLY place forms are styled. Every
// panel form (RenderForm / BuilderForm) uses it. Values = the project's design
// tokens (DESIGN.md); the plugin ships no styles. Delete keys you don't need.
import type { BuilderFormClassNames } from '@intecion/ipal-kit/client'
export const formClasses: BuilderFormClassNames = {
form: 'grid gap-6',
progress: 'text-sm text-muted', // "Krok 1 z 3"
step: 'grid gap-4',
stepTitle: 'text-h3 font-semibold',
stepDescription: 'text-muted',
fields: 'grid grid-cols-12 gap-4',
field: 'col-span-12',
fieldHalf: 'md:col-span-6', // width ≤ 50 in the panel
label: 'mb-1 block font-medium',
input: 'w-full rounded-md border border-border px-3 py-2',
textarea: 'w-full rounded-md border border-border px-3 py-2',
select: 'w-full rounded-md border border-border px-3 py-2',
checkboxLabel: 'flex items-start gap-2',
choices: 'grid gap-2', // radio / checkbox group <fieldset>
legend: 'mb-1 font-medium',
choice: 'flex items-center gap-2',
error: 'mt-1 text-sm text-danger',
formError: 'text-danger',
actions: 'flex gap-3',
back: 'btn btn-secondary', // same classes as Button.tsx variants
submit: 'btn btn-primary',
success: 'rounded-md bg-surface p-6',
}
@@ -27,6 +27,13 @@ const FORM = {
{ blockType: 'email', name: 'email', required: true, width: 50, label: { pl: 'E-mail', en: 'E-mail' } },
{ blockType: 'text', name: 'phone', required: false, width: 50, label: { pl: 'Telefon', en: 'Phone' } },
{ blockType: 'textarea', name: 'message', required: true, width: 100, label: { pl: 'Wiadomość', en: 'Message' } },
// Step-by-step form: a `step` block starts a new screen (title/description per language).
// { blockType: 'step', title: { pl: 'Projekt', en: 'Project' } },
// Choice lists (option labels per language, values stay the same):
// { blockType: 'radio', name: 'budget', required: true, label: { pl: 'Budżet', en: 'Budget' },
// options: [{ value: 's', label: { pl: 'do 10 tys.', en: 'up to 10k' } }, …] },
// { blockType: 'checkboxGroup', name: 'services', maxSelected: 3, label: {…}, options: [ …same shape… ] },
// { blockType: 'date', name: 'deadline', label: { pl: 'Termin', en: 'Deadline' } },
// GDPR consent — name MUST stay `consent`; never pre-ticked (the plugin enforces it server-side).
{
blockType: 'checkbox',
@@ -112,6 +119,20 @@ if (!/^[^\s@,;]+@[^\s@,;]+\.[^\s@,;]+$/.test(notifyTo)) {
process.exit(1)
}
/** A field with every per-language text ({ pl, en }) resolved: label, step title/description, option labels. */
function localizeField(field: Record<string, unknown>, locale: string): Record<string, unknown> {
const text = (v: unknown) => (v && typeof v === 'object' ? pick(v as Localized, locale) : v)
return {
...field,
...('label' in field ? { label: text(field.label) } : {}),
...('title' in field ? { title: text(field.title) } : {}),
...('description' in field ? { description: text(field.description) } : {}),
...(Array.isArray(field.options)
? { options: (field.options as Record<string, unknown>[]).map((o) => ({ ...o, label: text(o.label) })) }
: {}),
}
}
/** Form data in one locale (localized fields resolved for it). */
function dataFor(locale: string) {
return {
@@ -131,7 +152,7 @@ function dataFor(locale: string) {
subject: pick(FORM.confirmationEmail.subject, locale),
},
],
fields: FORM.fields.map(({ label, ...field }) => ({ ...field, label: pick(label, locale) })),
fields: FORM.fields.map((field) => localizeField(field as Record<string, unknown>, locale)),
submitButtonLabel: pick(FORM.submitButtonLabel, locale),
title: FORM.title,
}
@@ -155,7 +176,7 @@ if (!id) {
for (const locale of locales.filter((l) => l !== defaultLocale)) {
const doc = (await payload.findByID({ collection: 'forms' as never, depth: 0, id, locale: locale as never })) as {
emails?: { id?: string }[]
fields?: { id?: string }[]
fields?: { id?: string; options?: { id?: string }[] }[]
}
const d = dataFor(locale)
await payload.update({
@@ -163,7 +184,14 @@ for (const locale of locales.filter((l) => l !== defaultLocale)) {
data: {
...d,
emails: d.emails.map((e, i) => ({ ...e, id: doc.emails?.[i]?.id })),
fields: d.fields.map((f, i) => ({ ...f, id: doc.fields?.[i]?.id })),
// Keep row ids (fields and their options) — new ids would wipe the other languages' texts.
fields: d.fields.map((f, i) => ({
...f,
id: doc.fields?.[i]?.id,
...(Array.isArray(f.options)
? { options: (f.options as Record<string, unknown>[]).map((o, j) => ({ ...o, id: doc.fields?.[i]?.options?.[j]?.id })) }
: {}),
})),
} as never,
id,
locale: locale as never,
+5 -4
View File
@@ -1,6 +1,6 @@
---
name: ipal-nav
description: Builds the site header, footer, mobile menu and company data in an ipal-kit project — Header/Footer/Company globals with buildLinkField from the plugin, server-side link resolution (resolveNav), a small client MobileNav, legal links from System Pages, revalidation on change. Use when creating or changing navigation, menu, header, footer, contact details, social links or the company global.
description: Builds the site header, footer, mobile menu and company data in an ipal-kit project — Header/Footer/Company globals with buildLinkField from the plugin, server-side link resolution (resolveNav from the plugin), a small client MobileNav, legal links from System Pages, revalidation on change. Use when creating or changing navigation, menu, header, footer, contact details, social links or the company global.
---
# ipal-nav
@@ -19,10 +19,11 @@ Wymaga prymitywów z `../ipal-block/resources/kod-sekcji.md` (jak skill ipal-blo
(teksty localized), `access.read: () => true`.
2. Hook `afterChange` na każdym globalu: `revalidatePath('/', 'layout')`
(wstrzyknięty z `next/cache`, hooks.md).
3. `src/lib/navigation.ts` (`resolveNav`) — linki rozwiązane na serwerze do
`{ href, label, newTab, subItems }`.
3. Menu: `await resolveNav(header.navItems, locale)` z `lib/content` (plugin) — linki
rozwiązane na serwerze do `{ href, label, internal, newTab, targetProps, children }`.
Nie twórz `lib/navigation.ts`.
4. `src/components/layout/Header.tsx`, `Footer.tsx` (serwer), `MobileNav.tsx`
(`'use client'`, tylko stan otwarcia, dane przez props, `import type` z lib).
(`'use client'`, tylko stan otwarcia, dane przez props, `import type { NavItem } from '@intecion/ipal-kit'`).
5. **Linki prawne w stopce** z ról System Pages (`getSystemPagePath` + tytuł
strony) — nie jako ręczne pozycje. Rok w copyright z kodu, nazwa z `Company`.
6. Logo z Site Settings przez `<Media>` — nie duplikuj pola w Header.
@@ -86,49 +86,16 @@ export const Footer: GlobalConfig = {
- **Odświeżanie:** global zmienia się na każdej stronie → hook `afterChange`
z `revalidatePath('/', 'layout')` (hooks.md).
Linki rozwiązuj **na serwerze** do zwykłych danych, a do klienta (menu mobilne)
przekazuj tylko `{ href, label, newTab }` — komponent kliencki nie może wołać
`CMSLink` (to async server component).
Menu z globala rozwiązuje plugin: `await resolveNav(header.navItems, locale)` z `lib/content`
→ `{ href, label, internal, newTab, targetProps, children }[]` (martwe linki pominięte, dowolna
głębokość). To zwykłe dane — idą wprost do klienckiego `MobileNav`. Nie twórz `lib/navigation.ts`.
```ts
// src/lib/navigation.ts
import { resolveLinkHref } from '@intecion/ipal-kit'
import type { CmsLink } from '@/payload-types'
import { i18nConfig } from '@/i18n.config'
import { getSettings } from '@/lib/content'
export type NavItem = { href: string; label: string; newTab: boolean; subItems: NavItem[] }
type NavSource = { link?: CmsLink | null; subItems?: { link?: CmsLink | null }[] | null }
function toNavItem(link: CmsLink | null | undefined, locale: string, homeSlug?: string): NavItem | null {
const href = resolveLinkHref(link, { locale, config: i18nConfig, homeSlug })
if (!link || !href || !link.label) return null
return { href, label: link.label, newTab: Boolean(link.newTab), subItems: [] }
}
export async function resolveNav(items: NavSource[] | null | undefined, locale: string): Promise<NavItem[]> {
const settings = await getSettings(locale)
const home = settings?.homepage
const homeSlug = home && typeof home === 'object' && typeof home.slug === 'string' ? home.slug : undefined
return (items ?? []).flatMap((item) => {
const node = toNavItem(item.link, locale, homeSlug)
if (!node) return []
node.subItems = (item.subItems ?? []).flatMap((sub) => {
const child = toNavItem(sub.link, locale, homeSlug)
return child ? [child] : []
})
return [node]
})
}
```
```tsx
// src/components/layout/Header.tsx — serwer
import Link from 'next/link'
import type { Header as HeaderData } from '@/payload-types'
import { resolveNav } from '@/lib/navigation'
import { resolveNav } from '@/lib/content'
import { CMSLink } from '@/components/ui/CMSLink'
import { MobileNav } from './MobileNav'
@@ -141,9 +108,7 @@ export async function Header({ header, locale }: { header: HeaderData; locale: s
<ul className="hidden gap-6 md:flex">
{items.map((item) => (
<li key={item.href}>
<Link href={item.href} {...(item.newTab ? { target: '_blank', rel: 'noopener noreferrer' } : {})}>
{item.label}
</Link>
<Link href={item.href} {...item.targetProps}>{item.label}</Link>
</li>
))}
</ul>
@@ -160,7 +125,7 @@ export async function Header({ header, locale }: { header: HeaderData; locale: s
'use client'
import { useState } from 'react'
import Link from 'next/link'
import type { NavItem } from '@/lib/navigation' // import TYPU — nie ciągnie kodu serwera
import type { NavItem } from '@intecion/ipal-kit' // import TYPU — nie ciągnie kodu serwera
export function MobileNav({ items, menuLabel }: { items: NavItem[]; menuLabel: string }) {
const [open, setOpen] = useState(false)
+2 -2
View File
@@ -28,8 +28,8 @@ Sprawdza **działającą** aplikację, nie kod — dokładnie to, co dostaje Goo
| unknown URL returns 200 | brak `notFound()` w catch-all |
| sitemap URLs not 200 | w sitemapie adresy z przekierowaniem (stare slugi) |
| robots.txt points to localhost | `NEXT_PUBLIC_SERVER_URL` nieustawione w buildzie |
| no JSON-LD structured data | brak `<JsonLdGraph>` w `[locale]/layout.tsx` albo pusta nazwa w Site Settings |
| `/llms.txt` / `/llms-full.txt` → 404 | brak trasy `createLlmsTxtRoute` (drugiej z `full: true`) |
| no JSON-LD structured data | brak `<SiteProviders>` / `<JsonLdGraph>` w `[locale]/layout.tsx` albo pusta nazwa w Site Settings |
| `/llms.txt` / `/llms-full.txt` → 404 | brak trasy (`export { llmsRoute as GET }` / `llmsFullRoute` z `lib/content`) |
| Markdown version `/md/…` → 404 | brak `src/app/md/[locale]/[[...slug]]/route.ts`; strona noindex/draft |
| MCP not answering initialize | brak `src/app/api/mcp/route.ts` albo Cloudflare Access bez Bypass (mcp.md) |
+10 -10
View File
@@ -38,19 +38,19 @@ tylko, gdy użytkownik o to poprosi. Pełna budowa strony: skill **ipal-site**.
Impeccable albo załóż neutralne tokeny), `fluid.css` lub `fluid-wide.css` (AGENT §6.11a), fonty
przez `next/font` z `latin-ext`, `@source` na plugin (AGENT.md §6.11, przykład w `../ipal-block/resources/kod-sekcji.md`).
6. **Routing** — `proxy.ts` (`createProxy(i18nConfig, { NextResponse, markdown: true })`), `lib/content.ts`
(`markdownAlternate: true`), layout bez `<head>` z `JsonLdGraph`, `TurnstileProvider`
(`getTurnstileConfig`), consent (`equalChoice`, `logEndpoint`) i `Analytics` (PROGRAMISTA §2.8),
catch-all z ISR + `generateStaticParams` + `resolveRedirect` + `getPageJsonLd`,
`not-found.tsx` z `LocaleView` — bez `headers()`, wersja na każdy język (PROGRAMISTA §2.6–2.8, pages.md).
7. **SEO i bezpieczeństwo** — sitemap (`sitemap.xml/route.ts` = `sitemapRoute`, bez CSS w `public/`), robots, manifest, health
(z `force-dynamic`), `htmlLimitedBots`, `buildSecurityHeaders`, `buildUploadSecurityHeaders`,
(`createContentHelpers` z `markdownAlternate: true`, `summaryField`, `mcp` — PROGRAMISTA §2.7),
layout bez `<head>`: `<SiteProviders shell={await getSiteShell(locale)} logEndpoint banner={<CookieBanner equalChoice />}>`,
catch-all: `createPageRoute(content, { blocks, notFound, permanentRedirect, blockProps })` + literał `revalidate`,
`not-found.tsx`: `createNotFoundPage(content, { blocks })` (PROGRAMISTA §2.6–2.8, pages.md).
7. **SEO i bezpieczeństwo** — sitemap, robots, manifest, health jako re-eksporty z `lib/content`
(`sitemapRoute`, `robots`, `manifest`, `healthRoute`; z `force-dynamic` poza robots; bez CSS w `public/`), `htmlLimitedBots`, `buildSecurityHeaders`, `buildUploadSecurityHeaders`,
`images: buildImagesConfig()`,
`instrumentation.ts` z `assertEnv(ipalEnvRules({ storage: true, ipHeader: true }))` z `@intecion/ipal-kit/env` (PROGRAMISTA §2.8–2.9, env.md).
8. **GEO (obowiązkowe)** — `llms.txt`, `llms-full.txt` (`full: true`), `md/[locale]/[[...slug]]/route.ts`
(`createMarkdownRoute`), `api/mcp/route.ts` (publiczny), `indexnow-key.txt/route.ts`,
`summaryField: 'aiSummary'` w trasach AI; robots
8. **GEO (obowiązkowe)** — re-eksporty z `lib/content`: `llms.txt` (`llmsRoute`), `llms-full.txt`
(`llmsFullRoute`), `md/[locale]/[[...slug]]/route.ts` (`markdownRoute`), `api/mcp/route.ts`
(`mcpGET`/`mcpPOST`, publiczny), `indexnow-key.txt/route.ts` (`indexNowKeyRoute`); robots
wpuszcza boty AI (PROGRAMISTA §2.8, AGENT.md §0b.5–8).
9. **Formularze** — skill **ipal-form**: renderer + `createSubmitAction` raz, każdy formularz z seeda
9. **Formularze** — skill **ipal-form**: blok z `<RenderForm>`, `formClasses.ts`, `createSubmitAction` raz, każdy formularz z seeda
(mail do firmy + potwierdzenie do klienta). Cookies: skan + import (ipal-consent-check), `<CookieTable>`
na stronie polityki cookies.
10. **Nawigacja** — skill **ipal-nav**.
+8
View File
@@ -30,6 +30,14 @@ nie dodatek. Pomijasz tylko z decyzją klienta w `AGENTS.md` (`ipal-audit-skip:`
wymagany — sprawdź, że każdy formularz ma widget); `clientIp(await headers())` w
akcji formularza + `IPAL_IP_HEADER` w env produkcji; `buildR2Storage` wpięty.
**→ 1.9.2 (PROGRAMISTA §6, poz. 28–33) — import zamiast kodu, zacznij od poz. 28 (bezpieczeństwo):**
własny `FormRenderer` przekazywał do HTML zakładkę Emails (adresy firmy) → blok z `<RenderForm>` +
`formClasses.ts`, usuń renderer. Potem: layout → `SiteProviders`, strona i 404 → `createPageRoute` /
`createNotFoundPage`, trasy GEO → re-eksporty z `lib/content`, `src/fields/section*.ts` i
`lib/navigation.ts` → `buildSection*Field`, `resolveNav`, `resolveLink`. Każdą pozycję sprawdź w
przeglądarce (formularz: wysyłka + mail; strona: 200, 404, metadata). Postgres: `migrate:create`
(nowe typy pól formularza i teksty w Notifications).
## 2. Inwentaryzacja (bez zmian w kodzie)
Dla **każdej** pozycji tabeli PROGRAMISTA §6 pokaż dowód (grep / plik), czy
dotyczy projektu. Uruchom skill **ipal-audit** (`--quick`) i dołącz wynik.
+17
View File
@@ -74,6 +74,23 @@ const enhanceProps = ({ block, allBlocks }) => {
<RenderBlocks blocks={page.layout} components={registry} enhanceProps={enhanceProps} />
```
## Wspólne pola sekcji — `buildSectionHeaderField`, `buildSectionSettingsField`
```ts
import { buildLinksField, buildSectionHeaderField, buildSectionSettingsField } from '@intecion/ipal-kit'
fields: [
buildSectionHeaderField(), // grupa `header`: eyebrow, heading, intro (localized) — typ SectionHeaderData
…pola bloku…,
buildLinksField(),
buildSectionSettingsField(), // sidebar `settings`: anchor, background — typ SectionSettings
]
```
Wszystko do zmiany: `buildSectionSettingsField({ backgrounds: [{ label: 'Brand', value: 'brand' }], anchor: false,
fields: [{ name: 'spacing', … }] })`, `backgrounds: false` (bez wyboru tła), `buildSectionHeaderField({ name, fields,
interfaceName })`. Wartości tła mapuje na klasy `<Section>` projektu. Kształt danych taki jak dawne
`src/fields/sectionHeader.ts` / `sectionSettings.ts` z kod-sekcji.md — zamiana importu nie wymaga migracji.
## Komponent bloku
Każdy komponent dostaje dane bloku jako propsy (plus `_components`, plus to co
+8
View File
@@ -36,6 +36,14 @@ okazji aktualizacji.
## Front — Provider + banner
Zwykle jedną linią w layoutcie (PROGRAMISTA §2.8) — `SiteProviders` (`/rsc`) wpina provider,
baner, przycisk i `Analytics` w dobrej kolejności, z tekstami z `getSiteShell(locale).consent`:
```tsx
<SiteProviders shell={await getSiteShell(locale)} logEndpoint="/api/ipal/consent"
banner={<CookieBanner equalChoice classNames={…} />}>{children}</SiteProviders>
```
Ręcznie (własny układ) — to samo z pojedynczych części:
Provider owija aplikację, banner i button renderują się same. Import z
`@intecion/ipal-kit/client`:
+1 -1
View File
@@ -224,7 +224,7 @@ round-trip do bazy i zwraca 200/503, więc Coolify/Docker odróżni „proces ż
od „app gotowa, baza dostępna":
```ts
// app/api/health/route.ts
// app/api/health/route.ts — zwykle: export { healthRoute as GET } from '@/lib/content'
import { createHealthRoute } from '@intecion/ipal-kit'
import { getCachedPayload } from '@/lib/content'
export const dynamic = 'force-dynamic' // nigdy nie prerenderuj/cache'uj health
+77 -99
View File
@@ -150,10 +150,11 @@ sprawdzić: **AGENT.md §0b**. Kod wszystkich tras niżej (§2.7–2.9).
- `Media`: upload z `mimeTypes` (obrazy + PDF), `alt` (required, localized),
`normalizeFilenameHook`, `buildOptimizeUploadHook` + `buildOptimizeUploadField` (za duże pliki, za zgodą); R2 przez `buildR2Storage(['media'], { s3Storage })` —
`s3Storage` z `@payloadcms/storage-s3`, wstrzykiwany (storage.md).
- Linki z pluginu (`buildLinkField`, `buildLinksField`, `resolveLinkHref` — links.md),
`src/fields/` (sectionHeader, sectionSettings) i `src/components/ui/`
(CMSLink, Button, Media, Section, SectionHeader) — gotowy kod w
`agent/skills/ipal-block/resources/kod-sekcji.md`, reguły w AGENT.md §6.
- Pola z pluginu: linki (`buildLinkField`, `buildLinksField` — links.md), nagłówek i ustawienia
sekcji (`buildSectionHeaderField`, `buildSectionSettingsField` — blocks.md). W projekcie tylko
prymitywy wyglądu `src/components/ui/` (CMSLink na `resolveLink`, Button, Media, Section,
SectionHeader) i `src/components/forms/formClasses.ts` — gotowy kod w
`agent/skills/ipal-block/resources/kod-sekcji.md` i `ipal-form/resources/`, reguły w AGENT.md §6.
Załóż je **przed** pierwszym blokiem.
### 2.5 Tailwind
@@ -207,36 +208,44 @@ layoutach i `not-found.tsx` **nie czytaj `headers()`** (AGENT.md §4.6).
### 2.7 Warstwa danych — jedno źródło
```ts
// src/lib/content.ts
// src/lib/content.ts — JEDYNE miejsce konfiguracji: dane, trasy, linki, layout
import { createContentHelpers } from '@intecion/ipal-kit'
import config from '@/payload.config'
import { i18nConfig } from '@/i18n.config'
import { contentConfig } from '@/content.config'
export const {
getCachedPayload, getSettings, getConfiguredLocales, resolveRoute, getEntries, getPageJsonLd,
generatePageMetadata, getNotFoundPage, generateStaticParams, sitemap, robots,
// dane
getCachedPayload, getSettings, getConfiguredLocales, resolveRoute, getEntries, getNotFoundPage,
generatePageMetadata, generateStaticParams, getPageJsonLd, resolvePageRedirect, i18n,
// layout, formularze, linki
getSiteShell, getFormTexts, getLinkOptions, getHomeSlug, resolveLink, resolveNav,
// trasy (re-eksport w app/)
sitemap, sitemapRoute, robots, manifest, llmsRoute, llmsFullRoute, markdownRoute,
mcpGET, mcpPOST, healthRoute, indexNowKeyRoute,
} = createContentHelpers({
config,
content: contentConfig,
i18n: i18nConfig,
baseUrl: process.env.NEXT_PUBLIC_SERVER_URL,
markdownAlternate: true, // GEO: <link rel="alternate" type="text/markdown"> w każdej stronie
markdownAlternate: true, // GEO: <link rel="alternate" type="text/markdown"> w każdej stronie
summaryField: 'aiSummary', // llms.txt i MCP biorą opis dla AI z buildSummaryField
mcp: { serverName: '<klient>-site' },
// pageJsonLd: { faq: (doc) => …mapowanie bloku FAQ na { question, answer }… },
// siteJsonLd: async ({ settings, baseUrl, locale }) => [buildLocalBusinessJsonLd({…})], // firma lokalna
})
```
Wszystko liczy się dopiero przy pierwszym użyciu i jest w cache na żądanie. Każdą
funkcję można pominąć i złożyć stronę z niższych klocków (`createPageMetadata`,
`createLlmsTxtRoute`, `createMcpRoute`… — seo.md, mcp.md) — plugin niczego nie wymusza.
### 2.8 Trasy
```tsx
// src/app/(frontend)/[locale]/layout.tsx
import { notFound } from 'next/navigation'
import {
buildOrganizationJsonLd, buildWebSiteJsonLd, getAnalyticsConfig, getConsentTexts, getTurnstileConfig, sameAsUrls,
} from '@intecion/ipal-kit'
import { Analytics, ConsentProvider, CookieBanner, CookieButton, TurnstileProvider } from '@intecion/ipal-kit/client'
import { JsonLdGraph, MediaPreconnect } from '@intecion/ipal-kit/rsc'
import { i18nConfig } from '@/i18n.config'
import { getCachedPayload, getConfiguredLocales, getSettings } from '@/lib/content'
import { CookieBanner } from '@intecion/ipal-kit/client'
import { SiteProviders } from '@intecion/ipal-kit/rsc'
import { getConfiguredLocales, getSiteShell } from '@/lib/content'
import '../styles.css'
type Props = { children: React.ReactNode; params: Promise<{ locale: string }> }
@@ -244,88 +253,64 @@ type Props = { children: React.ReactNode; params: Promise<{ locale: string }> }
export default async function LocaleLayout({ children, params }: Props) {
const { locale } = await params
if (!(await getConfiguredLocales()).includes(locale)) notFound()
const payload = await getCachedPayload()
const [texts, analytics, turnstile, settings] = await Promise.all([
getConsentTexts({ config: i18nConfig, locale, payload }), // link do polityki — automatycznie (consent.md)
getAnalyticsConfig(payload),
getTurnstileConfig(payload), // siteKey tylko przy obu kluczach — inaczej widget i weryfikacja wyłączone
getSettings(locale),
])
const url = process.env.NEXT_PUBLIC_SERVER_URL
const name = typeof settings?.siteName === 'string' ? settings.siteName : undefined
// Dane z panelu; brak → węzeł pominięty (nigdy fallback z nazwą klienta). Firma lokalna: buildLocalBusinessJsonLd z globalu Company.
const schemas = name && url
? [buildWebSiteJsonLd({ name, url }), buildOrganizationJsonLd({ name, url, logo: settings.logo, sameAs: sameAsUrls(settings) })]
: []
// + buildNavigationJsonLd({ items: header.navItems, … }) z globala nagłówka (seo.md)
const shell = await getSiteShell(locale) // zgoda, analityka, Turnstile, JSON-LD strony, Site Settings
return (
<html lang={locale}>
{/* BEZ <head> — Next zarządza nim sam */}
<body>
<MediaPreconnect />
<JsonLdGraph schemas={schemas} />
<ConsentProvider texts={texts} logEndpoint="/api/ipal/consent">
<TurnstileProvider siteKey={turnstile.siteKey}> {/* zawsze — sam się wyłącza bez kluczy */}
<main>{children}</main>
</TurnstileProvider>
<CookieBanner equalChoice />
<CookieButton />
<Analytics {...analytics} /> {/* wewnątrz providera; opcja defer — analytics.md */}
</ConsentProvider>
<SiteProviders shell={shell} logEndpoint="/api/ipal/consent" banner={<CookieBanner equalChoice />}>
{/* <Header …/> */}
<main>{children}</main>
{/* <Footer …/> */}
</SiteProviders>
</body>
</html>
)
}
```
`SiteProviders` wpina w dobrej kolejności: `MediaPreconnect`, `JsonLdGraph` (WebSite + Organization
z Site Settings), `ConsentProvider` → `TurnstileProvider` (zawsze — sam się wyłącza bez kluczy) →
baner, `CookieButton`, `Analytics` (wewnątrz zgody). Nie dodaje żadnego markupu. Każdą część
zmienisz albo wyłączysz: `banner={<CookieBanner classNames={…} />}` / `false`, `cookieButton`,
`analytics={{ defer: true }}` / `false`, `jsonLd={[buildNavigationJsonLd(…)]}`, `cookieMap`,
`preconnect={false}`. Zupełnie własny układ: te same dane z `shell` do providerów (consent.md).
```tsx
// src/app/(frontend)/[locale]/[[...slug]]/page.tsx — PODWÓJNE nawiasy
import { notFound, permanentRedirect } from 'next/navigation'
import type { Metadata } from 'next'
import { JsonLdGraph, RenderBlocks } from '@intecion/ipal-kit/rsc'
import { resolveRedirect } from '@intecion/ipal-kit'
import { i18nConfig } from '@/i18n.config'
import { createPageRoute } from '@intecion/ipal-kit/rsc'
import * as content from '@/lib/content'
import { blockRegistry } from '@/blocks/registry'
import { generatePageMetadata, getCachedPayload, getPageJsonLd, resolveRoute } from '@/lib/content'
import { sendForm } from '../actions'
export { generateStaticParams } from '@/lib/content' // SSG → <head> synchroniczny
export const revalidate = 3600 // ISR
export const revalidate = 3600 // ISR — literał w pliku (Next czyta go statycznie)
type Args = { params: Promise<{ locale: string; slug?: string[] }> } // bez searchParams!
// Ten sam cache co strona: jedno odczytanie ustawień i jedno resolveRoute na żądanie
export async function generateMetadata({ params }: Args): Promise<Metadata> {
const { locale, slug } = await params
return generatePageMetadata(locale, slug)
}
export default async function Page({ params }: Args) {
const { locale, slug } = await params
const route = await resolveRoute(locale, slug ?? [], 1)
if (!route) {
const target = await resolveRedirect({ payload: await getCachedPayload(), locale, segments: slug, config: i18nConfig })
if (target) permanentRedirect(target)
notFound()
}
const enhanceProps = () => ({ locale }) // locale dla CMSLink w blokach
const doc = route.doc as { layout?: unknown[] }
return (
<>
<JsonLdGraph schemas={await getPageJsonLd(locale, slug)} /> {/* WebPage/BlogPosting, okruszki, FAQ */}
<RenderBlocks blocks={doc.layout as never} components={blockRegistry} enhanceProps={enhanceProps} />
</>
)
}
const route = createPageRoute(content, {
blocks: blockRegistry,
notFound, permanentRedirect, // wstrzyknięte z next/navigation
blockProps: async ({ locale }) => ({ formTexts: await content.getFormTexts(locale), sendForm }),
// render: ({ route, blocks }) => route.type === 'archive' ? <Archive … /> : undefined,
})
export default route.Page
export const generateMetadata = route.generateMetadata
export const generateStaticParams = route.generateStaticParams // SSG → <head> synchroniczny
```
Opcje `resolveRedirect` (`collections`, `homeSlug`): content.md.
Archiwum z paginacją (`?page=`) — osobna trasa albo świadomie dynamiczna (pages.md).
`createPageRoute`: trasa (`resolveRoute`), stary slug → 308 (`resolvePageRedirect`), 404, metadata,
`generateStaticParams`, JSON-LD strony (`getPageJsonLd`, wyłączenie: `jsonLd: false`) i bloki z
`locale` + `blockProps`. Bez `searchParams` — archiwum z paginacją (`?page=`) to osobna trasa albo
świadomie dynamiczna (pages.md). Własna strona: te same helpery ręcznie (pages.md).
404 z panelu: `src/app/(frontend)/[locale]/not-found.tsx` z `getNotFoundPage`
(przykład w pages.md).
```tsx
// src/app/(frontend)/[locale]/not-found.tsx — 404 z panelu, w języku z URL, bez headers()
import { createNotFoundPage } from '@intecion/ipal-kit/rsc'
import * as content from '@/lib/content'
import { blockRegistry } from '@/blocks/registry'
export default createNotFoundPage(content, { blocks: blockRegistry /*, fallback: <h1>404</h1> */ })
```
```ts
// Trasy SEO / GEO / ops — każda to re-eksport, konfiguracja jest w lib/content.ts
// src/app/sitemap.xml/route.ts — XML dla Google, wygląd dla ludzi z pluginu (nic w /public)
export { sitemapRoute as GET } from '@/lib/content'
export const dynamic = 'force-dynamic'
@@ -334,43 +319,29 @@ export const dynamic = 'force-dynamic'
export { robots as default } from '@/lib/content'
// src/app/manifest.ts
import { createManifestHandler } from '@intecion/ipal-kit'
import { getCachedPayload } from '@/lib/content'
import { i18nConfig } from '@/i18n.config'
export { manifest as default } from '@/lib/content'
export const dynamic = 'force-dynamic'
export default createManifestHandler({ getCachedPayload, config: i18nConfig })
// ---- GEO: wszystkie poniżej są obowiązkowe (AGENT.md §0b.5–7) ----
// src/app/llms.txt/route.ts (+ llms-full.txt/route.ts: to samo z `full: true`)
import { createLlmsTxtRoute } from '@intecion/ipal-kit'
// ---- GEO: wszystkie poniżej są obowiązkowe (AGENT.md §0b.5–8) ----
// src/app/llms.txt/route.ts (+ llms-full.txt/route.ts: llmsFullRoute)
export { llmsRoute as GET } from '@/lib/content'
export const dynamic = 'force-dynamic'
export const GET = createLlmsTxtRoute({ getCachedPayload, config: i18nConfig,
baseUrl: process.env.NEXT_PUBLIC_SERVER_URL!, summaryField: 'aiSummary' })
// src/app/md/[locale]/[[...slug]]/route.ts — każda strona jako Markdown (noindex + canonical do HTML)
import { createMarkdownRoute } from '@intecion/ipal-kit'
import { contentConfig } from '@/content.config'
export { markdownRoute as GET } from '@/lib/content'
export const dynamic = 'force-dynamic'
export const { GET } = createMarkdownRoute({ getCachedPayload, content: contentConfig, config: i18nConfig,
baseUrl: process.env.NEXT_PUBLIC_SERVER_URL })
// src/app/indexnow-key.txt/route.ts — klucz IndexNow (z Site Integrations albo INDEXNOW_KEY)
import { createIndexNowKeyRoute } from '@intecion/ipal-kit'
export { indexNowKeyRoute as GET } from '@/lib/content'
export const dynamic = 'force-dynamic'
export const GET = createIndexNowKeyRoute({ getCachedPayload })
// src/app/api/mcp/route.ts — publiczny serwer MCP (AI przegląda stronę)
import { createMcpRoute } from '@intecion/ipal-kit'
export { mcpGET as GET, mcpPOST as POST } from '@/lib/content'
export const dynamic = 'force-dynamic'
const mcp = createMcpRoute({ getCachedPayload, config: i18nConfig, content: contentConfig,
baseUrl: process.env.NEXT_PUBLIC_SERVER_URL!, serverName: '<klient>-site', summaryField: 'aiSummary' })
export const POST = mcp.POST
export const GET = mcp.GET
// src/app/api/health/route.ts
import { createHealthRoute } from '@intecion/ipal-kit'
export { healthRoute as GET } from '@/lib/content'
export const dynamic = 'force-dynamic'
export const GET = createHealthRoute({ getCachedPayload })
```
Jeden sitemap: `sitemap.xml/route.ts` **albo** `sitemap.ts` — nigdy oba. Nagłówek
sitemapy = „XML Sitemap”, pod nim „Technology by Intecion.com”; zmiana
@@ -567,6 +538,12 @@ Rób po jednej pozycji, buduj, sprawdzaj. Kolejność wg wagi:
| 25 | **1.9.1** — zgoda: wersja, rejestr, tabela | Cookie Settings → Policy version; `consentLog: true` + `logEndpoint`; `<CookieBanner equalChoice>`; skan + `<CookieTable>`; Postgres: `migrate:create` | consent.md |
| 26 | **1.9.1** — media: `priority`, brak placeholderów, `images` w next.config | `<Media>` przez `mediaImageProps`/`videoProps`, `buildMediaPlaceholderHook`, `buildImagesConfig`, `buildUploadSecurityHeaders` | storage.md |
| 27 | **1.9.1** — staging indeksowany | `IPAL_NOINDEX=1` w env stagingu | seo.md |
| 28 | **1.9.2** — własny `FormRenderer` (kopia silnika na `useForm`) | **bezpieczeństwo:** przekazywał do przeglądarki cały dokument formularza z zakładką Emails (adresy firmy w HTML). Blok → `<RenderForm form action locale texts classNames>`, wygląd do `formClasses.ts`, usuń `FormRenderer.tsx`; nietypowy formularz → `useBuilderForm` | forms.md |
| 29 | **1.9.2** — formularze krokowe / listy wyboru robione w kodzie | panel: bloki **Step**, **Radio**, **Checkbox group**, **Date**; Notifications → next / back / stepOf; Postgres: `migrate:create` | forms.md |
| 30 | **1.9.2** — layout składany ręcznie (ConsentProvider, TurnstileProvider, Analytics, JsonLdGraph, MediaPreconnect) | `<SiteProviders shell={await getSiteShell(locale)} …>` — te same opcje (banner, analytics, jsonLd, logEndpoint) | PROGRAMISTA §2.8 |
| 31 | **1.9.2** — strona catch-all i `not-found.tsx` pisane ręcznie | `createPageRoute(content, {…})` / `createNotFoundPage(content, {…})` z `/rsc`; `revalidate` zostaje literałem | pages.md |
| 32 | **1.9.2** — trasy llms/md/mcp/health/indexnow/manifest z konfiguracją w każdym pliku | re-eksport z `lib/content` (`llmsRoute`, `llmsFullRoute`, `markdownRoute`, `mcpGET`/`mcpPOST`, `healthRoute`, `indexNowKeyRoute`, `manifest`); `summaryField`, `mcp` raz w `createContentHelpers` | PROGRAMISTA §2.7 |
| 33 | **1.9.2** — `src/fields/sectionHeader.ts`, `sectionSettings.ts`, `lib/navigation.ts`, ręczne `resolveLinkHref` w `CMSLink` | `buildSectionHeaderField`, `buildSectionSettingsField` (ten sam kształt danych — bez migracji), `resolveNav`, `resolveLink` z `lib/content` | blocks.md, links.md |
Po aktualizacji pakietu: `pnpm ipal:skills` (nowe wersje skilli), `pnpm payload generate:importmap`, `rm -rf .next`, restart dev, grep nowego symbolu w
`node_modules/@intecion/ipal-kit/dist`.
@@ -619,6 +596,7 @@ grep -c "<symbol>" src/<ścieżka> # >0 — zmiana zapisana
# docs/: zmiana API/zachowania → zaktualizuj plik modułu W TYM SAMYM commicie
pnpm clean && pnpm build
grep -c "<symbol>" dist/<ścieżka> # >0 — build ją złapał (eksport w index.ts!)
# docs/CHANGELOG.md: nowa sekcja ## <wersja> na górze (zostaje min. 20 ostatnich wersji)
git add -A && git commit -m "opis" # PRZED version (dist/ i tak jest ignorowany)
npm version <wersja> # numer podaje człowiek; minor = nowe API, major = łamiące
npm publish
+19 -20
View File
@@ -127,14 +127,13 @@ Sprawdź: lista języków istnieje tylko w `i18n.config.ts` (grep `'pl'` w `src`
```
Zrób zgodnie z AGENT.md §5.3 i §6.2:
1. src/fields/sectionHeader.ts, sectionSettings.ts — kod 1:1 z
node_modules/@intecion/ipal-kit/docs/agent/skills/ipal-block/resources/kod-sekcji.md
(linki: buildLinkField/buildLinksField z @intecion/ipal-kit — nie kopiuj).
1. Wspólne pola sekcji i linki są w pluginie: buildSectionHeaderField, buildSectionSettingsField,
buildLinkField, buildLinksField z @intecion/ipal-kit — nie kopiuj, nie twórz src/fields/.
2. collections/Media.ts: upload (mimeTypes obrazy + PDF + mp4), alt required localized,
normalizeFilenameHook, buildOptimizeUploadHook + buildOptimizeUploadField (storage.md); jeśli R2 — buildR2Storage(['media'], { s3Storage }) z env, s3Storage
wstrzyknięty z @payloadcms/storage-s3 (storage.md).
3. collections/Pages.ts: title localized, buildSlugField, buildNoindexField,
layout typu blocks (na razie jeden blok Content: sectionHeaderField + content richText),
layout typu blocks (na razie jeden blok Content: buildSectionHeaderField + content richText),
trackSlugHistoryHook, buildRevalidateHook (hooks.md).
NIE twórz kolekcji users, settings, navigation ani żadnych innych.
Potem pnpm generate:types i payload generate:importmap.
@@ -167,12 +166,12 @@ Plan najpierw.
```
Zrób zgodnie z PROGRAMISTA.md §2.6–2.8 i AGENT.md §4:
- src/proxy.ts z createProxy, matcher jako literał inline,
- src/lib/content.ts z createContentHelpers (w tym getNotFoundPage, generateStaticParams),
- app/(frontend)/[locale]/layout.tsx: BEZ <head>, MediaPreconnect w body,
ConsentProvider + CookieBanner + CookieButton + Analytics wewnątrz providera,
- [locale]/[[...slug]]/page.tsx: revalidate, generateStaticParams, BEZ searchParams,
resolveRedirect przed notFound, enhanceProps wstrzykuje locale do bloków,
- [locale]/not-found.tsx z getNotFoundPage dla każdego języka + LocaleView, BEZ headers() (pages.md).
- src/lib/content.ts z createContentHelpers (PROGRAMISTA §2.7 — eksportuje też trasy, getSiteShell, resolveNav),
- app/(frontend)/[locale]/layout.tsx: BEZ <head>, <SiteProviders shell={await getSiteShell(locale)} …>
(zgoda, baner equalChoice, Turnstile, Analytics, JSON-LD, preconnect — w dobrej kolejności),
- [locale]/[[...slug]]/page.tsx: createPageRoute(content, { blocks, notFound, permanentRedirect }) +
export const revalidate (literał), BEZ searchParams,
- [locale]/not-found.tsx: createNotFoundPage(content, { blocks }) — BEZ headers() (pages.md).
Plan najpierw.
```
Sprawdź: `/` → `/<domyślny język>`; `pnpm build` pokazuje strony jako `●`;
@@ -184,11 +183,11 @@ Sprawdź: `/` → `/<domyślny język>`; `pnpm build` pokazuje strony jako `●`
```
Zrób wg PROGRAMISTA.md §2.8–2.9 i seo.md:
- app/sitemap.xml/route.ts (sitemapRoute z lib/content), robots.ts, manifest.ts (createManifestHandler), llms.txt/route.ts,
- re-eksporty z lib/content: app/sitemap.xml/route.ts (sitemapRoute), robots.ts (robots), manifest.ts (manifest), llms.txt/route.ts (llmsRoute),
api/health/route.ts — każda trasa czytająca bazę z export const dynamic = 'force-dynamic',
- next.config.ts: htmlLimitedBots, buildSecurityHeaders,
- metadata strony przez generatePageMetadata z lib/content (wspólny cache), favicon przez buildIconsMetadata,
- JSON-LD w root layoucie: Organization + WebSite (seo.md) z danych z panelu,
- JSON-LD: Organization + WebSite daje SiteProviders z Site Settings; firma lokalna → siteJsonLd w createContentHelpers (seo.md),
- src/instrumentation.ts z assertEnv(ipalEnvRules(...)) importowanym z @intecion/ipal-kit/env (env.md).
CSP jeszcze nie — będzie w kroku 14.
Plan najpierw.
@@ -207,7 +206,7 @@ Zrób wg AGENT.md §6.8, kod z node_modules/@intecion/ipal-kit/docs/agent/skills
- globals/Header.ts, Footer.ts (kod z §6.8),
- globals/Company.ts dla rynku <PL/AU/…>: nazwa, adres, <NIP/ABN/…>, telefon, email —
wszystko localized tam, gdzie tekst,
- lib/navigation.ts (resolveNav), components/layout/Header.tsx, Footer.tsx, MobileNav.tsx,
- menu przez resolveNav z lib/content (plugin, NIE lib/navigation.ts), components/layout/Header.tsx, Footer.tsx, MobileNav.tsx,
- linki prawne w stopce z ról System Pages, NIE ręcznie,
- hook afterChange na globalach z revalidatePath('/', 'layout').
Podepnij w [locale]/layout.tsx. Etykiety a11y z panelu.
@@ -234,8 +233,8 @@ Skrót: `/ipal-block <Nazwa> — <pola z 9a>, <opis wyglądu / zrzut>`.
```
Zbuduj blok <nazwa> wg AGENT.md §6 (warstwa 3):
- src/blocks/<Nazwa>/config.ts: sectionHeaderField, buildLinksField, media, items,
sectionSettingsField — tylko pola z listy z kroku 9a, nazwy z §6.5,
- src/blocks/<Nazwa>/config.ts: buildSectionHeaderField, buildLinksField, media, items,
buildSectionSettingsField — tylko pola z listy z kroku 9a, nazwy z §6.5,
- Component.tsx: Section + SectionHeader + Media + CMSLink, max ~80 linii JSX,
powtarzalne elementy w <Nazwa>Card.tsx, interakcja w osobnym pliku 'use client' (§6.9),
- dodaj do Pages.layout i do blocks/registry.ts,
@@ -253,11 +252,11 @@ Skrót: `/ipal-form <formularz, odbiorca zgłoszeń>`.
```
Zrób wg forms.md, turnstile.md, email.md:
- blok formularza korzystający z form-buildera pluginu (pola i teksty z panelu),
- logika przez useForm/useContactForm z @intecion/ipal-kit/client — bez ręcznego useState,
- blok formularza: <RenderForm> z @intecion/ipal-kit/rsc + formClasses.ts (skill ipal-form) — pola, kroki,
listy wyboru i teksty z panelu, żadnego własnego renderera,
- checkbox consent (zgoda RODO) z linkiem do polityki przez getSystemPagePath,
- TurnstileProvider w layoucie (siteKey z getSiteIntegrations) — bez przekazywania siteKey do bloku,
- honeypot, zdarzenie form_submit (formAnalyticsOnSuccess).
- Turnstile z SiteProviders w layoucie — bez przekazywania siteKey do bloku,
- honeypot i zdarzenie GTM z panelu robi RenderForm sam (forms.md).
Plan najpierw.
```
Sprawdź: panel → Site Integrations → Send test; wysłanie formularza bez zgody → odrzucone.
@@ -268,7 +267,7 @@ Sprawdź: panel → Site Integrations → Send test; wysłanie formularza bez zg
```
Zweryfikuj i dokończ wg consent.md i analytics.md:
- Analytics wewnątrz ConsentProvider, ID tylko z Site Integrations,
- Analytics przez SiteProviders (wewnątrz zgody), ID tylko z Site Integrations,
- czy włączyć defer (Core Web Vitals) — <tak/nie>,
- Meta Pixel: <w panelu | w GTM> (nigdy oba),
- link do polityki w banerze: automatyczny (bez parametru privacyPolicy w kodzie).
+64 -4
View File
@@ -23,8 +23,8 @@ consent RODO, powiadomienia).
| własna walidacja/wysyłka | `submitForm` (Turnstile+consent+mail) |
| klient nie zmieni formularza | klient edytuje pola w panelu |
**Jak poprawnie:** redaktor tworzy formularz w kolekcji Forms → front pobiera
jego definicję → renderuje pola dynamicznie → wysyła przez `submitForm`. Pola,
**Jak poprawnie:** redaktor tworzy formularz w kolekcji Forms → blok renderuje go
przez `<RenderForm>` → wysyłka przez `sendForm` (`createSubmitAction` → `submitForm`). Pola,
etykiety, komunikaty, odbiorca — wszystko z panelu.
Jeśli formularz wymaga pola, którego builder nie ma — dodaj je przez konfigurację
@@ -42,7 +42,8 @@ Jeśli formularz wymaga pola, którego builder nie ma — dodaj je przez konfigu
ipalKit({
forms: {
redirectRelationships: ['pages'], // formularz może przekierować na Page
// fields: { text: true, textarea: true, email: true, ... }, // domyślnie włączone sensowne
// fields: { date: false, payment: true, … }, // domyślnie: text, textarea, email, number, date,
// // select, radio, checkbox, checkboxGroup, message, step
},
})
```
@@ -53,6 +54,61 @@ Dodaje kolekcje **Forms** (edytor buduje formularze) i **Form Submissions**
`forms: { adminGroup: 'Content' }`; domyślna Payloada: `adminGroup: false`. Maile po zgłoszeniu wysyła form-builder według zakładki **Emails**
formularza — przez adapter z `email:` w configu (sekcja „Maile” niżej).
## Front — RenderForm (zalecane, jedna linia)
Cały front formularza z panelu jest w pluginie. Projekt ma blok i klasy:
```tsx
// src/blocks/FormBlock/Component.tsx
import { RenderForm } from '@intecion/ipal-kit/rsc'
<RenderForm form={form} action={sendForm} locale={locale} texts={formTexts} classNames={formClasses} />
```
- `form` — relacja z bloku (depth ≥ 1; ID albo null → nic się nie renderuje),
- `action` — `sendForm` z `createSubmitAction` (niżej), `texts` — `getFormTexts(locale)` z `lib/content`
(Notifications → Form messages),
- `classNames` — **jedyne** miejsce wyglądu (`src/components/forms/formClasses.ts`, szablon w ipal-form);
plugin nie ma żadnych stylów. Klucze: `form, progress, step, stepTitle, stepDescription, fields,
field, fieldHalf, fieldFull, label, input, textarea, select, checkbox, checkboxLabel, choices,
legend, choice, choiceInput, choiceLabel, message, error, formError, turnstile, actions, back,
next, submit, success, required`. Do CSS są też `data-ipal="form"`, `data-type`, `data-width`, `data-step`.
- opcje: `requiredMark` (np. `" *"`), `converters` / `richTextClassName` (wygląd rich text),
`linkOptions` (`await getLinkOptions(locale)` — redirect na stronę z panelu), `turnstileTheme`.
`RenderForm` (serwer) renderuje bloki **message** i potwierdzenie przez `RenderRichText`, wiąże
akcję z formularzem i językiem, rozwiązuje redirect i podaje przeglądarce **tylko publiczną część
formularza** — Local API czyta z `overrideAccess`, więc dokument ma zakładkę Emails (adresy firmy);
ręczne `<FormRenderer form={form}>` wysyłało je w HTML. Pod spodem `BuilderForm` (klient).
### Typy pól w panelu
text, email, textarea, number, **date**, select, **radio**, checkbox, **Checkbox group**,
message, **Step** (+ country/state jako tekst). Wyłączenie typu: `forms.fields: { date: false }`.
| Typ | Wartość | Serwer sprawdza |
|---|---|---|
| radio, select | jedna wartość | tylko wartości z panelu |
| Checkbox group | `string[]` (zapis: „www, seo”) | tylko wartości z panelu, bez duplikatów, `minSelected`/`maxSelected` |
| date | `YYYY-MM-DD` | prawdziwa data |
| Step | — (podział) | nie jest polem |
### Formularz krokowy
Blok **Step** (tytuł, opis, per język) zaczyna nowy ekran; pola nad pierwszym Step to ekran 1.
`BuilderForm`: „Krok 1 z 3” (`stepOf`), Dalej waliduje tylko bieżący krok, Wstecz zachowuje
wartości, fokus przechodzi na nowy krok, Turnstile na ostatnim kroku, błąd pola z serwera wraca
na krok z tym polem. Teksty przycisków: Notifications → Form messages → `next`, `back`, `stepOf`.
### Formularz nietypowy — bez kopiowania silnika
1. `renderField` (BuilderForm w pliku `'use client'`) — podmienia wybrane pola:
`renderField={({ field, defaultRender }) => field.name === 'budget' ? <Cards …/> : undefined}`.
2. `useBuilderForm({ form, action, texts })` — cała logika, markup Twój: `steps`, `step`,
`stepIndex`, `total`, `isFirst/isLast`, `next()`, `back()`, `goTo(i)`, `submit`, `values`,
`errors`, `errorMessage`, `isSubmitting`, `isSuccess`, `resultMessage`, `getFieldProps`,
`getInputProps`, `getTextareaProps`, `getSelectProps`, `getOptionProps`, `fieldId`, `errorId`,
`TurnstileWidget`. Przykład: `ipal-form/resources/CustomForm.example.tsx`.
3. Czysta logika (też na serwerze / w testach): `splitSteps`, `initialBuilderValues`,
`validateBuilderFields`, `stepOfField`, `inputFields`, `autoCompleteFor` (podpowiedź autouzupełniania z typu i nazwy pola).
`useOptionalTurnstile()` — jak `useTurnstile`, ale bez providera zwraca `enabled: false` zamiast rzucać.
## Front — submitForm (server)
Wołasz w Server Action. Kształt pasuje 1:1 do `useForm` / `useContactForm`
@@ -283,7 +339,11 @@ To obsługuje WSZYSTKIE kody (w tym `consent`, `rate_limited`, `validation` z
`{field}`) tekstami z panelu. Ręczny switch (wyżej) zostaw tylko, jeśli nie
używasz modułu notifications. Szczegóły: [notifications.md](./notifications.md).
## Logika klienta — useForm / useContactForm (bez markupu)
## Logika klienta — useForm / useContactForm (niższy poziom)
Dla formularzy z panelu używaj `RenderForm` / `useBuilderForm` (wyżej) — mają kroki, listy
wyboru i walidację z definicji pola. `useForm` to silnik pod spodem: dla formularza **spoza
buildera** (np. wyszukiwarka z filtrami), nie dla formularzy kontaktowych.
`submitForm` to serwer. Po stronie klienta powtarzała się ta sama hydraulika w
każdym projekcie: `useState` na pola, regex e-maila, token Turnstile, submit,
+4
View File
@@ -307,6 +307,10 @@ fallback na root `/{code}`.
> i przekaż do AlternateLinksUpdater. To eliminuje własny AlternateLinksContext
> (~150 linii) kopiowany w projektach.
Własny przełącznik (inny markup niż `LanguageSwitcher`): `useAlternateLinks()` (`/client`) zwraca
`{ [locale]: url }` bieżącej strony; `useSetAlternateLinks()` to setter, którego używa
`AlternateLinksUpdater` (zwykle niepotrzebny w projekcie).
## Next matcher — MUSI być literałem inline
Next.js analizuje `config.matcher` STATYCZNIE (AST) — musi być literałem tablicy
+48 -4
View File
@@ -69,11 +69,53 @@ Linki wewnętrzne wymagają **zpopulowanej** strony (`depth ≥ 2` w bloku).
`homeSlug` — slug strony głównej (string albo mapa per język, np. z
`SiteSettings.homepage`), żeby zwinąć ją do `/{locale}`.
## Render w projekcie
## Link gotowy do renderu — `resolveLink`
Komponent `CMSLink` jest w projekcie (wygląd przycisków to sprawa projektu) —
gotowy kod: [kod-sekcji.md](./agent/skills/ipal-block/resources/kod-sekcji.md). Menu: `resolveNav` w
`lib/navigation.ts` ([kod-nawigacji.md](./agent/skills/ipal-nav/resources/kod-nawigacji.md)) korzysta z tego samego `resolveLinkHref`.
```ts
// w komponencie serwerowym, z lib/content (locale → homeSlug i i18n same):
const l = await resolveLink(link, locale)
// bez lib/content: resolveLink(link, { locale, config: i18nConfig, homeSlug })
// → { href, label, internal, newTab, targetProps, appearance } | null
```
- `internal` → `next/link`, inaczej `<a>` (URL, plik, mailto, tel),
- `targetProps` → `{ target: '_blank', rel: 'noopener noreferrer' }` przy nowej karcie (plik zawsze),
- `appearance` → klucz wariantu w `Button.tsx` projektu,
- `null` → link prowadzi donikąd w tym języku (brak strony, pliku, niebezpieczny URL) — nic nie renderuj.
`CMSLink` zostaje w projekcie (element i klasy to wygląd), ale nie liczy niczego sam:
```tsx
// src/components/ui/CMSLink.tsx
import Link from 'next/link'
import type { ReactNode } from 'react'
import type { CmsLink } from '@/payload-types'
import { resolveLink } from '@/lib/content'
import { buttonClass } from './Button'
export async function CMSLink({ link, locale, className, children }: { link: CmsLink | null | undefined; locale: string; className?: string; children?: ReactNode }) {
const l = await resolveLink(link, locale)
const content = children ?? l?.label
if (!l || !content) return null
const cls = [l.appearance ? buttonClass(l.appearance as never) : '', className].filter(Boolean).join(' ') || undefined
return l.internal
? <Link href={l.href} className={cls} {...l.targetProps}>{content}</Link>
: <a href={l.href} className={cls} {...l.targetProps}>{content}</a>
}
```
## Menu — `resolveNav`
```ts
const items = await resolveNav(header.navItems, locale) // z lib/content
// resolveNav(items, { locale, config: i18nConfig, homeSlug, linkField: 'link', childrenField: 'subItems' })
// → NavItem[]: { href, label, internal, newTab, targetProps, appearance?, children: NavItem[] }
```
Dowolna głębokość, kształt pozycji konfigurowalny (`linkField`, `childrenField`), pozycje z martwym
linkiem albo bez etykiety pominięte (zamiast `href="#"`). Wynik to zwykłe dane — idzie wprost do
klienckiego `MobileNav`. Markup menu (Header, Footer, MobileNav) zostaje w projekcie:
[kod-nawigacji.md](./agent/skills/ipal-nav/resources/kod-nawigacji.md).
`homeSlugFrom(settings)` — slug strony głównej z `SiteSettings.homepage` (lib/content: `getHomeSlug(locale)`,
a komplet opcji linków: `getLinkOptions(locale)` — też dla `RenderForm linkOptions`).
## Migracja z `src/fields/link.ts`
@@ -85,3 +127,5 @@ bazy nie jest potrzebna**:
2. `resolveLinkHref(link, locale, homeSlug)` z `@/lib/links` →
`resolveLinkHref(link, { locale, config: i18nConfig, homeSlug })` z pluginu,
3. usuń `src/fields/link.ts` i `src/lib/links.ts`, `pnpm generate:types`.
4. `lib/navigation.ts` z własnym `resolveNav` → `resolveNav` z `lib/content` (te same dane +
`internal`, `targetProps`; `subItems` nazywa się teraz `children`).
+3
View File
@@ -35,6 +35,9 @@ odfiltrowane — ta sama zasada co sitemap/llms).
```ts
// app/api/mcp/route.ts
// Zwykle jedna linia (konfiguracja w createContentHelpers({ mcp: { serverName }, summaryField })):
// export { mcpGET as GET, mcpPOST as POST } from '@/lib/content'
// Niżej pełny wariant — gdy trasa potrzebuje opcji spoza lib/content.
import { createMcpRoute } from '@intecion/ipal-kit'
import { getCachedPayload } from '@/lib/content'
import { i18nConfig } from '@/i18n.config'
+4 -2
View File
@@ -16,7 +16,9 @@ Dzięki temu żaden komunikat nie jest zaszyty w kodzie — wszystko przez panel
Brak opcji — global **Notifications** jest zawsze budowany. Edytor zarządza
tekstami w panelu (karta Notifications), grupowane per kontekst. Grupa `form`:
`success`, `error`, `rateLimited`, `turnstile`, `validation`, `consent`,
`notFound`. Każde pole puste → fallback (NOTIFICATION_FALLBACK).
`notFound` oraz przyciski formularzy krokowych: `next` („Dalej”), `back` („Wstecz”),
`stepOf` („Krok {current} z {total}”). Każde pole puste → fallback (NOTIFICATION_FALLBACK, EN).
Dla formularzy: `getFormTexts(locale)` z `lib/content` = grupa `form` w danym języku.
## Helper — getNotificationTexts
@@ -25,7 +27,7 @@ Pobiera teksty z globala per język, fallback per pole. Analog `getConsentTexts`
```ts
import { getNotificationTexts } from '@intecion/ipal-kit'
const notifications = await getNotificationTexts({ payload, locale })
const notifications = await getNotificationTexts({ payload, locale }) // w lib/content: getFormTexts(locale) = .form
// notifications.form.error, notifications.form.success, ...
```
+20 -1
View File
@@ -62,7 +62,26 @@ Site Settings → System Pages → **404 (Not Found)**. Edytor wybiera:
- stronę główną (część klientów tak woli), **albo**
- nic → projekt pokazuje wbudowany fallback z `not-found.tsx`.
Projekt — `app/(frontend)/[locale]/not-found.tsx` (pełny plik):
Projekt — `app/(frontend)/[locale]/not-found.tsx`, jedna linia (od 1.9.2):
```tsx
import { createNotFoundPage } from '@intecion/ipal-kit/rsc'
import * as content from '@/lib/content'
import { blockRegistry } from '@/blocks/registry'
export default createNotFoundPage(content, {
blocks: blockRegistry,
fallback: <h1>404</h1>, // gdy w panelu nie wybrano strony 404 (albo per język: (locale) => …)
// blockProps: async ({ locale }) => ({ formTexts: await content.getFormTexts(locale), sendForm }),
})
```
Robi dokładnie to, co pełny plik poniżej (widok dla każdego języka + `LocaleView`, bez `headers()`).
Strona catch-all z tymi samymi helperami: `createPageRoute(content, { blocks, notFound, permanentRedirect,
blockProps, render, jsonLd })` — PROGRAMISTA §2.8. `render` daje własny widok dla archiwum lub wpisu
(`route.type`: `page | home | archive | entry`), reszta zostaje domyślna.
Ręcznie (pełny plik — gdy potrzebujesz czegoś, czego `createNotFoundPage` nie ma):
```tsx
import React from 'react'
+8 -3
View File
@@ -415,7 +415,7 @@ klienta w fallbacku. Fallback z nazwą/kolorem klienta to ukryty hardkod.
> **Zalecane (aktualne): `createManifestHandler`** — to samo bez ręcznego kodu,
> z try/catch na brak bazy w buildzie:
> ```ts
> // app/manifest.ts
> // app/manifest.ts — zwykle: export { manifest as default } from '@/lib/content'
> import { createManifestHandler } from '@intecion/ipal-kit'
> import { getCachedPayload } from '@/lib/content'
> import { i18nConfig } from '@/i18n.config'
@@ -1004,6 +1004,7 @@ fields: [ /* … */ buildSummaryField() ]
Potem wskaż je jako źródło opisu dla AI (preferowane nad meta.description):
```ts
createContentHelpers({ …, summaryField: 'aiSummary' }) // llmsRoute, llmsFullRoute, mcpGET/POST — raz
buildLlmsTxt({ …, summaryField: 'aiSummary' })
createLlmsTxtRoute({ …, summaryField: 'aiSummary' })
createSearchRoute({ …, summaryField: 'aiSummary' })
@@ -1021,7 +1022,7 @@ llmstxt.org) — agent dostaje całą stronę jednym żądaniem. Dołóż drugi
`full: true`:
```ts
// app/llms-full.txt/route.ts
// app/llms-full.txt/route.ts — zwykle: export { llmsFullRoute as GET } from '@/lib/content'
import { createLlmsTxtRoute } from '@intecion/ipal-kit'
import { getCachedPayload } from '@/lib/content'
import { i18nConfig } from '@/i18n.config'
@@ -1171,7 +1172,8 @@ Dopełnia Markdown/llms: asystent łatwiej wyciąga kluczową treść strony.
## 1.9.1 — dane strukturalne strony, IndexNow, sameAs, godziny otwarcia
- **`getPageJsonLd(locale, slug, { faq, pageType, entryType, breadcrumbs })`** z `createContentHelpers`:
- **`getPageJsonLd(locale, slug, { faq, pageType, entryType, breadcrumbs })`** z `createContentHelpers`
(węzeł strony składa `buildWebPageJsonLd` — dostępny też osobno dla własnych tras):
WebPage / CollectionPage / BlogPosting (język, `dateModified`, obraz), BreadcrumbList z prawdziwej
trasy (tytuły stron z panelu), FAQPage, gdy projekt zmapuje swój blok FAQ. W `[[...slug]]/page.tsx`:
`<JsonLdGraph schemas={await getPageJsonLd(locale, slug)} />`.
@@ -1191,6 +1193,9 @@ Dopełnia Markdown/llms: asystent łatwiej wyciąga kluczową treść strony.
co. (ChatGPT Search, Copilot korzystają z indeksu Binga). Tylko produkcja z publicznym https.
Klucz: Site Integrations → IndexNow (generuje się przy zapisie) albo `INDEXNOW_KEY`. Google nie
obsługuje IndexNow — dla niego sitemap.
Trasa klucza z `lib/content`: `export { indexNowKeyRoute as GET } from '@/lib/content'`.
Ręcznie (np. import treści skryptem): `submitToIndexNow({ payload, urls })` (klucz: `getIndexNowKey(payload)`)
— nigdy nie rzuca, tylko loguje.
- **llms.txt / llms-full.txt** obejmują wpisy kolekcji treści (`content`) i wszystkie języki; MCP
`list_pages` też. Wspólne źródło: `collectSiteIndex`.
+3
View File
@@ -116,6 +116,9 @@ przekazywania siteKey do każdego formularza.
### 1. Provider w layoutcie (raz, siteKey z serwera)
Z `SiteProviders` (PROGRAMISTA §2.8) provider jest już wpięty — klucz z `getSiteShell(locale).turnstileSiteKey`,
widget renderuje `RenderForm` na ostatnim kroku formularza. Ręcznie:
```tsx
// app/(frontend)/[locale]/layout.tsx (server)
import { getTurnstileConfig } from '@intecion/ipal-kit'
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@intecion/ipal-kit",
"version": "1.9.1",
"version": "1.9.2",
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
"license": "MIT",
"repository": {
+14 -1
View File
@@ -24,9 +24,22 @@ export {
useConsentContext,
} from '../modules/consent/client.js'
export type { CookieBannerClassNames } from '../modules/consent/client.js'
export { BuilderForm } from '../modules/forms/BuilderForm.js'
export type { BuilderFieldRenderArgs, BuilderFormClassNames, BuilderFormProps } from '../modules/forms/BuilderForm.js'
export { autoCompleteFor, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields } from '../modules/forms/builderLogic.js'
export type {
BuilderField,
BuilderFormAction,
BuilderFormDoc,
BuilderFormTexts,
BuilderOption,
BuilderStep,
} from '../modules/forms/builderTypes.js'
export { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js'
export type { FormAnalyticsConfig } from '../modules/forms/formAnalytics.js'
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js'
export { useBuilderForm } from '../modules/forms/useBuilderForm.js'
export type { BuilderFormApi, UseBuilderFormOptions } from '../modules/forms/useBuilderForm.js'
export { useContactForm } from '../modules/forms/useContactForm.js'
export type { ContactFormErrors, ContactFormValues, SubmitAction } from '../modules/forms/useContactForm.js'
export { useForm } from '../modules/forms/useForm.js'
@@ -64,5 +77,5 @@ export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStat
export { LocaleView } from '../modules/pages/LocaleView.js'
export { YouTubeEmbed } from '../modules/storage/YouTubeEmbed.js'
export { Turnstile } from '../modules/turnstile/client.js'
export { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js'
export { TurnstileProvider, useOptionalTurnstile, useTurnstile } from '../modules/turnstile/client.js'
export type { TurnstileProps } from '../modules/turnstile/client.js'
+8
View File
@@ -14,6 +14,14 @@ export type {
} from '../modules/blocks/index.js'
export { CookieTable } from '../modules/consent/CookieTable.js'
export type { CookieTableLabels } from '../modules/consent/CookieTable.js'
export { RenderForm } from '../modules/forms/RenderForm.js'
export type { RenderFormProps, SendFormAction } from '../modules/forms/RenderForm.js'
// Layout wiring + catch-all page + 404 from lib/content helpers (optional — the
// pieces stay available for a project that composes them itself).
export { createNotFoundPage, createPageRoute } from '../modules/frontend/pageRoute.js'
export type { NotFoundPageOptions, PageRouteOptions } from '../modules/frontend/pageRoute.js'
export { SiteProviders } from '../modules/frontend/SiteProviders.js'
export type { SiteProvidersProps } from '../modules/frontend/SiteProviders.js'
export { RenderRichText } from '../modules/richtext/index.js'
export type { RenderRichTextProps } from '../modules/richtext/index.js'
export { JsonLdGraph } from '../modules/seo/index.js'
+23
View File
@@ -69,6 +69,29 @@ export const notificationsFields: Field[] = [
admin: { placeholder: 'This form is no longer available.' },
localized: true,
},
{
type: 'row',
fields: [
{
name: 'next',
type: 'text',
admin: { description: 'Step-by-step forms: button to the next step.', placeholder: 'Next', width: '33%' },
localized: true,
},
{
name: 'back',
type: 'text',
admin: { description: 'Step-by-step forms: button to the previous step.', placeholder: 'Back', width: '33%' },
localized: true,
},
{
name: 'stepOf',
type: 'text',
admin: { description: 'Progress — {current} and {total} are replaced.', placeholder: 'Step {current} of {total}', width: '34%' },
localized: true,
},
],
},
],
label: 'Form messages',
},
+11 -2
View File
@@ -19,6 +19,9 @@ export { rowLabel } from './modules/admin-ui/index.js'
export type { RowLabelProps } from './modules/admin-ui/index.js'
export type { AnalyticsConfig } from './modules/analytics/index.js'
export { getAnalyticsConfig } from './modules/analytics/index.js'
// Shared section fields (header: eyebrow/heading/intro, settings: anchor/background).
export { buildSectionHeaderField, buildSectionSettingsField } from './modules/blocks/sectionFields.js'
export type { SectionHeaderFieldOptions, SectionSettingsFieldOptions } from './modules/blocks/sectionFields.js'
export {
ACCEPT_ALL_CONSENT,
buildConsentLogCollection,
@@ -74,6 +77,9 @@ export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js'
// Boot-time environment validation (fail fast on misconfigured deploys).
export { assertEnv, ipalEnvRules } from './modules/env/index.js'
export type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from './modules/env/index.js'
export { checkboxGroupBlock, stepBlock } from './modules/forms/builderBlocks.js'
export { initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields } from './modules/forms/builderLogic.js'
export type { BuilderField, BuilderFormDoc, BuilderFormTexts, BuilderStep } from './modules/forms/builderTypes.js'
// Panel-managed form analytics (config-time field builder).
export { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js'
export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
@@ -99,7 +105,7 @@ export {
required,
} from './modules/forms/validators.js'
export type { Rule } from './modules/forms/validators.js'
export type { PageJsonLdOptions } from './modules/frontend/createContentHelpers.js'
export type { ContentHelpers, PageJsonLdOptions, SiteShell } from './modules/frontend/createContentHelpers.js'
export { createContentHelpers } from './modules/frontend/index.js'
// Healthcheck route (Coolify/Docker liveness with a real DB round-trip).
export { createHealthRoute } from './modules/health/index.js'
@@ -126,13 +132,16 @@ export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js'
export { resolveLocalized } from './modules/i18n/index.js'
export { buildIntegrationStatusBanner, buildIntegrationStatusField, recordIntegrationStatus } from './modules/integrations/index.js'
export type { IntegrationState, IntegrationStatus } from './modules/integrations/index.js'
export { buildLinkField, buildLinksField, resolveLinkHref, safeHref } from './modules/links/index.js'
export { buildLinkField, buildLinksField, homeSlugFrom, resolveLink, resolveLinkHref, resolveNav, safeHref } from './modules/links/index.js'
export type {
BuildLinkFieldOptions,
BuildLinksFieldOptions,
LinkAppearance,
LinkValue,
NavItem,
ResolvedLink,
ResolveLinkHrefOptions,
ResolveNavOptions,
} from './modules/links/index.js'
// Read-only MCP server (Claude/agents connect to the site and query it).
export { createMcpRoute } from './modules/mcp/index.js'
+2
View File
@@ -1,3 +1,5 @@
export { RenderBlocks } from './RenderBlocks.js'
export type { RenderBlocksProps } from './RenderBlocks.js'
export { buildSectionHeaderField, buildSectionSettingsField } from './sectionFields.js'
export type { SectionHeaderFieldOptions, SectionSettingsFieldOptions } from './sectionFields.js'
export type { BlockComponentMap, BlockData, EnhanceProps } from './types.js'
+82
View File
@@ -0,0 +1,82 @@
import type { Field, GroupField } from 'payload'
/**
* The two field groups every section block shares — same panel, same data
* shape in every project, so the shared <Section>/<SectionHeader> components
* work on every block. Everything is overridable: names, options, extra fields.
*
* fields: [buildSectionHeaderField(), …the block's own fields…, buildSectionSettingsField()]
* fields: [buildSectionSettingsField({ backgrounds: [{ label: 'Brand', value: 'brand' }] })]
*/
export type SectionHeaderFieldOptions = {
/** Extra fields inside the group (e.g. a heading level select). */
fields?: Field[]
/** Generated TS type name. Default 'SectionHeaderData'. */
interfaceName?: string
/** Default 'header'. */
name?: string
}
/** eyebrow + heading + intro, localized — rendered by the project's <SectionHeader>. */
export function buildSectionHeaderField({ name = 'header', fields = [], interfaceName = 'SectionHeaderData' }: SectionHeaderFieldOptions = {}): GroupField {
return {
name,
type: 'group',
fields: [
{ name: 'eyebrow', type: 'text', admin: { description: 'Small line above the heading. Optional.' }, localized: true },
{ name: 'heading', type: 'text', localized: true },
{ name: 'intro', type: 'textarea', admin: { rows: 3 }, localized: true },
...fields,
],
interfaceName,
}
}
export type SectionSettingsFieldOptions = {
/** Section #id for anchor links and a section nav. Default true. */
anchor?: boolean
/**
* Background choices — values map to the project's own classes in <Section>.
* Default Default / Muted / Inverted (dark). `false` → no background select.
*/
backgrounds?: { label: string; value: string }[] | false
/** Extra settings (e.g. spacing, width). */
fields?: Field[]
/** Generated TS type name. Default 'SectionSettings'. */
interfaceName?: string
/** Default 'settings'. */
name?: string
}
const DEFAULT_BACKGROUNDS = [
{ label: 'Default', value: 'default' },
{ label: 'Muted', value: 'muted' },
{ label: 'Inverted (dark)', value: 'inverted' },
]
/** Sidebar group: anchor + background (+ your own) — instead of bgColor / sectionId per block. */
export function buildSectionSettingsField({
name = 'settings',
anchor = true,
backgrounds = DEFAULT_BACKGROUNDS,
fields = [],
interfaceName = 'SectionSettings',
}: SectionSettingsFieldOptions = {}): GroupField {
return {
name,
type: 'group',
admin: { position: 'sidebar' },
fields: [
...(anchor
? [{ name: 'anchor', type: 'text', admin: { description: 'Section id for #links and section nav, e.g. "pricing".' } } as Field]
: []),
...(backgrounds && backgrounds.length
? [{ name: 'background', type: 'select', defaultValue: backgrounds[0].value, options: backgrounds } as Field]
: []),
...fields,
],
interfaceName,
label: 'Section settings',
}
}
+219
View File
@@ -0,0 +1,219 @@
'use client'
import type { ReactNode } from 'react'
import { useEffect, useRef } from 'react'
import type { BuilderField } from './builderTypes.js'
import type { BuilderFormApi, UseBuilderFormOptions } from './useBuilderForm.js'
import { honeypotInputProps } from './honeypot.js'
import { useBuilderForm } from './useBuilderForm.js'
/**
* Class names for every element — the plugin ships none. Set them once in the
* project (e.g. src/components/forms/formClasses.ts) and every panel form looks
* the same. Plain strings, so a server component can pass them.
*/
export type BuilderFormClassNames = Partial<
Record<
| 'actions' | 'back' | 'checkbox' | 'checkboxLabel' | 'choice' | 'choiceInput' | 'choiceLabel' | 'choices'
| 'error' | 'field' | 'fieldFull' | 'fieldHalf' | 'fields' | 'form' | 'formError' | 'input' | 'label'
| 'legend' | 'message' | 'next' | 'progress' | 'required' | 'select' | 'step' | 'stepDescription'
| 'stepTitle' | 'submit' | 'success' | 'textarea' | 'turnstile',
string
>
>
export type BuilderFieldRenderArgs = {
/** The default markup for this field — return it to keep it, or wrap it. */
defaultRender: () => ReactNode
field: BuilderField
form: BuilderFormApi
/** Position in the panel's field list (key of `messages`). */
index: number
}
export type BuilderFormProps = {
classNames?: BuilderFormClassNames
/** Shown after success instead of the form (the form's confirmation message, rendered by RenderForm). */
confirmation?: ReactNode
/** Rendered `message` blocks, keyed by their index in form.fields (RenderForm fills it). */
messages?: Record<number, ReactNode>
/**
* Client-side only (use BuilderForm from a 'use client' file): replace the
* markup of chosen fields — a project's own field type, option cards, a
* slider. Return undefined to keep the default.
*/
renderField?: (args: BuilderFieldRenderArgs) => ReactNode | undefined
/** Appended to required labels, e.g. "*". Default: nothing. */
requiredMark?: ReactNode
turnstileTheme?: 'auto' | 'dark' | 'light'
} & UseBuilderFormOptions
const cx = (...c: (false | null | string | undefined)[]) => c.filter(Boolean).join(' ') || undefined
/**
* Renders ANY panel form — single screen or step-by-step, text, e-mail, number,
* date, select, radio, checkbox, checkbox group, message blocks — with plain,
* accessible HTML and no styles. Look: `classNames` (+ `data-*` hooks:
* data-ipal="form", data-type, data-width, data-step). Different markup:
* `renderField`, or your own component on useBuilderForm.
*
* In a block, use RenderForm (/rsc) — it renders the rich text, binds the
* action and passes only the public part of the form to the browser.
*/
export function BuilderForm({
classNames: cn = {},
confirmation,
messages = {},
renderField,
requiredMark,
turnstileTheme,
...options
}: BuilderFormProps) {
const f = useBuilderForm(options)
const stepRef = useRef<HTMLDivElement>(null)
const firstRender = useRef(true)
// Moving between steps: focus the new step, so keyboard and screen-reader users land on it.
useEffect(() => {
if (firstRender.current) {
firstRender.current = false
return
}
const el = stepRef.current
const target = el?.querySelector<HTMLElement>('[aria-invalid="true"], input, select, textarea') ?? el
target?.focus()
}, [f.stepIndex])
if (f.isSuccess && options.form.confirmationType !== 'redirect') {
return (
<div className={cn.success} data-ipal="form-success" role="status">
{confirmation ?? f.resultMessage ?? options.texts.success}
</div>
)
}
const label = (field: BuilderField) => (
<>
{field.label}
{field.required && requiredMark ? <span aria-hidden className={cn.required}>{requiredMark}</span> : null}
</>
)
const errorOf = (field: BuilderField) => {
const error = field.name ? f.errors[field.name] : undefined
return error ? <p className={cn.error} id={f.errorId(field)}>{error}</p> : null
}
const defaultField = (field: BuilderField, index: number): ReactNode => {
if (field.blockType === 'message') {return <div className={cn.message}>{messages[index]}</div>}
switch (field.blockType) {
case 'checkbox': {
const props = f.getInputProps(field)
return (
<>
<label className={cn.checkboxLabel} htmlFor={props.id}>
<input {...props} className={cn.checkbox} />
<span>{label(field)}</span>
</label>
{errorOf(field)}
</>
)
}
case 'checkboxGroup':
case 'radio':
return (
<fieldset
aria-describedby={f.getFieldProps(field)['aria-describedby']}
aria-invalid={f.getFieldProps(field)['aria-invalid']}
className={cn.choices}
id={f.fieldId(field)}
>
<legend className={cn.legend}>{label(field)}</legend>
{(field.options ?? []).map((option, i) => {
const o = f.getOptionProps(field, option, i)
return (
<label className={cn.choice} htmlFor={o.id} key={option.value}>
<input {...o} className={cn.choiceInput} />
<span className={cn.choiceLabel}>{option.label ?? option.value}</span>
</label>
)
})}
{errorOf(field)}
</fieldset>
)
case 'select': {
const props = f.getSelectProps(field)
return (
<>
<label className={cn.label} htmlFor={props.id}>{label(field)}</label>
<select {...props} className={cn.select}>
<option value="">{field.placeholder ?? ''}</option>
{(field.options ?? []).map((o) => <option key={o.value} value={o.value}>{o.label ?? o.value}</option>)}
</select>
{errorOf(field)}
</>
)
}
case 'textarea': {
const props = f.getTextareaProps(field)
return (
<>
<label className={cn.label} htmlFor={props.id}>{label(field)}</label>
<textarea {...props} className={cn.textarea} rows={5} />
{errorOf(field)}
</>
)
}
default: {
const props = f.getInputProps(field)
return (
<>
<label className={cn.label} htmlFor={props.id}>{label(field)}</label>
<input {...props} className={cn.input} />
{errorOf(field)}
</>
)
}
}
}
const { step } = f
const progress = options.texts.stepOf?.replace('{current}', String(f.stepIndex + 1)).replace('{total}', String(f.total))
return (
<form className={cn.form} data-ipal="form" data-step={f.stepIndex + 1} noValidate onSubmit={f.submit}>
<input {...honeypotInputProps()} />
{f.total > 1 && progress ? <p aria-live="polite" className={cn.progress}>{progress}</p> : null}
<div className={cn.step} data-ipal="form-step" ref={stepRef} tabIndex={-1}>
{step.title ? <p className={cn.stepTitle}>{step.title}</p> : null}
{step.description ? <p className={cn.stepDescription}>{step.description}</p> : null}
<div className={cn.fields}>
{step.fields.map(({ field, index }) => {
const half = typeof field.width === 'number' && field.width <= 50
const content = renderField?.({ defaultRender: () => defaultField(field, index), field, form: f, index }) ?? defaultField(field, index)
return (
<div
className={cx(cn.field, half ? cn.fieldHalf : cn.fieldFull)}
data-type={field.blockType}
data-width={field.width ?? 100}
key={field.id ?? `${field.blockType}-${index}`}
>
{content}
</div>
)
})}
</div>
</div>
{f.isLast ? <div className={cn.turnstile}><f.TurnstileWidget theme={turnstileTheme} /></div> : null}
{f.errorMessage ? <p className={cn.formError} role="alert">{f.errorMessage}</p> : null}
<div className={cn.actions}>
{!f.isFirst ? <button className={cn.back} onClick={f.back} type="button">{options.texts.back ?? 'Back'}</button> : null}
<button className={f.isLast ? cn.submit : (cn.next ?? cn.submit)} disabled={f.isSubmitting} type="submit">
{f.isLast ? options.form.submitButtonLabel || 'Send' : options.texts.next ?? 'Next'}
</button>
</div>
</form>
)
}
+109
View File
@@ -0,0 +1,109 @@
import type { SerializedEditorState } from '@payloadcms/richtext-lexical/lexical'
import type { JSXConvertersFunction } from '@payloadcms/richtext-lexical/react'
import type { ReactNode } from 'react'
import type { ResolveLinkHrefOptions } from '../links/resolveLinkHref.js'
import type { BuilderFormClassNames } from './BuilderForm.js'
import type { BuilderField, BuilderFormDoc, BuilderFormTexts } from './builderTypes.js'
import type { SubmitActionResult } from './createSubmitAction.js'
import { resolveLinkHref, safeHref } from '../links/resolveLinkHref.js'
import { RenderRichText } from '../richtext/RenderRichText.js'
import { BuilderForm } from './BuilderForm.js'
/** The action from createSubmitAction — `sendForm(formId, locale, values, token?)`. */
export type SendFormAction = (
formId: string,
locale: string,
values: Record<string, unknown>,
turnstileToken?: string,
) => Promise<SubmitActionResult>
export type RenderFormProps = {
/** The project's `sendForm` server action (createSubmitAction). */
action: SendFormAction
classNames?: BuilderFormClassNames
/** Rich text styling for message blocks and the confirmation (same as RenderRichText). */
converters?: JSXConvertersFunction
/** The `form` relationship of the block, populated (page query depth ≥ 1). An id or null renders nothing. */
form: BuilderFormDoc | null | number | string | undefined
/**
* For redirect forms pointing at a page: `{ config: i18nConfig, homeSlug }`
* (locale is added). Without it only a custom URL redirect works.
*/
linkOptions?: Omit<ResolveLinkHrefOptions, 'locale'>
locale: string
requiredMark?: ReactNode
richTextClassName?: string
/** Notifications → form texts in this locale (getNotificationTexts(...).form). */
texts: BuilderFormTexts
turnstileTheme?: 'auto' | 'dark' | 'light'
}
/** Only what the browser needs. The Local API reads with overrideAccess, so the
* document still carries Emails (recipient addresses) — those never leave the server. */
function publicForm(form: BuilderFormDoc): BuilderFormDoc {
return {
id: form.id,
analytics: form.analytics,
confirmationType: form.confirmationType,
fields: (form.fields ?? []).map(({ message: _message, ...field }: BuilderField) => field),
redirect: form.redirect?.type === 'custom' || form.redirect?.url ? { url: safeHref(form.redirect?.url) } : null,
submitButtonLabel: form.submitButtonLabel,
title: form.title,
}
}
/**
* A panel form inside a block, in one line — server part of BuilderForm:
*
* <RenderForm form={form} action={sendForm} locale={locale} texts={formTexts} classNames={formClasses} />
*
* Renders `message` blocks and the confirmation with RenderRichText, binds the
* action to the form and locale, resolves the redirect target, and passes the
* client only the public part of the form (never the Emails tab).
*/
export function RenderForm({
action,
classNames,
converters,
form,
linkOptions,
locale,
requiredMark,
richTextClassName,
texts,
turnstileTheme,
}: RenderFormProps) {
if (!form || typeof form !== 'object') {return null} // never a placeholder form
const rich = (data: unknown) =>
data ? <RenderRichText className={richTextClassName} converters={converters} data={data as SerializedEditorState} /> : null
const messages: Record<number, ReactNode> = {}
form.fields?.forEach((field, i) => {
if (field.blockType === 'message' && field.message) {messages[i] = rich(field.message)}
})
const page = form.redirect?.type === 'reference' ? (form.redirect.reference as { value?: unknown } | null)?.value : undefined
const redirectHref =
form.confirmationType === 'redirect'
? page && linkOptions
? resolveLinkHref({ type: 'internal', page }, { ...linkOptions, locale })
: safeHref(form.redirect?.url)
: null
return (
<BuilderForm
action={action.bind(null, String(form.id), locale)}
classNames={classNames}
confirmation={rich(form.confirmationMessage)}
form={publicForm(form)}
messages={messages}
redirectHref={redirectHref}
requiredMark={requiredMark}
texts={texts}
turnstileTheme={turnstileTheme}
/>
)
}
+74
View File
@@ -0,0 +1,74 @@
import type { Block, Field } from 'payload'
/**
* Extra form-builder field types — what the built-in set can't express:
*
* - `step` — a divider: fields below it (until the next Step) are one
* screen of a step-by-step form, with Next / Back buttons.
* Carries no value.
* - `checkboxGroup` — a list of options where the visitor ticks several
* ("Services you're interested in"). Value: string[].
*
* Plain English labels (the panel is EN). Rendered by BuilderForm /
* useBuilderForm, validated by submitForm like every other field.
*/
const name: Field = {
name: 'name',
type: 'text',
admin: { description: 'Technical name, e.g. "services" — no spaces.', width: '50%' },
label: 'Name (lowercase, no special characters)',
required: true,
}
const label: Field = { name: 'label', type: 'text', admin: { width: '50%' }, label: 'Label', localized: true }
const width: Field = { name: 'width', type: 'number', admin: { width: '50%' }, label: 'Field width (percentage)' }
const required: Field = { name: 'required', type: 'checkbox', admin: { width: '50%' }, label: 'Required' }
export const stepBlock: Block = {
slug: 'step',
fields: [
{
name: 'title',
type: 'text',
admin: {
description:
'Starts a new step: the fields below it (until the next Step) are shown together, with Next / Back buttons. Leave the form without Steps for a single-screen form.',
},
label: 'Step title',
localized: true,
},
{ name: 'description', type: 'textarea', admin: { rows: 2 }, label: 'Step description', localized: true },
],
labels: { plural: 'Steps', singular: 'Step' },
}
export const checkboxGroupBlock: Block = {
slug: 'checkboxGroup',
fields: [
{ type: 'row', fields: [name, label] },
{ type: 'row', fields: [width, required] },
{
name: 'options',
type: 'array',
fields: [
{
type: 'row',
fields: [
{ name: 'label', type: 'text', admin: { width: '50%' }, label: 'Label', localized: true, required: true },
{ name: 'value', type: 'text', admin: { width: '50%' }, label: 'Value', required: true },
],
},
],
labels: { plural: 'Options', singular: 'Option' },
minRows: 1,
},
{
type: 'row',
fields: [
{ name: 'minSelected', type: 'number', admin: { description: 'Empty = no minimum (Required = at least one).', width: '50%' }, label: 'Minimum selected', min: 0 },
{ name: 'maxSelected', type: 'number', admin: { description: 'Empty = no limit.', width: '50%' }, label: 'Maximum selected', min: 1 },
],
},
],
labels: { plural: 'Checkbox groups', singular: 'Checkbox group' },
}
+96
View File
@@ -0,0 +1,96 @@
import type { BuilderField, BuilderFormTexts, BuilderStep } from './builderTypes.js'
import { NON_INPUT_TYPES } from './builderTypes.js'
import { isEmail } from './validators.js'
/**
* Pure logic of a panel form — steps, initial values, validation. No React, so
* it's shared by useBuilderForm and tested on its own. The server re-checks
* everything (validateSubmission); this is only for instant feedback.
*/
/** Fields that hold a value (have a name and aren't message/step). */
export function inputFields(fields: BuilderField[] | null | undefined): ({ name: string } & BuilderField)[] {
return (fields ?? []).filter(
(f): f is { name: string } & BuilderField => typeof f.name === 'string' && f.name !== '' && !NON_INPUT_TYPES.has(f.blockType),
)
}
/**
* Splits the field list at `step` blocks. Fields before the first Step form
* the first screen; a form without Steps is one screen.
*/
export function splitSteps(fields: BuilderField[] | null | undefined): BuilderStep[] {
const steps: BuilderStep[] = []
let current: BuilderStep | null = null
;(fields ?? []).forEach((field, index) => {
if (field.blockType === 'step') {
current = { description: field.description ?? undefined, fields: [], index: steps.length, title: field.title ?? undefined }
steps.push(current)
return
}
if (!current) {
current = { fields: [], index: 0 }
steps.push(current)
}
current.fields.push({ field, index })
})
// Drop screens a trailing / doubled Step left empty.
const kept = steps.filter((s) => s.fields.length > 0)
return (kept.length ? kept : [{ fields: [], index: 0 }]).map((s, i) => ({ ...s, index: i }))
}
/** Starting values: checkbox → boolean, checkboxGroup → string[], the rest → string. */
export function initialBuilderValues(fields: BuilderField[] | null | undefined): Record<string, unknown> {
return Object.fromEntries(
inputFields(fields).map((f) => {
if (f.blockType === 'checkbox') {return [f.name, f.defaultValue === true]}
if (f.blockType === 'checkboxGroup') {return [f.name, Array.isArray(f.defaultValue) ? f.defaultValue : []]}
const v = f.defaultValue
return [f.name, typeof v === 'string' || typeof v === 'number' ? String(v) : '']
}),
)
}
const isBlank = (v: unknown) =>
v == null || v === false || (typeof v === 'string' && v.trim() === '') || (Array.isArray(v) && v.length === 0)
/** Errors for the given fields (one message per field), empty object = valid. */
export function validateBuilderFields(
fields: BuilderField[],
values: Record<string, unknown>,
texts: Pick<BuilderFormTexts, 'validation'>,
): Record<string, string> {
const errors: Record<string, string> = {}
for (const f of inputFields(fields)) {
const v = values[f.name]
const msg = texts.validation.replace('{field}', f.label || f.name)
if (isBlank(v)) {
if (f.required) {errors[f.name] = msg}
continue
}
if (f.blockType === 'email' && !isEmail(v)) {errors[f.name] = msg}
else if (f.blockType === 'number' && !Number.isFinite(Number(v))) {errors[f.name] = msg}
else if (f.blockType === 'checkboxGroup' && Array.isArray(v)) {
if ((f.minSelected && v.length < f.minSelected) || (f.maxSelected && v.length > f.maxSelected)) {errors[f.name] = msg}
}
}
return errors
}
/** Index of the step holding a field — to jump back to it after a failed submit. */
export function stepOfField(steps: BuilderStep[], name: string): number {
const i = steps.findIndex((s) => s.fields.some(({ field }) => field.name === name))
return i < 0 ? 0 : i
}
/** Browser autofill hint from the field type / a conventional name. */
export function autoCompleteFor(field: BuilderField): string | undefined {
if (field.blockType === 'email') {return 'email'}
if (field.blockType === 'country') {return 'country-name'}
const n = (field.name ?? '').toLowerCase()
if (/^(?:full_?)?name$|^imie/.test(n)) {return 'name'}
if (/phone|tel/.test(n)) {return 'tel'}
if (/company|organi[sz]ation|firma/.test(n)) {return 'organization'}
return undefined
}
+69
View File
@@ -0,0 +1,69 @@
import type { FormAnalyticsConfig } from './formAnalytics.js'
/**
* Shapes of a panel form as the frontend receives it (form-builder + ipal's
* step / checkboxGroup). Loose on purpose — the project's generated types fit.
*/
export type BuilderOption = { label?: null | string; value: string }
export type BuilderField = {
blockName?: null | string
/** text · textarea · email · number · date · select · radio · checkbox · checkboxGroup · country · state · message · step · a project's own type */
blockType: string
defaultValue?: unknown
/** step */
description?: null | string
id?: null | string
label?: null | string
maxSelected?: null | number
/** message — rich text, rendered on the server (RenderForm) */
message?: unknown
minSelected?: null | number
name?: null | string
options?: BuilderOption[] | null
placeholder?: null | string
required?: boolean | null
/** step */
title?: null | string
width?: null | number
}
export type BuilderFormDoc = {
analytics?: FormAnalyticsConfig
confirmationMessage?: unknown
confirmationType?: 'message' | 'redirect' | null
fields?: BuilderField[] | null
id: number | string
redirect?: { reference?: unknown; type?: 'custom' | 'reference' | null; url?: null | string } | null
submitButtonLabel?: null | string
title?: null | string
}
/** Texts the form needs — Notifications → form (getNotificationTexts) fits. */
export type BuilderFormTexts = {
back?: string
error?: string
next?: string
/** "Step {current} of {total}" */
stepOf?: string
success?: string
/** "Please check the {field} field" */
validation: string
}
/** The bound server action: createSubmitAction(...) bound to formId + locale (RenderForm does it). */
export type BuilderFormAction = (
values: Record<string, unknown>,
turnstileToken?: string,
) => Promise<{ field?: string; message?: string; reason?: string; success: boolean }>
export type BuilderStep = {
description?: string
/** Every field of the step, `message` blocks included, in panel order. */
fields: { field: BuilderField; index: number }[]
index: number
title?: string
}
/** Field types that carry no value. */
export const NON_INPUT_TYPES = new Set(['message', 'step'])
+11 -1
View File
@@ -5,6 +5,7 @@ import { formBuilderPlugin } from '@payloadcms/plugin-form-builder'
import type { FormsOption } from './types.js'
import { hasMinimumRole, isAdmin } from '../access/predicates.js'
import { checkboxGroupBlock, stepBlock } from './builderBlocks.js'
type AccessArgs = { req: { user?: unknown } }
@@ -52,16 +53,25 @@ export function buildFormsPlugin(forms: FormsOption): Plugin {
const adminGroup = forms.adminGroup === undefined ? 'Forms' : forms.adminGroup
const group = adminGroup ? { group: adminGroup } : {}
return formBuilderPlugin({
// Built-in types + ipal's `step` and `checkboxGroup` (builderBlocks). All are
// panel choices only — a form uses what the editor adds, nothing changes on
// existing forms. Switch any off with forms.fields.<type>: false.
fields: {
checkbox: true,
checkboxGroup: forms.fields?.checkboxGroup === false ? false : checkboxGroupBlock,
date: true,
email: true,
message: true,
number: true,
payment: false,
radio: true,
select: true,
step: forms.fields?.step === false ? false : stepBlock,
text: true,
textarea: true,
...forms.fields,
...Object.fromEntries(
Object.entries(forms.fields ?? {}).filter(([k]) => k !== 'checkboxGroup' && k !== 'step'),
),
},
...(forms.redirectRelationships
? { redirectRelationships: forms.redirectRelationships }
+5
View File
@@ -1,3 +1,8 @@
// Panel field types: step-by-step forms + multiple choice (enabled by default).
export { checkboxGroupBlock, stepBlock } from './builderBlocks.js'
// Pure panel-form logic (steps, values, validation) — the engine of useBuilderForm.
export { initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields } from './builderLogic.js'
export type { BuilderField, BuilderFormDoc, BuilderFormTexts, BuilderStep } from './builderTypes.js'
export { formAnalyticsOnSuccess } from './formAnalytics.js'
export type { FormAnalyticsConfig } from './formAnalytics.js'
// Panel-managed form analytics: fields (config-time) + onSuccess helper (client).
+2 -1
View File
@@ -147,7 +147,8 @@ export async function submitForm({
form: formId,
submissionData: Object.entries(validation.cleaned).map(([field, value]) => ({
field,
value: value == null ? '' : typeof value === 'object' ? JSON.stringify(value) : String(value as boolean | number | string),
// checkboxGroup → "a, b" (readable in the panel and in {{field}} e-mails)
value: value == null ? '' : Array.isArray(value) ? value.join(', ') : typeof value === 'object' ? JSON.stringify(value) : String(value as boolean | number | string),
})),
} as never,
})
+9
View File
@@ -34,11 +34,20 @@ export type FormsOption = {
/** Field types available in the form builder. Sensible defaults applied. */
fields?: {
checkbox?: boolean
/** Multiple choice from a list (ipal). Default on. */
checkboxGroup?: boolean
country?: boolean
date?: boolean
email?: boolean
message?: boolean
number?: boolean
payment?: boolean
/** Single choice from a list. Default on. */
radio?: boolean
select?: boolean
state?: boolean
/** Step-by-step forms: divider between screens (ipal). Default on. */
step?: boolean
text?: boolean
textarea?: boolean
}
+268
View File
@@ -0,0 +1,268 @@
'use client'
import type { ChangeEvent } from 'react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import type { BuilderField, BuilderFormAction, BuilderFormDoc, BuilderFormTexts, BuilderOption } from './builderTypes.js'
import { safeHref } from '../links/resolveLinkHref.js'
import { useOptionalTurnstile } from '../turnstile/TurnstileProvider.js'
import { autoCompleteFor, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields } from './builderLogic.js'
import { formAnalyticsOnSuccess } from './formAnalytics.js'
import { useForm } from './useForm.js'
export type UseBuilderFormOptions = {
/** Bound server action (RenderForm binds createSubmitAction to formId + locale). */
action: BuilderFormAction
form: BuilderFormDoc
/** Router navigation for redirect forms (e.g. router.push). Default: window.location.assign. */
navigate?: (href: string) => void
/** After a successful submit — on top of the panel's analytics event. */
onSuccess?: (values: Record<string, unknown>) => void
/** Redirect target resolved on the server (RenderForm). Falls back to the form's custom URL. */
redirectHref?: null | string
texts: BuilderFormTexts
}
/**
* Engine of every panel form: steps, values, per-step validation, Turnstile,
* submit through the server action, field errors from the server, redirect,
* analytics — and NO markup. <BuilderForm> renders a default on top of it; a
* form that looks or behaves differently (cards to pick from, a summary step,
* a custom field type) builds its own markup on the same hook:
*
* const f = useBuilderForm({ form, action, texts })
* <form onSubmit={f.submit}>
* {f.step.fields.map(({ field }) => <input key={field.name} {...f.getInputProps(field)} />)} // getTextareaProps, getSelectProps, getOptionProps
* <f.TurnstileWidget />
* {!f.isFirst && <button type="button" onClick={f.back}>{texts.back}</button>}
* <button type="submit">{f.isLast ? form.submitButtonLabel : texts.next}</button>
* </form>
*/
export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref, texts }: UseBuilderFormOptions) {
const fields = useMemo(() => form.fields ?? [], [form.fields])
const steps = useMemo(() => splitSteps(fields), [fields])
const inputs = useMemo(() => inputFields(fields), [fields])
const [stepIndex, setStepIndex] = useState(0)
const [resultMessage, setResultMessage] = useState<null | string>(null)
const ts = useOptionalTurnstile()
// A field error returned by the server (e.g. "email invalid") — applied after useForm records the failure.
const serverFieldError = useRef<{ field: string; message: string } | null>(null)
const submitAction = useCallback(
async (values: Record<string, unknown>, token?: string) => {
const result = await action(values, token)
if (result.success) {setResultMessage(result.message ?? null)}
else if (result.field) {serverFieldError.current = { field: result.field, message: result.message ?? texts.validation.replace('{field}', result.field) }}
return result
},
[action, texts.validation],
)
const validate = useCallback((values: Record<string, unknown>) => validateBuilderFields(inputs, values, texts), [inputs, texts])
const f = useForm<Record<string, unknown>>({
errorFallback: texts.error,
initialValues: initialBuilderValues(fields),
onSuccess: (_result, values) => {
formAnalyticsOnSuccess(form.analytics)(_result, values)
onSuccess?.(values)
if (form.confirmationType === 'redirect') {
const href = redirectHref ?? safeHref(form.redirect?.url)
if (href) {(navigate ?? ((h: string) => window.location.assign(h)))(href)}
}
},
requireTurnstile: ts.enabled,
submitAction,
validate,
})
const { setErrors, setTurnstileToken } = f
// Turnstile token lives in the provider; the engine needs it at submit.
useEffect(() => setTurnstileToken(ts.token), [ts.token, setTurnstileToken])
useEffect(() => {
if (!f.errorMessage) {return}
ts.reset()
const fieldError = serverFieldError.current
serverFieldError.current = null
if (fieldError) {
setErrors({ [fieldError.field]: fieldError.message })
setStepIndex(stepOfField(steps, fieldError.field))
}
}, [f.errorMessage])
const step = steps[Math.min(stepIndex, steps.length - 1)]
const isFirst = stepIndex === 0
const isLast = stepIndex >= steps.length - 1
/** Validates the current step and moves on. Returns false when the step has errors. */
const next = useCallback(() => {
const errors = validateBuilderFields(step.fields.map(({ field }) => field), f.values, texts)
setErrors(errors)
if (Object.keys(errors).length) {return false}
setStepIndex((i) => Math.min(i + 1, steps.length - 1))
return true
}, [step, f.values, texts, setErrors, steps.length])
const back = useCallback(() => setStepIndex((i) => Math.max(i - 1, 0)), [])
/** Jump to a step that's already been passed (a clickable progress bar). Forward jumps validate on the way. */
const goTo = useCallback(
(target: number) => {
if (target <= stepIndex) {return setStepIndex(Math.max(target, 0))}
for (let i = stepIndex; i < target; i++) {
const errors = validateBuilderFields(steps[i].fields.map(({ field }) => field), f.values, texts)
if (Object.keys(errors).length) {
setErrors(errors)
return setStepIndex(i)
}
}
setStepIndex(Math.min(target, steps.length - 1))
},
[stepIndex, steps, f.values, texts, setErrors],
)
/** onSubmit of the <form>: Next on earlier steps, send on the last one. */
const submit = useCallback(
(e?: { preventDefault?: () => void }) => {
e?.preventDefault?.()
if (!isLast) {return void next()}
const errors = validate(f.values)
if (Object.keys(errors).length) {
setErrors(errors)
return setStepIndex(stepOfField(steps, Object.keys(errors)[0]))
}
void f.handleSubmit()
},
[isLast, next, validate, f, setErrors, steps],
)
const fieldId = useCallback((field: BuilderField) => `ipal-f-${String(form.id)}-${field.name ?? ''}`, [form.id])
const errorId = useCallback((field: BuilderField) => `${fieldId(field)}-error`, [fieldId])
/** id, name, required and aria for any field's control (or its fieldset). */
const getFieldProps = useCallback(
(field: BuilderField) => {
const error = field.name ? f.errors[field.name] : undefined
return {
id: fieldId(field),
name: field.name ?? undefined,
'aria-describedby': error ? errorId(field) : undefined,
'aria-invalid': error ? true : undefined,
required: Boolean(field.required),
}
},
[f.errors, errorId, fieldId],
)
const textValue = useCallback((name: string) => {
const value = f.values[name]
return typeof value === 'string' ? value : value == null ? '' : String(value as number)
}, [f.values])
/** Everything an <input> needs, by field type: text · email · number · date · tel · checkbox. */
const getInputProps = useCallback(
(field: BuilderField) => {
const name = field.name ?? ''
const base = { ...getFieldProps(field), autoComplete: autoCompleteFor(field) }
if (field.blockType === 'checkbox') {
return { ...base, type: 'checkbox', checked: f.values[name] === true, onChange: (e: ChangeEvent<HTMLInputElement>) => f.setField(name, e.target.checked) }
}
const type =
field.blockType === 'email' ? 'email'
: field.blockType === 'number' ? 'number'
: field.blockType === 'date' ? 'date'
: base.autoComplete === 'tel' ? 'tel'
: 'text'
return {
...base,
...(type === 'number' ? { inputMode: 'decimal' as const } : {}),
type,
onChange: (e: ChangeEvent<HTMLInputElement>) => f.setField(name, e.target.value),
placeholder: field.placeholder ?? undefined,
value: textValue(name),
}
},
[f, getFieldProps, textValue],
)
/** Props of a <textarea>. */
const getTextareaProps = useCallback(
(field: BuilderField) => ({
...getFieldProps(field),
onChange: (e: ChangeEvent<HTMLTextAreaElement>) => f.setField(field.name ?? '', e.target.value),
placeholder: field.placeholder ?? undefined,
value: textValue(field.name ?? ''),
}),
[f, getFieldProps, textValue],
)
/** Props of a <select> (render the options yourself — field.options). */
const getSelectProps = useCallback(
(field: BuilderField) => ({
...getFieldProps(field),
autoComplete: autoCompleteFor(field),
onChange: (e: ChangeEvent<HTMLSelectElement>) => f.setField(field.name ?? '', e.target.value),
value: textValue(field.name ?? ''),
}),
[f, getFieldProps, textValue],
)
/** Props of one option's input in a radio group or checkboxGroup. */
const getOptionProps = useCallback(
(field: BuilderField, option: BuilderOption, i: number) => {
const name = field.name ?? ''
const id = `${fieldId(field)}-${i}`
if (field.blockType === 'checkboxGroup') {
const picked = Array.isArray(f.values[name]) ? (f.values[name] as string[]) : []
return {
id,
name,
type: 'checkbox',
checked: picked.includes(option.value),
onChange: (e: ChangeEvent<HTMLInputElement>) =>
f.setField(name, e.target.checked ? [...picked, option.value] : picked.filter((v) => v !== option.value)),
value: option.value,
}
}
return {
id,
name,
type: 'radio',
checked: f.values[name] === option.value,
onChange: () => f.setField(name, option.value),
required: Boolean(field.required) && i === 0,
value: option.value,
}
},
[f, fieldId],
)
return {
...f,
back,
errorId,
fieldId,
form,
getFieldProps,
getInputProps,
getOptionProps,
getSelectProps,
getTextareaProps,
goTo,
isFirst,
isLast,
next,
/** Message the server returned on success (Notifications → success). */
resultMessage,
step,
stepIndex,
steps,
submit,
total: steps.length,
TurnstileWidget: ts.TurnstileWidget,
}
}
export type BuilderFormApi = ReturnType<typeof useBuilderForm>
+30 -4
View File
@@ -4,8 +4,11 @@ import type { BasePayload } from 'payload'
type FormField = {
blockType?: string
label?: string
/** checkboxGroup limits. */
maxSelected?: null | number
minSelected?: null | number
name?: string
/** select / radio choices defined in the panel. */
/** select / radio / checkboxGroup choices defined in the panel. */
options?: { value?: unknown }[] | null
required?: boolean | null
}
@@ -35,7 +38,10 @@ export type FormValidationResult =
| { ok: false; reason: 'not_found' }
/** Field block types that don't carry a submittable value. */
const NON_DATA_BLOCKS = new Set(['message'])
const NON_DATA_BLOCKS = new Set(['message', 'step'])
/** YYYY-MM-DD (a date input) or a full ISO timestamp. */
const DATE = /^\d{4}-\d{2}-\d{2}(?:T[\d:.]+(?:Z|[+-]\d{2}:?\d{2})?)?$/
/**
* Keys injected by the captcha widget itself, not by the form definition.
@@ -63,7 +69,7 @@ const MAX_EMAIL_LENGTH = 254
// eslint-disable-next-line no-control-regex
const CONTROL = /[\u0000-\u0008\v\f\u000E-\u001F\u007F\u202A-\u202E\u2066-\u2069]/g
type Checked = { error?: 'invalid_format'; value?: unknown }
type Checked = { error?: 'invalid_format' | 'required'; value?: unknown }
/**
* Type-checks one value against its field's block type, as defined in the
@@ -76,6 +82,23 @@ function checkValue(field: FormField, value: unknown): Checked {
switch (field.blockType) {
case 'checkbox':
return typeof value === 'boolean' ? { value } : { error: 'invalid_format' }
case 'checkboxGroup': {
// string[] of distinct option values, within the panel's min/max.
if (!Array.isArray(value) || value.some((v) => typeof v !== 'string')) {return { error: 'invalid_format' }}
const picked = [...new Set(value as string[])]
const allowed = new Set((field.options ?? []).map((o) => String(o?.value)))
if (picked.some((v) => !allowed.has(v))) {return { error: 'invalid_format' }}
if (picked.length === 0) {return { value: undefined }}
if (field.minSelected && picked.length < field.minSelected) {return { error: 'required' }}
if (field.maxSelected && picked.length > field.maxSelected) {return { error: 'invalid_format' }}
return { value: picked }
}
case 'date': {
if (typeof value !== 'string' || !DATE.test(value.trim()) || Number.isNaN(Date.parse(value.trim()))) {
return { error: 'invalid_format' }
}
return { value: value.trim() }
}
case 'email': {
if (typeof value !== 'string') {return { error: 'invalid_format' }}
const email = value.trim()
@@ -154,7 +177,10 @@ export async function validateSubmission(
for (const field of fields) {
const value = data[field.name]
const isBlank =
value == null || (typeof value === 'string' && value.trim() === '') || value === false
value == null ||
(typeof value === 'string' && value.trim() === '') ||
value === false ||
(Array.isArray(value) && value.length === 0)
// GDPR consent gate: a field matching the consent name must be truthy
// (checked). Enforced independently of `required`, so it can't be weakened
+74
View File
@@ -0,0 +1,74 @@
import type { ReactNode } from 'react'
import type { AnalyticsProps } from '../analytics/Analytics.js'
import type { ConsentCookieMap } from '../consent/useConsent.js'
import type { SiteShell } from './createContentHelpers.js'
import { Analytics } from '../analytics/Analytics.js'
import { ConsentProvider } from '../consent/ConsentContext.js'
import { CookieBanner } from '../consent/CookieBanner.js'
import { CookieButton } from '../consent/CookieButton.js'
import { JsonLdGraph } from '../seo/JsonLdGraph.js'
import { MediaPreconnect } from '../storage/MediaPreconnect.js'
import { TurnstileProvider } from '../turnstile/TurnstileProvider.js'
export type SiteProvidersProps = {
/** `defer` etc. for <Analytics>; `false` = no analytics tags at all. */
analytics?: false | Omit<AnalyticsProps, keyof SiteShell['analytics']>
/** The cookie banner. Default `<CookieBanner />`; pass your own configured one (`equalChoice`, classNames) or `false`. */
banner?: false | ReactNode
children: ReactNode
/** The "cookie settings" button. Default `<CookieButton />`; your own or `false`. */
cookieButton?: false | ReactNode
/** Extra cookies per category to delete when consent is withdrawn. */
cookieMap?: ConsentCookieMap
/** More site-wide JSON-LD nodes next to shell.jsonLd (e.g. buildNavigationJsonLd). */
jsonLd?: (null | Record<string, unknown> | undefined)[]
/** Consent log endpoint, e.g. '/api/ipal/consent' (ipalKit consentLog: true). */
logEndpoint?: string
/** <link rel=preconnect> to the media origin (R2_PUBLIC_URL). Default true. */
preconnect?: boolean
/** getSiteShell(locale) from lib/content. */
shell: SiteShell
}
/**
* The wiring every [locale] layout repeats — consent, Turnstile, analytics,
* site JSON-LD, media preconnect — in the right order (Analytics inside the
* consent provider, forms inside Turnstile). Renders no markup of its own:
* <html>, <body>, header, footer and <main> stay in the layout.
*
* const shell = await getSiteShell(locale)
* <body>
* <SiteProviders shell={shell} logEndpoint="/api/ipal/consent" banner={<CookieBanner equalChoice />}>
* <Header … /><main>{children}</main><Footer … />
* </SiteProviders>
* </body>
*
* Every part is replaceable or switchable off; for a fully custom tree use the
* providers themselves (consent.md, turnstile.md) — the shell data still fits.
*/
export function SiteProviders({
analytics,
banner,
children,
cookieButton,
cookieMap,
jsonLd = [],
logEndpoint,
preconnect = true,
shell,
}: SiteProvidersProps) {
return (
<>
{preconnect ? <MediaPreconnect /> : null}
<JsonLdGraph schemas={[...shell.jsonLd, ...jsonLd]} />
<ConsentProvider cookieMap={cookieMap} logEndpoint={logEndpoint} texts={shell.consent}>
<TurnstileProvider siteKey={shell.turnstileSiteKey}>{children}</TurnstileProvider>
{banner === undefined ? <CookieBanner /> : banner || null}
{cookieButton === undefined ? <CookieButton /> : cookieButton || null}
{analytics === false ? null : <Analytics {...shell.analytics} {...analytics} />}
</ConsentProvider>
</>
)
}
+178 -1
View File
@@ -3,14 +3,32 @@ import type { BasePayload, SanitizedConfig } from 'payload'
import { getPayload } from 'payload'
import { cache } from 'react'
import type { AnalyticsConfig } from '../analytics/types.js'
import type { ConsentTexts } from '../consent/texts.js'
import type { ArchiveEntries, ContentOption, ResolvedRoute } from '../content/index.js'
import type { I18nConfig } from '../i18n/index.js'
import type { LinkValue, NavItem, ResolvedLink, ResolveLinkHrefOptions } from '../links/index.js'
import type { CreateMcpRouteArgs } from '../mcp/createMcpRoute.js'
import type { FormNotificationTexts } from '../notifications/types.js'
import type { PageMetadata, RobotsOptions, RobotsRules, SitemapEntry, SitemapStyleOptions } from '../seo/index.js'
import { getAnalyticsConfig } from '../analytics/getAnalyticsConfig.js'
import { getConsentTexts } from '../consent/getConsentTexts.js'
import { createMarkdownRoute } from '../content/createMarkdownRenderer.js'
import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js'
import { MARKDOWN_PREFIX, markdownHref } from '../content/markdownNegotiation.js'
import { resolveRedirect as resolveRedirectRaw } from '../content/resolveRedirect.js'
import { createHealthRoute } from '../health/createHealthRoute.js'
import { homeSlugFrom, resolveLink as resolveLinkRaw, resolveNav as resolveNavRaw } from '../links/resolveNav.js'
import { createMcpRoute } from '../mcp/createMcpRoute.js'
import { getNotificationTexts } from '../notifications/getNotificationTexts.js'
import { buildOrganizationJsonLd, sameAsUrls } from '../seo/buildOrganizationJsonLd.js'
import { buildWebPageJsonLd } from '../seo/buildWebPageJsonLd.js'
import { buildArticleJsonLd, buildBreadcrumbJsonLd, buildFaqJsonLd, buildRobots, buildSitemapEntries, createPageMetadata, createSitemapRouteHandler } from '../seo/index.js'
import { buildWebSiteJsonLd } from '../seo/buildWebSiteJsonLd.js'
import { buildArticleJsonLd, buildBreadcrumbJsonLd, buildFaqJsonLd, buildRobots, buildSitemapEntries, createManifestHandler, createPageMetadata, createSitemapRouteHandler } from '../seo/index.js'
import { createIndexNowKeyRoute } from '../seo/indexNow.js'
import { createLlmsTxtRoute } from '../seo/routeHandlers.js'
import { getTurnstileConfig } from '../turnstile/config.js'
type CreateContentHelpersArgs = {
/**
@@ -31,6 +49,8 @@ type CreateContentHelpersArgs = {
* handlers — they need the locale list to emit hreflang.
*/
i18n?: I18nConfig
/** Markdown route (`markdownRoute`): per-block overrides, frontmatter, layout field. */
markdown?: { frontmatter?: boolean; layoutField?: string; overrides?: Record<string, (block: Record<string, unknown>) => string> }
/**
* Advertise each page's Markdown version from generatePageMetadata:
* `<link rel="alternate" type="text/markdown" href="/md/pl/o-nas">` (GEO —
@@ -39,10 +59,14 @@ type CreateContentHelpersArgs = {
* (content.md). Indexable pages only.
*/
markdownAlternate?: boolean | string
/** MCP route (`mcpRoute`): server name/version, rate limit, batch size. */
mcp?: Pick<CreateMcpRouteArgs, 'clientIp' | 'maxBatch' | 'rateLimit' | 'serverName' | 'serverVersion'>
/** Defaults for getPageJsonLd — each call can override them. */
pageJsonLd?: PageJsonLdOptions
/** Pages collection slug. Defaults to 'pages'. */
pagesSlug?: string
/** Collections checked for an old slug before a 404 (`resolvePageRedirect`). Default pages. */
redirectCollections?: { historyField?: string; slug: string; slugField?: string }[]
/**
* Options for the ready-made `robots` handler, e.g.
* `{ disallowParams: ['s', 'meter'], aiBots: 'block-training' }`, or
@@ -51,6 +75,13 @@ type CreateContentHelpersArgs = {
robots?: RobotsOptions
/** SiteSettings global slug. Defaults to 'site-settings'. */
settingsSlug?: string
/**
* Site-wide JSON-LD for `getSiteShell` (layout). Default: WebSite + Organization
* from Site Settings (siteName, logo, sameAs) — skipped when the name or the
* origin is missing, never a fallback name. A function replaces it (e.g.
* LocalBusiness from the Company global); `false` = none.
*/
siteJsonLd?: ((ctx: { baseUrl: string; locale: string; settings: Record<string, unknown> }) => Promise<Record<string, unknown>[]> | Record<string, unknown>[]) | false
/** Image URLs of a document for the sitemap (Google Images). Default: its SEO share image. */
sitemapImages?: (doc: Record<string, unknown>) => (null | string | undefined)[]
/**
@@ -58,6 +89,8 @@ type CreateContentHelpersArgs = {
* header "XML Sitemap", credit "Technology by Intecion.com". `false` = raw XML.
*/
sitemapStyle?: false | SitemapStyleOptions
/** Field with the AI summary (buildSummaryField) — llms.txt and MCP prefer it. */
summaryField?: string
}
export type PageJsonLdOptions = {
@@ -105,13 +138,18 @@ export function createContentHelpers({
config,
content,
i18n,
markdown: markdownOptions,
markdownAlternate,
mcp: mcpOptions,
pageJsonLd: pageJsonLdDefaults,
pagesSlug = 'pages',
redirectCollections,
robots: robotsOptions,
settingsSlug = 'site-settings',
siteJsonLd,
sitemapImages,
sitemapStyle,
summaryField,
}: CreateContentHelpersArgs) {
const origin = baseUrl ?? process.env.NEXT_PUBLIC_SERVER_URL ?? ''
const getCachedPayload = cache(
@@ -522,18 +560,157 @@ export function createContentHelpers({
*/
const sitemapRoute = createSitemapRouteHandler(sitemap, { style: sitemapStyle ?? {} })
const needI18n = (what: string): I18nConfig => {
if (!i18n) {throw new Error(`[ipal] createContentHelpers: pass \`i18n\` to use ${what}.`)}
return i18n
}
// ── Links & navigation ────────────────────────────────────────────────────
/** Homepage slug in this locale (SiteSettings.homepage) — links to it collapse to /{locale}. */
const getHomeSlug = async (locale: string) => homeSlugFrom(await getSettings(locale))
/** Options for resolveLinkHref / resolveLink / RenderForm `linkOptions` in this locale. */
const getLinkOptions = async (locale: string): Promise<ResolveLinkHrefOptions> => {
const homeSlug = await getHomeSlug(locale)
return { config: needI18n('getLinkOptions'), locale, ...(homeSlug ? { homeSlug } : {}) }
}
/**
* A panel link → `{ href, label, internal, newTab, targetProps, appearance }`
* or null. The project's CMSLink only picks the element and the classes.
*/
const resolveLink = async (link: LinkValue | null | undefined, locale: string): Promise<null | ResolvedLink> =>
resolveLinkRaw(link, await getLinkOptions(locale))
/** Menu items of a Header/Footer global → serializable NavItem[] (pass to a client MobileNav as is). */
const resolveNav = async (items: unknown, locale: string, options: { childrenField?: string; linkField?: string } = {}): Promise<NavItem[]> =>
resolveNavRaw(items, { ...(await getLinkOptions(locale)), ...options })
/** Old slug → its new URL (308), for the catch-all page before notFound(). */
const resolvePageRedirect = async (locale: string, segments: string[] | undefined): Promise<null | string> =>
resolveRedirectRaw({
collections: redirectCollections,
config: needI18n('resolvePageRedirect'),
homeSlug: await getHomeSlug(locale),
locale,
payload: await getCachedPayload(),
segments,
})
// ── Layout ────────────────────────────────────────────────────────────────
/** Notifications → form texts in this locale (BuilderForm / RenderForm `texts`). */
const getFormTexts = cache(async (locale: string): Promise<FormNotificationTexts> =>
(await getNotificationTexts({ locale, payload: await getCachedPayload() })).form,
)
/**
* Everything the [locale] layout reads, in one cached call: consent texts,
* analytics IDs, Turnstile site key, site JSON-LD, form texts and Site
* Settings. Feed it to <SiteProviders> (/rsc) — or use the pieces yourself.
*/
const getSiteShell = cache(async (locale: string): Promise<SiteShell> => {
const payload = await getCachedPayload()
const [consent, analytics, turnstile, settings, formTexts] = await Promise.all([
getConsentTexts({ config: needI18n('getSiteShell'), locale, payload, settingsSlug }),
getAnalyticsConfig(payload),
getTurnstileConfig(payload),
getSettings(locale) as Promise<Record<string, unknown>>,
getFormTexts(locale),
])
let jsonLd: Record<string, unknown>[] = []
if (typeof siteJsonLd === 'function') {
jsonLd = await siteJsonLd({ baseUrl: origin, locale, settings: settings ?? {} })
} else if (siteJsonLd !== false) {
const name = typeof settings?.siteName === 'string' && settings.siteName.trim() ? settings.siteName.trim() : undefined
if (name && origin) {
jsonLd = [
buildWebSiteJsonLd({ name, url: origin }),
buildOrganizationJsonLd({ name, logo: settings.logo as never, sameAs: sameAsUrls(settings), url: origin }),
]
}
}
return {
analytics,
consent,
formTexts,
jsonLd: jsonLd.map(({ '@context': _context, ...node }) => node),
settings: settings ?? {},
turnstileSiteKey: turnstile.siteKey,
}
})
// ── Ready route handlers (one line per route file) ────────────────────────
// Created on first request, so a project that doesn't use one pays nothing
// and a missing option only fails the route that needs it.
const lazy = <T>(make: () => T) => {
let value: T | undefined
return () => (value ??= make())
}
const llms = lazy(() => createLlmsTxtRoute({ baseUrl: origin, config: needI18n('llmsRoute'), content, getCachedPayload, pagesSlug, settingsSlug, summaryField }))
const llmsFull = lazy(() => createLlmsTxtRoute({ baseUrl: origin, config: needI18n('llmsFullRoute'), content, full: true, getCachedPayload, pagesSlug, settingsSlug, summaryField }))
const md = lazy(() => createMarkdownRoute({ baseUrl: origin || undefined, collection: pagesSlug, config: i18n, content, getCachedPayload, settingsSlug, ...markdownOptions }))
const mcp = lazy(() => createMcpRoute({ baseUrl: origin, collection: pagesSlug, config: needI18n('mcpRoute'), content, getCachedPayload, settingsSlug, summaryField, ...mcpOptions }))
const health = lazy(() => createHealthRoute({ collection: pagesSlug, getCachedPayload }))
const indexNowKey = lazy(() => createIndexNowKeyRoute({ getCachedPayload }))
const manifestHandler = lazy(() => createManifestHandler({ config: needI18n('manifest'), getCachedPayload, settingsSlug }))
/** app/llms.txt/route.ts: `export { llmsRoute as GET } from '@/lib/content'` */
const llmsRoute = () => llms()()
/** app/llms-full.txt/route.ts: `export { llmsFullRoute as GET } from '@/lib/content'` */
const llmsFullRoute = () => llmsFull()()
/** app/md/[locale]/[[...slug]]/route.ts: `export { markdownRoute as GET } from '@/lib/content'` */
const markdownRoute = (req: Request, ctx: { params: Promise<{ locale: string; slug?: string[] }> }) => md().GET(req, ctx)
/** app/api/mcp/route.ts: `export { mcpGET as GET, mcpPOST as POST } from '@/lib/content'` */
const mcpGET = () => mcp().GET()
const mcpPOST = (req: Request) => mcp().POST(req)
/** app/api/health/route.ts: `export { healthRoute as GET } from '@/lib/content'` */
const healthRoute = () => health()()
/** app/indexnow-key.txt/route.ts: `export { indexNowKeyRoute as GET } from '@/lib/content'` */
const indexNowKeyRoute = () => indexNowKey()()
/** app/manifest.ts: `export { manifest as default } from '@/lib/content'` */
const manifest = () => manifestHandler()()
return {
generatePageMetadata,
generateStaticParams,
getCachedPayload,
getConfiguredLocales,
getEntries,
getFormTexts,
getHomeSlug,
getLinkOptions,
getNotFoundPage,
getPageJsonLd,
getSettings,
getSiteShell,
healthRoute,
i18n,
indexNowKeyRoute,
llmsFullRoute,
llmsRoute,
manifest,
markdownRoute,
mcpGET,
mcpPOST,
resolveLink,
resolveNav,
resolvePageRedirect,
resolveRoute,
robots,
sitemap,
sitemapRoute,
}
}
/** What the layout needs — getSiteShell(locale). Plain data, safe to pass to client components. */
export type SiteShell = {
analytics: AnalyticsConfig
consent: ConsentTexts
formTexts: FormNotificationTexts
/** Site-wide nodes (WebSite, Organization…) for <JsonLdGraph>. */
jsonLd: Record<string, unknown>[]
settings: Record<string, unknown>
turnstileSiteKey: null | string
}
export type ContentHelpers = ReturnType<typeof createContentHelpers>
+138
View File
@@ -0,0 +1,138 @@
import type { ReactNode } from 'react'
import type { BlockComponentMap, BlockData } from '../blocks/types.js'
import type { ResolvedRoute } from '../content/index.js'
import type { ContentHelpers, PageJsonLdOptions } from './createContentHelpers.js'
import { RenderBlocks } from '../blocks/RenderBlocks.js'
import { LocaleView } from '../pages/LocaleView.js'
import { JsonLdGraph } from '../seo/JsonLdGraph.js'
type Helpers = Pick<
ContentHelpers,
'generatePageMetadata' | 'generateStaticParams' | 'getConfiguredLocales' | 'getNotFoundPage' | 'getPageJsonLd' | 'i18n' | 'resolvePageRedirect' | 'resolveRoute'
>
type BlockPropsContext = { doc: Record<string, unknown>; locale: string }
export type PageRouteOptions = {
/** Props for every block on top of `locale`, computed once per page — e.g. `{ formTexts, sendForm }` for form blocks. */
blockProps?: (ctx: BlockPropsContext) => Promise<Record<string, unknown>> | Record<string, unknown>
/** blockType → component (the project's registry). */
blocks: BlockComponentMap
/** Per-page JSON-LD (WebPage, breadcrumbs, FAQ…). Default true; options as getPageJsonLd. */
jsonLd?: boolean | PageJsonLdOptions
/** Field with the blocks. Default 'layout'. */
layoutField?: string
/** `notFound` from 'next/navigation' — injected, the plugin doesn't import next/* on the server. */
notFound: () => never
/** `permanentRedirect` from 'next/navigation' (308 for an old slug). */
permanentRedirect: (url: string) => never
/**
* Render a route yourself — an archive listing, a blog entry template.
* Return undefined to keep the default (the document's blocks).
*/
render?: (ctx: { blocks: ReactNode; locale: string; route: ResolvedRoute; segments: string[] }) => Promise<ReactNode | undefined> | ReactNode | undefined
}
type PageArgs = { params: Promise<{ locale?: string; slug?: string[] }> }
/**
* The catch-all page — route resolution, old-slug 308, 404, metadata, static
* params, per-page JSON-LD and the blocks — from one call:
*
* // src/app/(frontend)/[locale]/[[...slug]]/page.tsx
* import { notFound, permanentRedirect } from 'next/navigation'
* import { createPageRoute } from '@intecion/ipal-kit/rsc'
* import * as content from '@/lib/content'
* import { blockRegistry } from '@/blocks/registry'
*
* export const revalidate = 3600 // must stay a literal in the file (Next reads it statically)
* const route = createPageRoute(content, { blocks: blockRegistry, notFound, permanentRedirect })
* export default route.Page
* export const generateMetadata = route.generateMetadata
* export const generateStaticParams = route.generateStaticParams
*
* Archive listings / entry templates: `render`. Anything else: write the page
* yourself with the same helpers (PROGRAMISTA §2.8) — nothing here is required.
*/
export function createPageRoute(helpers: Helpers, options: PageRouteOptions) {
const { blockProps, blocks, jsonLd = true, layoutField = 'layout', notFound, permanentRedirect, render } = options
const localeOf = (locale: string | undefined) => {
const l = locale ?? helpers.i18n?.defaultLocale
if (!l) {throw new Error('[ipal] createPageRoute: no locale param and no i18n.defaultLocale in createContentHelpers.')}
return l
}
async function generateMetadata({ params }: PageArgs) {
const { slug, locale } = await params
return helpers.generatePageMetadata(localeOf(locale), slug)
}
async function Page({ params }: PageArgs) {
const { slug, locale: param } = await params
const locale = localeOf(param)
const segments = slug ?? []
const route = await helpers.resolveRoute(locale, segments, 1)
if (!route) {
const target = await helpers.resolvePageRedirect(locale, segments)
return target ? permanentRedirect(target) : notFound()
}
const doc = route.doc
const extra = blockProps ? await blockProps({ doc, locale }) : {}
const rendered = (
<RenderBlocks
blocks={doc[layoutField] as BlockData[] | undefined}
components={blocks}
enhanceProps={() => ({ locale, ...extra })}
/>
)
const custom = render ? await render({ blocks: rendered, locale, route, segments }) : undefined
const schemas = jsonLd ? await helpers.getPageJsonLd(locale, slug, jsonLd === true ? {} : jsonLd) : []
return (
<>
{schemas.length ? <JsonLdGraph schemas={schemas} /> : null}
{custom ?? rendered}
</>
)
}
return { generateMetadata, generateStaticParams: helpers.generateStaticParams, Page }
}
export type NotFoundPageOptions = {
blockProps?: (ctx: BlockPropsContext) => Promise<Record<string, unknown>> | Record<string, unknown>
blocks: BlockComponentMap
/** Shown when no 404 page is assigned in Site Settings (or the DB is unreachable). Per locale or one node. */
fallback?: ((locale: string) => ReactNode) | ReactNode
layoutField?: string
}
/**
* app/(frontend)/[locale]/not-found.tsx — the 404 page from the panel, in the
* visitor's language, WITHOUT headers() (the route stays static): one view per
* locale rendered here, <LocaleView> picks the one from the URL.
*
* import { createNotFoundPage } from '@intecion/ipal-kit/rsc'
* export default createNotFoundPage(content, { blocks: blockRegistry })
*/
export function createNotFoundPage(helpers: Helpers, options: NotFoundPageOptions) {
const { blockProps, blocks, fallback = null, layoutField = 'layout' } = options
return async function NotFoundPage() {
const configured = await helpers.getConfiguredLocales()
const locales = configured.length ? configured : [helpers.i18n?.defaultLocale ?? '']
const views = Object.fromEntries(
await Promise.all(
locales.map(async (locale) => {
const doc = await helpers.getNotFoundPage(locale)
const layout = doc?.[layoutField] as BlockData[] | undefined
const fb = typeof fallback === 'function' ? fallback(locale) : fallback
if (!doc || !layout?.length) {return [locale, fb] as const}
const extra = blockProps ? await blockProps({ doc, locale }) : {}
return [locale, <RenderBlocks blocks={layout} components={blocks} enhanceProps={() => ({ locale, ...extra })} key={locale} />] as const
}),
),
)
return <LocaleView defaultLocale={helpers.i18n?.defaultLocale ?? locales[0]} views={views} />
}
}
+2
View File
@@ -2,3 +2,5 @@ export { buildLinkField, buildLinksField } from './buildLinkField.js'
export type { BuildLinkFieldOptions, BuildLinksFieldOptions, LinkAppearance } from './buildLinkField.js'
export { resolveLinkHref, safeHref } from './resolveLinkHref.js'
export type { LinkValue, ResolveLinkHrefOptions } from './resolveLinkHref.js'
export { homeSlugFrom, resolveLink, resolveNav } from './resolveNav.js'
export type { NavItem, ResolvedLink, ResolveNavOptions } from './resolveNav.js'
+77
View File
@@ -0,0 +1,77 @@
import type { LinkValue, ResolveLinkHrefOptions } from './resolveLinkHref.js'
import { resolveLinkHref } from './resolveLinkHref.js'
/**
* Everything an <a>/<Link> needs for a panel link — the project keeps the
* element and the classes (Button variants), the plugin decides the rest:
* href, new tab (files always open in one), rel, and whether it's internal
* (render next/link) or not (plain <a>).
*/
export type ResolvedLink = {
/** `link.appearance` from the panel (primary / secondary / link) — map it to your Button classes. */
appearance?: string
href: string
/** Internal page → next/link; external URL / file / mailto → <a>. */
internal: boolean
label: string
newTab: boolean
/** Spread on the element: target + rel for a new tab, nothing otherwise. */
targetProps: { rel: string; target: '_blank' } | Record<string, never>
}
/** A panel link → ResolvedLink, or null when it leads nowhere in this locale (no page, no file, unsafe URL). */
export function resolveLink(link: LinkValue | null | undefined, options: ResolveLinkHrefOptions): null | ResolvedLink {
const href = resolveLinkHref(link, options)
if (!link || !href) {return null}
const newTab = Boolean(link.newTab) || link.type === 'file'
return {
...(link.appearance ? { appearance: link.appearance } : {}),
href,
internal: (link.type ?? 'internal') === 'internal',
label: link.label ?? '',
newTab,
targetProps: newTab ? { rel: 'noopener noreferrer', target: '_blank' } : {},
}
}
export type NavItem = {
/** Nested items (dropdown), already resolved. */
children: NavItem[]
} & ResolvedLink
export type ResolveNavOptions = {
/** Field with the nested items inside an item. Default 'subItems'. */
childrenField?: string
/** Field with the link inside an item. Default 'link'. */
linkField?: string
} & ResolveLinkHrefOptions
/**
* Menu items from a Header/Footer global → plain, serializable items (safe to
* pass to a client MobileNav). Items whose link leads nowhere in this locale
* — a deleted or untranslated page — are dropped instead of rendering "#".
*
* const items = resolveNav(header.navItems, { locale, config: i18nConfig, homeSlug })
* // [{ href, label, newTab, internal, targetProps, children: [...] }]
*
* Any depth; the item shape is configurable (linkField, childrenField).
*/
export function resolveNav(items: unknown, options: ResolveNavOptions): NavItem[] {
const { childrenField = 'subItems', linkField = 'link', ...linkOptions } = options
if (!Array.isArray(items)) {return []}
return items.flatMap((item) => {
if (!item || typeof item !== 'object') {return []}
const record = item as Record<string, unknown>
const link = resolveLink(record[linkField] as LinkValue, linkOptions)
if (!link || !link.label) {return []}
return [{ ...link, children: resolveNav(record[childrenField], options) }]
})
}
/** Homepage slug from SiteSettings (`homepage` relationship, populated) — for links that collapse to /{locale}. */
export function homeSlugFrom(settings: unknown, field = 'homepage'): string | undefined {
const home = settings && typeof settings === 'object' ? (settings as Record<string, unknown>)[field] : undefined
const slug = home && typeof home === 'object' ? (home as { slug?: unknown }).slug : undefined
return typeof slug === 'string' && slug ? slug : undefined
}
+1 -1
View File
@@ -46,7 +46,7 @@ import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit
const DEFAULT_PROTOCOL = '2025-06-18'
type CreateMcpRouteArgs = {
export type CreateMcpRouteArgs = {
/** Absolute origin for building result URLs. */
baseUrl?: string
/** How to read the client IP for the rate limit — see clientIp(). */
+3
View File
@@ -7,10 +7,13 @@ import type { NotificationTexts } from './types.js'
*/
export const NOTIFICATION_FALLBACK: NotificationTexts = {
form: {
back: 'Back',
consent: 'Please accept the privacy policy to continue.',
error: 'Something went wrong. Please try again later.',
next: 'Next',
notFound: 'This form is no longer available.',
rateLimited: 'Too many attempts. Please wait a moment and try again.',
stepOf: 'Step {current} of {total}',
success: 'Thank you — your message has been sent.',
turnstile: 'Captcha verification failed. Please try again.',
validation: 'Please check the {field} field and try again.',
@@ -28,10 +28,13 @@ export async function getNotificationTexts({
return {
form: {
back: f.back || fb.back,
consent: f.consent || fb.consent,
error: f.error || fb.error,
next: f.next || fb.next,
notFound: f.notFound || fb.notFound,
rateLimited: f.rateLimited || fb.rateLimited,
stepOf: f.stepOf || fb.stepOf,
success: f.success || fb.success,
turnstile: f.turnstile || fb.turnstile,
validation: f.validation || fb.validation,
+6
View File
@@ -3,11 +3,17 @@
* `form` maps submitForm result codes to user-facing messages.
*/
export type FormNotificationTexts = {
/** Step-by-step forms: "Back" button. */
back: string
/** Shown when a required GDPR consent checkbox was left unchecked. */
consent: string
error: string
/** Step-by-step forms: "Next" button. */
next: string
notFound: string
rateLimited: string
/** Step-by-step forms: progress, with {current} and {total}. */
stepOf: string
success: string
turnstile: string
/** May contain the {field} placeholder — resolve with resolveValidationText. */
@@ -64,6 +64,21 @@ export function useTurnstile(): {
if (!ctx) {
throw new Error('useTurnstile must be used within <TurnstileProvider>')
}
return useTurnstileFrom(ctx)
}
const NO_PROVIDER: TurnstileContextValue = { setToken: () => {}, siteKey: null, token: null }
/**
* useTurnstile without the provider requirement: outside <TurnstileProvider>
* it reports `enabled: false` (no widget, no token) instead of throwing. For
* shared components (BuilderForm) that must not crash a page missing the provider.
*/
export function useOptionalTurnstile(): ReturnType<typeof useTurnstile> {
return useTurnstileFrom(use(TurnstileContext) ?? NO_PROVIDER)
}
function useTurnstileFrom(ctx: TurnstileContextValue): ReturnType<typeof useTurnstile> {
const { setToken, siteKey, token } = ctx
const reset = useCallback(() => setToken(null), [setToken])
+1 -1
View File
@@ -3,4 +3,4 @@
// the server-only verify never leaks into a browser bundle.
export { Turnstile } from './Turnstile.js'
export type { TurnstileProps } from './Turnstile.js'
export { TurnstileProvider, useTurnstile } from './TurnstileProvider.js'
export { TurnstileProvider, useOptionalTurnstile, useTurnstile } from './TurnstileProvider.js'
+133
View File
@@ -0,0 +1,133 @@
import { createElement, isValidElement } from 'react'
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, expect, test, vi } from 'vitest'
import type { BuilderField, BuilderFormDoc } from '../src/modules/forms/builderTypes.js'
import { BuilderForm } from '../src/modules/forms/BuilderForm.js'
import { autoCompleteFor, initialBuilderValues, splitSteps, stepOfField, validateBuilderFields } from '../src/modules/forms/builderLogic.js'
import { RenderForm } from '../src/modules/forms/RenderForm.js'
vi.mock('server-only', () => ({}))
const fields: BuilderField[] = [
{ name: 'name', blockType: 'text', label: 'Imię', required: true },
{ name: 'email', blockType: 'email', label: 'E-mail', required: true },
{ blockType: 'step', title: 'Szczegóły' },
{ name: 'budget', blockType: 'radio', label: 'Budżet', options: [{ label: 'Mały', value: 's' }, { label: 'Duży', value: 'l' }], required: true },
{ name: 'services', blockType: 'checkboxGroup', label: 'Usługi', maxSelected: 2, options: [{ value: 'www' }, { value: 'seo' }, { value: 'ads' }] },
{ blockType: 'message', message: { root: {} } },
{ name: 'deadline', blockType: 'date', label: 'Termin' },
{ name: 'consent', blockType: 'checkbox', label: 'Zgoda', required: true },
]
const texts = { back: 'Wstecz', next: 'Dalej', stepOf: 'Krok {current} z {total}', validation: 'Sprawdź pole {field}' }
describe('panel form logic', () => {
test('Step blocks split the form into screens; fields before the first Step are screen 1', () => {
const steps = splitSteps(fields)
expect(steps.map((s) => ({ names: s.fields.map(({ field }) => field.name ?? field.blockType), title: s.title }))).toEqual([
{ names: ['name', 'email'], title: undefined },
{ names: ['budget', 'services', 'message', 'deadline', 'consent'], title: 'Szczegóły' },
])
expect(stepOfField(steps, 'consent')).toBe(1)
})
test('no Steps → one screen; trailing or doubled Steps leave no empty screens', () => {
expect(splitSteps(fields.filter((f) => f.blockType !== 'step'))).toHaveLength(1)
expect(splitSteps([{ blockType: 'step' }, { blockType: 'step' }, { name: 'a', blockType: 'text' }, { blockType: 'step' }])).toHaveLength(1)
})
test('initial values by type', () => {
expect(initialBuilderValues(fields)).toEqual({ name: '', budget: '', consent: false, deadline: '', email: '', services: [] })
})
test('validation: required, e-mail, choice limits — only for the fields given (one step)', () => {
const values = { ...initialBuilderValues(fields), email: 'zły', services: ['www', 'seo', 'ads'] }
expect(validateBuilderFields(splitSteps(fields)[0].fields.map(({ field }) => field), values, texts)).toEqual({
name: 'Sprawdź pole Imię',
email: 'Sprawdź pole E-mail',
})
expect(validateBuilderFields(fields, values, texts)).toMatchObject({ budget: expect.any(String), consent: expect.any(String), services: expect.any(String) })
})
test('autofill hints', () => {
expect(autoCompleteFor({ name: 'phone', blockType: 'text' })).toBe('tel')
expect(autoCompleteFor({ name: 'x', blockType: 'email' })).toBe('email')
expect(autoCompleteFor({ name: 'message', blockType: 'text' })).toBeUndefined()
})
})
const form: BuilderFormDoc = { id: 7, fields, submitButtonLabel: 'Wyślij' }
const action = async () => ({ success: true })
describe('BuilderForm markup', () => {
test('unstyled by default: no class attributes, data hooks, honeypot, progress and Next on step 1', () => {
const html = renderToStaticMarkup(createElement(BuilderForm, { action, form, texts }))
expect(html).not.toMatch(/class="/)
expect(html).toContain('data-ipal="form"')
expect(html).toContain('name="company_url"')
expect(html).toContain('Krok 1 z 2')
expect(html).toContain('>Dalej</button>')
expect(html).not.toContain('Wyślij')
expect(html).toMatch(/<label for="ipal-f-7-name">Imię<\/label><input[^>]*id="ipal-f-7-name"[^>]*required=""/)
expect(html).toContain('autoComplete="email"')
})
test('classNames go where they belong; a single-screen form shows the submit label', () => {
const html = renderToStaticMarkup(
createElement(BuilderForm, {
action,
classNames: { fieldHalf: 'half', form: 'f', input: 'in', submit: 'btn' },
form: { ...form, fields: [{ name: 'a', blockType: 'text', label: 'A', width: 50 }] },
texts,
}),
)
expect(html).toContain('<form class="f"')
expect(html).toContain('class="half"')
expect(html).toContain('class="in"')
expect(html).toContain('<button class="btn" type="submit">Wyślij</button>')
expect(html).not.toContain('Krok')
})
test('radio and checkbox groups are fieldsets with a legend', () => {
const html = renderToStaticMarkup(
createElement(BuilderForm, { action, form: { ...form, fields: fields.slice(3, 5) }, texts }),
)
expect(html).toMatch(/<fieldset[^>]*id="ipal-f-7-budget"><legend>Budżet<\/legend>/)
expect(html).toMatch(/type="radio"[^>]*value="s"|value="s"[^>]*type="radio"/)
expect(html).toMatch(/<fieldset[^>]*id="ipal-f-7-services"><legend>Usługi<\/legend>/)
})
test('renderField replaces chosen fields and can reuse the default', () => {
const html = renderToStaticMarkup(
createElement(BuilderForm, {
action,
form: { ...form, fields: fields.slice(0, 2) },
renderField: ({ defaultRender, field }) => (field.name === 'email' ? createElement('div', { 'data-x': 'wrap' }, defaultRender()) : undefined),
texts,
}),
)
expect(html).toMatch(/<div data-x="wrap"><label for="ipal-f-7-email">/)
})
})
describe('RenderForm', () => {
test('passes only the public part of the form to the browser — never the Emails tab', () => {
const doc = {
...form,
confirmationType: 'redirect' as const,
emails: [{ emailTo: '[email protected]' }],
redirect: { type: 'custom' as const, url: 'javascript:alert(1)' },
}
const el = RenderForm({ action: async () => ({ message: '', success: true }), form: doc, locale: 'pl', texts })
expect(isValidElement(el)).toBe(true)
const props = (el as { props: { form: Record<string, unknown>; redirectHref: unknown } }).props
expect(JSON.stringify(props.form)).not.toContain('[email protected]')
expect(props.form).not.toHaveProperty('emails')
expect(props.redirectHref).toBeNull() // unsafe scheme dropped
})
test('a bare id or null renders nothing (no placeholder form)', () => {
expect(RenderForm({ action: async () => ({ message: '', success: true }), form: 5, locale: 'pl', texts })).toBeNull()
})
})
+111
View File
@@ -0,0 +1,111 @@
/**
* Docs ↔ code, both ways — so the instructions agents follow never drift from
* the package:
* 1. every name a doc imports from '@intecion/ipal-kit[/entry]' or '@/lib/content'
* exists there (a renamed/removed API breaks this test, not a client project);
* 2. every public runtime export is described somewhere in docs/ (an API
* nobody knows about gets re-implemented in projects).
*/
import { readdirSync, readFileSync, statSync } from 'node:fs'
import path from 'node:path'
import { describe, expect, test } from 'vitest'
const root = path.resolve(import.meta.dirname, '..')
const read = (p: string) => readFileSync(path.join(root, p), 'utf8')
const ENTRIES: Record<string, string> = {
'': 'src/index.ts',
'/admin': 'src/exports/admin.ts',
'/client': 'src/exports/client.ts',
'/env': 'src/exports/env.ts',
'/next/middleware': 'src/exports/next-middleware.ts',
'/rsc': 'src/exports/rsc.ts',
'/server': 'src/exports/server.ts',
}
/** Names an entry file exports — `export { a, b as c } from …`, `export type { … }`. */
function exportsOf(file: string): { runtime: Set<string>; types: Set<string> } {
const src = read(file).replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*$/gm, '')
const runtime = new Set<string>()
const types = new Set<string>()
for (const m of src.matchAll(/export\s+(type\s+)?\{([^}]*)\}/g)) {
for (const raw of m[2].split(',')) {
const item = raw.trim()
if (!item) {continue}
const isType = Boolean(m[1]) || item.startsWith('type ')
const name = item.replace(/^type\s+/, '').split(/\s+as\s+/).pop()!.trim()
;(isType ? types : runtime).add(name)
}
}
return { runtime, types }
}
/** Keys returned by createContentHelpers — what `@/lib/content` can re-export. */
function contentHelperNames(): Set<string> {
const src = read('src/modules/frontend/createContentHelpers.ts')
const block = src.slice(src.lastIndexOf(' return {'))
return new Set([...block.slice(0, block.indexOf('}')).matchAll(/^\s+(\w+),?$/gm)].map((m) => m[1]))
}
function docFiles(dir = 'docs'): string[] {
return readdirSync(path.join(root, dir)).flatMap((name) => {
const rel = path.join(dir, name)
return statSync(path.join(root, rel)).isDirectory() ? docFiles(rel) : /\.(?:md|ts|tsx|mjs)$/.test(name) ? [rel] : []
})
}
const docs = docFiles()
const exported = Object.fromEntries(Object.entries(ENTRIES).map(([sub, file]) => [sub, exportsOf(file)]))
describe('docs ↔ code', () => {
test('every name imported in the docs exists in the entry it is imported from', () => {
const helpers = contentHelperNames()
const missing: string[] = []
for (const file of docs) {
const text = read(file)
for (const m of text.matchAll(/import\s+(?:type\s+)?\{([^}]*)\}\s+from\s+'(@intecion\/ipal-kit(?:\/[a-z/-]+)?|@\/lib\/content)'/g)) {
const source = m[2]
for (const raw of m[1].split(',')) {
const name = raw.trim().replace(/^type\s+/, '').split(/\s+as\s+/)[0].trim()
if (!name || name.startsWith('…') || name === '...') {continue}
if (source === '@/lib/content') {
if (!helpers.has(name)) {missing.push(`${file}: ${name} from @/lib/content`)}
continue
}
const entry = exported[source.replace('@intecion/ipal-kit', '')]
if (!entry) {continue} // unknown subpath — exports.test.ts reports it
if (!entry.runtime.has(name) && !entry.types.has(name)) {missing.push(`${file}: ${name} from ${source}`)}
}
}
// `export { x as GET } from '@/lib/content'` in route examples
for (const m of text.matchAll(/export\s+\{([^}]*)\}\s+from\s+'@\/lib\/content'/g)) {
for (const raw of m[1].split(',')) {
const name = raw.trim().split(/\s+as\s+/)[0].trim()
if (name && !helpers.has(name)) {missing.push(`${file}: export ${name} from @/lib/content`)}
}
}
}
expect(missing).toEqual([])
})
test('every public runtime export is described in the docs', () => {
// Constants and building blocks the plugin wires itself — documented through what uses them.
const internal = new Set([
'A11Y_DEFAULT', 'ACCEPT_ALL_CONSENT', 'buildConsentLogCollection', 'buildConsentLogEndpoint', 'buildFormsPlugin', 'buildIndexNowHook',
'buildIntegrationStatusBanner', 'buildIntegrationStatusField', 'checkboxGroupBlock', 'CONSENT_LOG_SLUG', 'CONSENT_MAX_AGE',
'CONSENT_VERSION', 'DEFAULT_CONSENT', 'DEFAULT_SITEMAP_CREDIT', 'INDEXNOW_KEY_ENV', 'INDEXNOW_KEY_PATH',
'injectAutoFillMeta', 'IntecionCredit', 'IntegrationStatusBanner', 'MARKDOWN_PREFIX', 'matchAcceptLanguage',
'readConsentRecord', 'recordIntegrationStatus', 'REJECT_ALL_CONSENT', 'serializeA11y',
'serializeConsent', 'SITE_INTEGRATIONS_SLUG', 'SITE_SETTINGS_SLUG', 'SITEMAP_STYLE_PARAM', 'stepBlock', 'TestEmailButton',
])
const all = docs.map(read).join('\n')
const undocumented: string[] = []
for (const [sub, { runtime }] of Object.entries(exported)) {
for (const name of runtime) {
if (internal.has(name)) {continue}
if (!new RegExp(`\\b${name}\\b`).test(all)) {undocumented.push(`${name} (@intecion/ipal-kit${sub})`)}
}
}
expect(undocumented).toEqual([])
})
})
+35
View File
@@ -65,3 +65,38 @@ describe('form validation — injection and abuse', () => {
expect(await check({ count: ' 42 ' })).toMatchObject({ cleaned: { count: 42 }, ok: true })
})
})
describe('form validation — choice lists and dates', () => {
const { payload: p } = fakePayload({
forms: {
g: {
fields: [
{ name: 'services', blockType: 'checkboxGroup', maxSelected: 2, minSelected: 1, options: [{ value: 'www' }, { value: 'seo' }, { value: 'ads' }] },
{ name: 'size', blockType: 'radio', options: [{ value: 's' }, { value: 'l' }] },
{ name: 'deadline', blockType: 'date' },
{ blockType: 'step' },
],
},
},
})
const v = (data: Record<string, unknown>) => validateSubmission(p, 'g', data)
test('checkbox group: only configured values, deduplicated, within min/max', async () => {
expect(await v({ services: ['www', 'seo', 'www'] })).toMatchObject({ cleaned: { services: ['www', 'seo'] }, ok: true })
expect(await v({ services: ['www', '<b>x</b>'] })).toMatchObject({ field: 'services', kind: 'invalid_format' })
expect(await v({ services: ['www', 'seo', 'ads'] })).toMatchObject({ field: 'services', kind: 'invalid_format' })
expect(await v({ services: 'www' })).toMatchObject({ field: 'services', kind: 'invalid_format' })
expect(await v({ services: [{ $ne: 1 }] })).toMatchObject({ field: 'services', kind: 'invalid_format' })
})
test('radio accepts only its options; date must be a real date', async () => {
expect(await v({ deadline: '2026-11-30', size: 'l' })).toMatchObject({ cleaned: { deadline: '2026-11-30', size: 'l' }, ok: true })
expect(await v({ size: 'xl' })).toMatchObject({ field: 'size', kind: 'invalid_format' })
expect(await v({ deadline: 'jutro' })).toMatchObject({ field: 'deadline', kind: 'invalid_format' })
expect(await v({ deadline: '2026-13-45' })).toMatchObject({ field: 'deadline', kind: 'invalid_format' })
})
test('a Step block carries no value and is not an unknown field', async () => {
expect(await v({})).toMatchObject({ ok: true })
})
})
+81
View File
@@ -16,6 +16,7 @@ import { buildConsentLogEndpoint } from '../src/modules/consent/consentLog.js'
import { getCookieTable } from '../src/modules/consent/getConsentTexts.js'
import { submitForm } from '../src/modules/forms/submitForm.js'
import { createContentHelpers } from '../src/modules/frontend/createContentHelpers.js'
import { createPageRoute } from '../src/modules/frontend/pageRoute.js'
import { ipalKit } from '../src/plugin.js'
vi.mock('server-only', () => ({}))
@@ -117,6 +118,41 @@ describe('forms against a real Payload', () => {
expect(await send({ name: 'Ala', consent: true, role: 'admin' })).toMatchObject({ kind: 'unknown_fields' })
})
test('step-by-step form with a checkbox group, radio and date: built in the panel, stored readable', async () => {
const multi = await payload.create({
collection: 'forms' as never,
data: {
confirmationType: 'redirect',
fields: [
{ name: 'name', blockType: 'text', label: 'Imię', required: true },
{ blockType: 'step', title: 'Szczegóły' },
{ name: 'services', blockType: 'checkboxGroup', label: 'Usługi', options: [{ label: 'Strona', value: 'www' }, { label: 'SEO', value: 'seo' }], required: true },
{ name: 'size', blockType: 'radio', label: 'Wielkość', options: [{ label: 'Mała', value: 's' }, { label: 'Duża', value: 'l' }] },
{ name: 'deadline', blockType: 'date', label: 'Termin' },
],
redirect: { url: '/dziekujemy' },
title: 'Wycena',
} as never,
})
const result = await submitForm({
data: { name: 'Ala', deadline: '2026-12-01', services: ['www', 'seo'], size: 'l' },
formId: String(multi.id),
ip: '10.7.0.9',
payload,
})
expect(result).toMatchObject({ success: true })
if (!result.success) {return}
const stored = (await payload.findByID({ id: result.submissionId, collection: 'form-submissions' as never, depth: 0 })) as unknown as {
submissionData: { field: string; value: string }[]
}
expect(stored.submissionData.map(({ field, value }) => [field, value])).toEqual([
['name', 'Ala'],
['services', 'www, seo'],
['size', 'l'],
['deadline', '2026-12-01'],
])
})
test('REST/anonymous creation of submissions is closed (only submitForm writes)', async () => {
await expect(
payload.create({
@@ -178,6 +214,51 @@ describe('getPageJsonLd', () => {
})
})
describe('one-call helpers — layout, page, GEO routes', () => {
const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] } as const
const h = () => createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n, mcp: { serverName: 'acme-site' } })
test('getSiteShell: consent, analytics, Turnstile, form texts and site JSON-LD in one call', async () => {
await payload.updateGlobal({ slug: 'site-settings' as never, data: { siteName: 'Acme' } as never })
const shell = await h().getSiteShell('pl')
expect(shell.turnstileSiteKey).toBeNull()
expect(shell.consent.buttons.acceptAll).toEqual(expect.any(String))
expect(shell.formTexts).toMatchObject({ next: 'Next', stepOf: 'Step {current} of {total}' })
expect(shell.jsonLd.map((n) => n['@type'])).toEqual(['WebSite', 'Organization'])
expect(shell.jsonLd.every((n) => !('@context' in n))).toBe(true)
const custom = createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n, siteJsonLd: false })
expect((await custom.getSiteShell('pl')).jsonLd).toEqual([])
})
test('createPageRoute: renders a page with its JSON-LD, 404s an unknown slug', async () => {
await payload.create({ collection: 'pages' as never, data: { slug: 'uslugi', title: 'Usługi' } as never })
const notFound = vi.fn(() => {
throw new Error('NEXT_NOT_FOUND')
}) as unknown as () => never
const permanentRedirect = vi.fn() as unknown as (url: string) => never
const route = createPageRoute(h(), { blocks: {}, notFound, permanentRedirect })
const el = (await route.Page({ params: Promise.resolve({ slug: ['uslugi'] }) })) as { props: { children: unknown[] } }
expect(JSON.stringify(el.props.children[0])).toContain('Usługi')
await expect(route.Page({ params: Promise.resolve({ slug: ['nie-ma'] }) })).rejects.toThrow('NEXT_NOT_FOUND')
expect((await route.generateMetadata({ params: Promise.resolve({ slug: ['uslugi'] }) })).alternates?.canonical).toBe('https://acme.pl/uslugi')
})
test('route handlers answer without per-file configuration', async () => {
const helpers = h()
const llms = await helpers.llmsRoute()
expect(llms.status).toBe(200)
expect(await llms.text()).toContain('https://acme.pl/uslugi')
expect((await helpers.healthRoute()).status).toBe(200)
expect((await helpers.indexNowKeyRoute()).status).toBe(404) // no key configured
const mcp = await helpers.mcpPOST(
new Request('https://acme.pl/api/mcp', { body: JSON.stringify({ id: 1, jsonrpc: '2.0', method: 'initialize' }), headers: { 'content-type': 'application/json' }, method: 'POST' }),
)
expect(JSON.stringify(await mcp.json())).toContain('acme-site')
const md = await helpers.markdownRoute(new Request('https://acme.pl/md/uslugi'), { params: Promise.resolve({ slug: ['uslugi'], locale: 'pl' }) })
expect(md.status).toBe(200)
})
})
describe('consent log', () => {
const post = (body: unknown, ip = '10.6.0.1') =>
buildConsentLogEndpoint().handler({
+78
View File
@@ -0,0 +1,78 @@
import { describe, expect, test } from 'vitest'
import { buildSectionHeaderField, buildSectionSettingsField } from '../src/modules/blocks/sectionFields.js'
import { homeSlugFrom, resolveLink, resolveNav } from '../src/modules/links/resolveNav.js'
const config = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }, { code: 'en', label: 'EN' }] } as const
const opts = { config, homeSlug: 'start', locale: 'pl' }
const page = (slug: string) => ({ type: 'internal' as const, label: slug, page: { slug } })
describe('resolveLink', () => {
test('internal page → next/link, no target', () => {
expect(resolveLink(page('kontakt'), opts)).toEqual({ href: '/pl/kontakt', internal: true, label: 'kontakt', newTab: false, targetProps: {} })
})
test('files always open in a new tab with rel; appearance is passed through', () => {
expect(resolveLink({ type: 'file', appearance: 'primary', file: { url: '/media/cennik.pdf' }, label: 'Cennik' }, opts)).toMatchObject({
appearance: 'primary',
href: '/media/cennik.pdf',
internal: false,
targetProps: { rel: 'noopener noreferrer', target: '_blank' },
})
})
test('nowhere → null: unsafe URL, missing page, empty link', () => {
expect(resolveLink({ type: 'external', url: 'javascript:alert(1)' }, opts)).toBeNull()
expect(resolveLink({ type: 'internal', page: 5 }, opts)).toBeNull()
expect(resolveLink(null, opts)).toBeNull()
})
test('the homepage collapses to the locale root', () => {
expect(resolveLink(page('start'), opts)?.href).toBe('/pl')
})
})
describe('resolveNav', () => {
test('nested items resolved; dead or unlabeled items dropped', () => {
const items = [
{ link: page('oferta'), subItems: [{ link: page('www') }, { link: { type: 'internal', label: 'x', page: null } }] },
{ link: { type: 'external', url: 'https://x.pl' } }, // no label
{ link: page('kontakt') },
]
const nav = resolveNav(items, opts)
expect(nav.map((i) => [i.href, i.children.map((c) => c.href)])).toEqual([
['/pl/oferta', ['/pl/www']],
['/pl/kontakt', []],
])
})
test('custom item shape and junk input', () => {
expect(resolveNav([{ children: [{ to: page('a') }], to: page('b') }], { ...opts, childrenField: 'children', linkField: 'to' })[0].children[0].href).toBe('/pl/a')
expect(resolveNav(null, opts)).toEqual([])
expect(resolveNav('x', opts)).toEqual([])
})
test('homeSlugFrom reads a populated homepage only', () => {
expect(homeSlugFrom({ homepage: { slug: 'start' } })).toBe('start')
expect(homeSlugFrom({ homepage: 3 })).toBeUndefined()
expect(homeSlugFrom(null)).toBeUndefined()
})
})
describe('section fields', () => {
test('defaults match the documented shape (types SectionHeaderData / SectionSettings)', () => {
const header = buildSectionHeaderField()
expect(header).toMatchObject({ name: 'header', interfaceName: 'SectionHeaderData' })
expect(header.fields.map((f) => ('name' in f ? f.name : ''))).toEqual(['eyebrow', 'heading', 'intro'])
const settings = buildSectionSettingsField()
expect(settings).toMatchObject({ name: 'settings', admin: { position: 'sidebar' }, interfaceName: 'SectionSettings' })
expect(settings.fields.map((f) => ('name' in f ? f.name : ''))).toEqual(['anchor', 'background'])
})
test('the project decides: own backgrounds, no anchor, extra fields', () => {
const s = buildSectionSettingsField({ anchor: false, backgrounds: [{ label: 'Brand', value: 'brand' }], fields: [{ name: 'spacing', type: 'text' }] })
expect(s.fields.map((f) => ('name' in f ? f.name : ''))).toEqual(['background', 'spacing'])
expect(s.fields[0]).toMatchObject({ defaultValue: 'brand' })
expect(buildSectionSettingsField({ backgrounds: false }).fields.map((f) => ('name' in f ? f.name : ''))).toEqual(['anchor'])
})
})