Compare commits

...
14 Commits
Author SHA1 Message Date
radoslaw.smolinski 800ba30200 1.9.1
CI / check (push) Canceled after 0s
2026-10-16 10:56:18 +02:00
radoslaw.smolinskiandClaude Opus 5.5 0c5c6ac3e3 Merge 1.9.1: SEO/GEO, consent, security, forms seed, media, fluid
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 10:56:17 +02:00
radoslaw.smolinskiandClaude Opus 5.5 e301ff3d00 Release as 1.9.1 instead of 1.10.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 10:56:16 +02:00
radoslaw.smolinskiandClaude Opus 5.5 3986e70e5f Dev sandbox: enable consent log
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 03:27:13 +02:00
radoslaw.smolinskiandClaude Opus 5.5 de929422bb Docs for 1.10: mandatory set (18 items), setup skill, reference code, module docs, changelog
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 03:25:58 +02:00
radoslaw.smolinskiandClaude Opus 5.5 f52fbe6b12 Audits: performance, responsive and new mandatory items; seo-check content checks
ipal-audit: <video> outside Media, priority outside the hero, <Media> without
sizes, raw YouTube iframes, 100vh/h-screen, fixed pixel sizes, page JSON-LD,
upload sandbox headers, images preset, missing form seeds; accepts
createMarkdownRoute / createSubmitAction.
ipal-seo-check: exactly one h1, heading jumps, img alt and dimensions, LCP
priority, og:image, thin pages, internal links, X-Robots-Tag noindex left on
in production. Verified on bad and good fixtures.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 03:22:55 +02:00
radoslaw.smolinskiandClaude Opus 5.5 69309b09e3 Fluid scaling to 1920px and height-aware variables; speed and responsive guidelines
- fluid-wide.css: the fluid.css variables stretched over 360→1920px (export
  @intecion/ipal-kit/fluid-wide.css); fluid.css values unchanged.
- New variables in both (unused until a project opts in): --ipal-measure,
  --ipal-container(-wide), --ipal-hero-min-h (svh), --ipal-fs-display-fit,
  --ipal-fs-h1-fit, --ipal-space-section-fit — keep the hero CTA above the fold
  on 1366×768. Verified in Chromium at 360…1920 widths.
- AGENT.md §6.11a (scaling, viewport test list incl. 13–15" laptops and 125/150 %
  zoom) and §6.11b (Core Web Vitals table: LCP image, sizes, placeholders, video
  modes, YouTube facade, images preset, fonts).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 03:21:38 +02:00
radoslaw.smolinskiandClaude Opus 5.5 55fc27a13f Media performance tools: image/video props, upload placeholders, images preset, YouTube facade
Headless helpers for the project's own <Media> (look stays in the project):
- mediaImageProps: dimensions from the doc (no CLS), lazy by default, LCP image
  gets preload + fetchPriority=high + eager (Next 16 replaced 'priority'),
  focal point → object-position, blur placeholder + dominant colour.
- MEDIA_SIZES suggestions for 'sizes' (any string still works).
- videoProps: 'background' (muted loop, respects reduced motion) or 'player'
  (controls, preload=none, poster).
- buildMediaPlaceholderHook/Field: tiny WebP blur + dominant colour at upload
  via the configured sharp (no new dependency).
- buildImagesConfig: AVIF/WebP, R2 remotePatterns, 31-day cache.
- <YouTubeEmbed> (/client): poster + button, youtube-nocookie iframe on click.
- buildCsp youtube allows the i.ytimg.com poster. kod-sekcji Media template
  uses the helpers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 03:19:38 +02:00
radoslaw.smolinskiandClaude Opus 5.5 f7466cf77f noindex tooling, content/noindex/component/testing guidelines for agents
- IPAL_NOINDEX=1: whole-site noindex for staging (robots Disallow /, robots
  meta noindex,nofollow, X-Robots-Tag via buildSecurityHeaders).
- Markdown mirrors and llms files: X-Robots-Tag noindex; Markdown adds a
  Link rel=canonical to the HTML page.
- buildNoindexField refuses noindex on the homepage and archive pages.
- AGENT.md §0c: writing pages for Google and AI (structure, answer-first,
  facts, E-E-A-T, entity consistency, sameAs, aiSummary, meta) and a
  when-to-noindex table (legal pages stay indexed by default; drafts instead
  of noindexed pages; staging via env).
- AGENT.md §6.0: ten component rules (small, Button styled once, buttons as
  '+ Add Button' array, variants, panel clarity); audit warns on buttons
  styled inside sections.
- AGENT.md §8a + smoke.spec.template.ts: what to test in a client project;
  PROGRAMISTA §8.1a: how the plugin itself is tested.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 03:13:44 +02:00
radoslaw.smolinskiandClaude Opus 5.5 8e2dd28b83 Form seed template: fields, confirmation, company notification and sender confirmation in every language
The ipal-form skill now requires seeding each form (scripts/seed-form-*.ts):
idempotent, reads the notification inbox from the panel and stops without
one, adds both e-mails ({{email}} is safe since submitForm accepts exactly one
address). Verified on the dev sandbox in pl + en. Dev sandbox enables forms.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 03:08:56 +02:00
radoslaw.smolinskiandClaude Opus 5.5 9e49856611 Security review: drafts no longer public, submissions staff-only, safe links, upload sandbox
- Fix: resolveRoute served never-published drafts by URL (Payload's find
  returns them with _status 'draft') — also via Markdown, MCP get_page and
  metadata. Drafts are dropped on every branch; `draft: true` for previews.
- Fix: getArchiveEntries listed drafts in archive pages despite its comment;
  `_status: published` is added automatically when the collection has drafts.
- form-submissions readable only by editor+ (form-builder default: any account
  of the admin collection, incl. plain users from an open sign-up); delete admin.
- Forms stay public for rendering, but the Emails tab (recipients) is hidden
  from anonymous REST reads.
- safeHref: CMS links only http(s), mailto, tel, sms, #, / — javascript:, data:
  and control-character tricks are dropped in resolveLinkHref.
- Analytics IDs validated in the panel and before reaching the browser.
- buildUploadSecurityHeaders: sandbox CSP for /api/<upload>/file/* so an
  uploaded SVG can't run script on the site's origin.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 03:06:26 +02:00
radoslaw.smolinskiandClaude Opus 5.5 ebf70d49bd Consent: withdrawal clears tool cookies, policy version, consent log, cookie scan; form input hardening
Consent (GDPR)
- Withdrawing consent now deletes GA/Meta/Ads/Clarity/LinkedIn/TikTok/Hotjar
  cookies (prefix patterns) on the host AND parent domains — previously only
  the locale cookie was removed and _ga & co. stayed. Projects extend the list
  via <ConsentProvider cookieMap>, merged with the defaults.
- Cookie Settings → Policy version: raising it asks every visitor again.
- <CookieBanner equalChoice>: Reject styled like Accept (UODO/EDPB), opt-in.
- Opt-in consent log (ipalKit({ consentLog: true }) + logEndpoint): random id,
  choices, version, time — no IP/UA; admin-only collection, retention purge.
- Cookie Settings → Cookies + getCookieTable + unstyled <CookieTable> (/rsc).
- Consent cookie gets Secure on HTTPS; consent id stored with the decision.
- ipal-consent-check: cookie-scan.mjs (before/after consent, known-tool
  catalog PL/EN, flags non-necessary cookies set before consent) and
  import-cookies.ts into the panel (idempotent, keeps editor edits).

Forms
- Server-side type checks per field from the panel definition: email = one
  address (blocks "a@x, b@y" recipient injection into {{email}} confirmations
  and CR/LF header injection), select/radio only configured options, numbers,
  booleans; objects/arrays rejected; control and bidi characters stripped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 02:31:58 +02:00
radoslaw.smolinskiandClaude Opus 5.5 c9a50abc33 SEO/GEO tools and project requests: site index, IndexNow, page JSON-LD, fixes
GEO / SEO
- collectSiteIndex: one list of public docs per locale (pages + archive
  entries) on sitemap rules; llms.txt/llms-full and MCP list_pages now include
  blog/content entries and every language. Fixes hard-coded "## Strony" heading
  and homepage not collapsing to the locale root in llms.txt.
- Markdown frontmatter: canonical url + updated date.
- Metadata: X/Twitter card, OG image width/height/alt, og:type article with
  published/modified times for entries.
- Fix: Site Settings "defaultShareImage" was never used — now the OG fallback.
- getPageJsonLd (createContentHelpers): WebPage/CollectionPage/BlogPosting,
  BreadcrumbList from the real route, FAQPage via a project mapper.
- IndexNow (opt-in ipalKit({ indexNow: true })): submit published URLs in all
  languages, key generated in Site Integrations or INDEXNOW_KEY, key route.
- sameAs profiles in Site Settings + sameAsUrls(); sitemap <image:image>.

From project reports
- Fix: package exports were missing ./env and ./fluid.css although the docs
  import them (TS2307); regression test checks every documented subpath.
- Fix: plugins run before Payload adds its default users collection, so roles
  and 2FA had nothing to attach to — ipalKit injects an auth collection when
  the project has none (project's own one wins). Audit no longer errors on it.
- createMarkdownRoute, createSubmitAction (/server, headers injected).
- formatOpeningHours (PL/EN/DE text → schema.org), used by
  buildLocalBusinessJsonLd, which also takes a schema.org `type`.
- buildNavigationJsonLd straight from the header global.
- buildCsp googleMaps: full Maps JS API domain set; values de-duplicated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 02:19:08 +02:00
radoslaw.smolinskiandClaude Opus 5.5 9e40d74bb3 Normalize bin path (npm pkg fix) to silence publish warning
CI / check (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 01:27:21 +02:00
96 changed files with 4308 additions and 304 deletions
+397
View File
@@ -71,6 +71,8 @@ export interface Config {
pages: Page;
posts: Post;
media: Media;
forms: Form;
'form-submissions': FormSubmission;
'payload-kv': PayloadKv;
'payload-locked-documents': PayloadLockedDocument;
'payload-preferences': PayloadPreference;
@@ -82,6 +84,8 @@ export interface Config {
pages: PagesSelect<false> | PagesSelect<true>;
posts: PostsSelect<false> | PostsSelect<true>;
media: MediaSelect<false> | MediaSelect<true>;
forms: FormsSelect<false> | FormsSelect<true>;
'form-submissions': FormSubmissionsSelect<false> | FormSubmissionsSelect<true>;
'payload-kv': PayloadKvSelect<false> | PayloadKvSelect<true>;
'payload-locked-documents': PayloadLockedDocumentsSelect<false> | PayloadLockedDocumentsSelect<true>;
'payload-preferences': PayloadPreferencesSelect<false> | PayloadPreferencesSelect<true>;
@@ -223,6 +227,188 @@ export interface Post {
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "forms".
*/
export interface Form {
id: number;
title: string;
fields?:
| (
| {
name: string;
label?: string | null;
width?: number | null;
required?: boolean | null;
defaultValue?: boolean | null;
id?: string | null;
blockName?: string | null;
blockType: 'checkbox';
}
| {
name: string;
label?: string | null;
width?: number | null;
required?: boolean | null;
id?: string | null;
blockName?: string | null;
blockType: 'country';
}
| {
name: string;
label?: string | null;
width?: number | null;
required?: boolean | null;
id?: string | null;
blockName?: string | null;
blockType: 'email';
}
| {
message?: {
root: {
type: string;
children: {
type: any;
version: number;
[k: string]: unknown;
}[];
direction: ('ltr' | 'rtl') | null;
format: 'left' | 'start' | 'center' | 'right' | 'end' | 'justify' | '';
indent: number;
version: number;
};
[k: string]: unknown;
} | null;
id?: string | null;
blockName?: string | null;
blockType: 'message';
}
| {
name: string;
label?: string | null;
width?: number | null;
defaultValue?: number | null;
required?: boolean | null;
id?: string | null;
blockName?: string | null;
blockType: 'number';
}
| {
name: string;
label?: string | null;
width?: number | null;
defaultValue?: string | null;
placeholder?: string | null;
options?:
| {
label: string;
value: string;
id?: string | null;
}[]
| null;
required?: boolean | null;
id?: string | null;
blockName?: string | null;
blockType: 'select';
}
| {
name: string;
label?: string | null;
width?: number | null;
required?: boolean | null;
id?: string | null;
blockName?: string | null;
blockType: 'state';
}
| {
name: string;
label?: string | null;
width?: number | null;
defaultValue?: string | null;
required?: boolean | null;
id?: string | null;
blockName?: string | null;
blockType: 'text';
}
| {
name: string;
label?: string | null;
width?: number | null;
defaultValue?: string | null;
required?: boolean | null;
id?: string | null;
blockName?: string | null;
blockType: 'textarea';
}
)[]
| null;
submitButtonLabel?: string | null;
confirmationType?: ('message' | 'redirect') | null;
confirmationMessage?: {
root: {
type: string;
children: {
type: any;
version: number;
[k: string]: unknown;
}[];
direction: ('ltr' | 'rtl') | null;
format: 'left' | 'start' | 'center' | 'right' | 'end' | 'justify' | '';
indent: number;
version: number;
};
[k: string]: unknown;
} | null;
redirect?: {
url: string;
};
emails?:
| {
emailTo?: string | null;
cc?: string | null;
bcc?: string | null;
replyTo?: string | null;
emailFrom?: string | null;
subject: string;
message?: {
root: {
type: string;
children: {
type: any;
version: number;
[k: string]: unknown;
}[];
direction: ('ltr' | 'rtl') | null;
format: 'left' | 'start' | 'center' | 'right' | 'end' | 'justify' | '';
indent: number;
version: number;
};
[k: string]: unknown;
} | null;
id?: string | null;
}[]
| null;
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "form-submissions".
*/
export interface FormSubmission {
id: number;
form: number | Form;
submissionData?:
| {
field: string;
value: string;
id?: string | null;
}[]
| null;
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "payload-kv".
@@ -262,6 +448,14 @@ export interface PayloadLockedDocument {
| ({
relationTo: 'media';
value: number | Media;
} | null)
| ({
relationTo: 'forms';
value: number | Form;
} | null)
| ({
relationTo: 'form-submissions';
value: number | FormSubmission;
} | null);
globalSlug?: string | null;
user: {
@@ -380,6 +574,155 @@ export interface MediaSelect<T extends boolean = true> {
focalX?: T;
focalY?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "forms_select".
*/
export interface FormsSelect<T extends boolean = true> {
title?: T;
fields?:
| T
| {
checkbox?:
| T
| {
name?: T;
label?: T;
width?: T;
required?: T;
defaultValue?: T;
id?: T;
blockName?: T;
};
country?:
| T
| {
name?: T;
label?: T;
width?: T;
required?: T;
id?: T;
blockName?: T;
};
email?:
| T
| {
name?: T;
label?: T;
width?: T;
required?: T;
id?: T;
blockName?: T;
};
message?:
| T
| {
message?: T;
id?: T;
blockName?: T;
};
number?:
| T
| {
name?: T;
label?: T;
width?: T;
defaultValue?: T;
required?: T;
id?: T;
blockName?: T;
};
select?:
| T
| {
name?: T;
label?: T;
width?: T;
defaultValue?: T;
placeholder?: T;
options?:
| T
| {
label?: T;
value?: T;
id?: T;
};
required?: T;
id?: T;
blockName?: T;
};
state?:
| T
| {
name?: T;
label?: T;
width?: T;
required?: T;
id?: T;
blockName?: T;
};
text?:
| T
| {
name?: T;
label?: T;
width?: T;
defaultValue?: T;
required?: T;
id?: T;
blockName?: T;
};
textarea?:
| T
| {
name?: T;
label?: T;
width?: T;
defaultValue?: T;
required?: T;
id?: T;
blockName?: T;
};
};
submitButtonLabel?: T;
confirmationType?: T;
confirmationMessage?: T;
redirect?:
| T
| {
url?: T;
};
emails?:
| T
| {
emailTo?: T;
cc?: T;
bcc?: T;
replyTo?: T;
emailFrom?: T;
subject?: T;
message?: T;
id?: T;
};
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "form-submissions_select".
*/
export interface FormSubmissionsSelect<T extends boolean = true> {
form?: T;
submissionData?:
| T
| {
field?: T;
value?: T;
id?: T;
};
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "payload-kv_select".
@@ -450,6 +793,15 @@ export interface SiteSetting {
* Fallback Open Graph image when a page has none.
*/
defaultShareImage?: (number | null) | Media;
/**
* Official profiles of this business (Google Business Profile, LinkedIn, Facebook, Wikipedia…). Tells search engines and AI which entity the site belongs to.
*/
sameAs?:
| {
url: string;
id?: string | null;
}[]
| null;
/**
* Square icon, PNG or SVG, min. 48×48px (Google requires this to show it in search). Rendered via buildIconsMetadata.
*/
@@ -539,6 +891,10 @@ export interface SiteIntegration {
since?: string | null;
checkedAt?: string | null;
};
/**
* Key that proves this site owns its URLs to IndexNow (Bing, ChatGPT Search). Generated automatically — change only to rotate it.
*/
indexNowKey?: string | null;
updatedAt?: string | null;
createdAt?: string | null;
}
@@ -548,6 +904,10 @@ export interface SiteIntegration {
*/
export interface CookieSetting {
id: number;
/**
* Raise by 1 when you add a tool or change the cookie policy — every visitor is asked for consent again.
*/
policyVersion: number;
/**
* Main consent message shown in the banner.
*/
@@ -581,6 +941,25 @@ export interface CookieSetting {
id?: string | null;
}[]
| null;
/**
* Cookies the site uses — shown on the cookie policy page (<CookieTable>). Fill it from a scan: ipal-consent-check → cookie-scan.
*/
cookies?:
| {
name: string;
/**
* e.g. Google, this site
*/
provider?: string | null;
category: 'necessary' | 'functional' | 'analytics' | 'marketing';
purpose?: string | null;
/**
* e.g. "2 years", "session"
*/
duration?: string | null;
id?: string | null;
}[]
| null;
updatedAt?: string | null;
createdAt?: string | null;
}
@@ -622,6 +1001,12 @@ export interface SiteSettingsSelect<T extends boolean = true> {
titleSeparator?: T;
logo?: T;
defaultShareImage?: T;
sameAs?:
| T
| {
url?: T;
id?: T;
};
favicon?: T;
defaultTheme?: T;
allowThemeToggle?: T;
@@ -667,6 +1052,7 @@ export interface SiteIntegrationsSelect<T extends boolean = true> {
since?: T;
checkedAt?: T;
};
indexNowKey?: T;
updatedAt?: T;
createdAt?: T;
globalType?: T;
@@ -676,6 +1062,7 @@ export interface SiteIntegrationsSelect<T extends boolean = true> {
* via the `definition` "cookie-settings_select".
*/
export interface CookieSettingsSelect<T extends boolean = true> {
policyVersion?: T;
message?: T;
settingsTitle?: T;
privacyLinkLabel?: T;
@@ -696,6 +1083,16 @@ export interface CookieSettingsSelect<T extends boolean = true> {
description?: T;
id?: T;
};
cookies?:
| T
| {
name?: T;
provider?: T;
category?: T;
purpose?: T;
duration?: T;
id?: T;
};
updatedAt?: T;
createdAt?: T;
globalType?: T;
+2
View File
@@ -63,6 +63,8 @@ export default buildConfig({
{ code: 'en', label: 'English' },
],
},
consentLog: true,
forms: {},
seo: { collections: ['posts', 'pages'] },
// 2FA is enforced by default; the dev sandbox opts out so it boots without an authenticator.
twoFactor: false,
+37
View File
@@ -3,6 +3,43 @@
Zmiany ważne dla projektów na ipal-kit. Jak przejść na nową wersję: skill
**ipal-upgrade** i [PROGRAMISTA.md §6](./dev/PROGRAMISTA.md).
## 1.9.1
### Wymaga zmian w projekcie
- **Bezpieczeństwo — drafty:** nigdy nieopublikowane strony i wpisy były dostępne pod swoim adresem
(oraz w Markdown, MCP, na listach archiwum). Teraz nie są. Podgląd redaktora: `draft: true`
w `resolveRoute` / `getArchiveEntries` w trybie `draftMode()`.
- **Zgłoszenia formularzy** czytają tylko role `editor`/`admin` (wcześniej każde konto panelu);
adresy odbiorców (zakładka Emails) zniknęły z publicznego `GET /api/forms`.
- **Formularze:** pole `email` przyjmuje dokładnie jeden adres, select tylko opcje z panelu, typy
sprawdzane po stronie serwera (`kind: 'invalid_format'`). Formularz wysyłający dane w innym kształcie
zostanie odrzucony.
- **Wycofanie zgody kasuje ciasteczka narzędzi** (`_ga*`, `_fbp`, `_gcl_*`, Clarity, LinkedIn…), także
na domenie nadrzędnej.
- **Nowe pola w globalach** (Postgres: `pnpm payload migrate:create`): Site Settings → sameAs; Cookie
Settings → Policy version, Cookies; Site Integrations → IndexNow.
- **Eksporty:** `@intecion/ipal-kit/env` i `/fluid.css` w końcu działają (były w docs, nie w paczce).
- **`users`:** plugin dodaje kolekcję auth, gdy projekt jej nie ma — usuń obejścia z `payload.config`.
- Komplet AGENT.md §0b rozszerzony do 18 pozycji (`ipal-audit` zgłosi braki).
### Nowe
- SEO/GEO: `getPageJsonLd`, `buildNavigationJsonLd`, `formatOpeningHours` + `type` w
`buildLocalBusinessJsonLd`, `sameAsUrls`, IndexNow (`indexNow: true`, `createIndexNowKeyRoute`),
`collectSiteIndex` (blog i wszystkie języki w llms.txt i MCP), URL + data w frontmatterze Markdown,
karta X/Twitter, `og:type=article`, obrazy w sitemapie, domyślny obraz udostępniania działa.
- Gotowe trasy i akcje: `createMarkdownRoute`, `createSubmitAction`, `createProxy({ markdown: true })`.
- Zgoda: wersja polityki z panelu, `equalChoice`, rejestr zgód (`consentLog`), tabela ciasteczek
(`getCookieTable`, `<CookieTable>`), skaner `cookie-scan` + import do panelu.
- noindex: `IPAL_NOINDEX=1` dla stagingu, Markdown/llms z `X-Robots-Tag: noindex` i canonical,
blokada noindex na stronie głównej i archiwach.
- Media: `mediaImageProps`, `videoProps`, `MEDIA_SIZES`, placeholdery przy uploadzie,
`buildImagesConfig`, `<YouTubeEmbed>`, `buildUploadSecurityHeaders`.
- Skalowanie: `fluid-wide.css` (do 1920 px) i zmienne zależne od wysokości ekranu.
- `safeHref` (linki z CMS bez `javascript:`), walidacja ID analityki, pełny preset CSP Google Maps.
- Agent: AGENT.md §0c (treść pod Google i AI, kiedy noindex), §6.0 (zasady komponentu), §6.11a/b
(skalowanie, Core Web Vitals), §8a (testy) + szablon `smoke.spec.ts`; seed formularza; nowe
kontrole w `ipal-audit` i `ipal-seo-check`.
## 1.9.0
### Wymaga zmian w projekcie
+154 -12
View File
@@ -23,7 +23,7 @@
3. **Next 16 = `proxy.ts`.** NIGDY `middleware.ts`.
4. **Bez jawnego `<head>`, z ISR i `generateStaticParams`** — inaczej metadata
ląduje w `<body>` i SEO pada.
5. **Minimum kolekcji.** Users są wbudowane, dane firmy/nawigacja to globale,
5. **Minimum kolekcji.** Users wstrzykuje ipalKit, dane firmy/nawigacja to globale,
FAQ/hero to bloki.
6. **Sekcja = kompozycja prymitywów.** `buildLinksField()` + `<CMSLink>`, upload +
`<Media>`, `<Section>` + `<SectionHeader>`. Zero pól `ctaLabel`/`pdfUrl`.
@@ -55,19 +55,21 @@ strona), **P** = test w panelu. Pełny kod: PROGRAMISTA.md §2.
| 1 | i18n + routing | `src/proxy.ts`, `[locale]/[[...slug]]/page.tsx` z ISR + `generateStaticParams`, `not-found.tsx` | `createProxy`, `createContentHelpers`, `resolveRoute`, `resolveRedirect` | 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 | `<JsonLdGraph>` w `[locale]/layout.tsx`: `WebSite` + `Organization` (lub `LocalBusiness` dla firmy lokalnej) z danych z panelu; `Breadcrumb` na podstronach; `FAQPage` przy bloku FAQ | `build*JsonLd`, `JsonLdGraph` (`/rsc`) | 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`; `createContentHelpers({ markdownAlternate: true })` (link w `<head>`); `createProxy(…, { NextResponse, markdown: true })` (bez tego `/md/…` dostaje redirect na język) | `createMarkdownRenderer`, `markdownResponse`, `markdownAlternate`, `createProxy({ markdown })` | 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 | robots **wpuszcza** boty AI (domyślne `aiBots: 'allow'`); `'block-training'` / `'disallow'` tylko z decyzji klienta | `buildRobots` | S |
| 9 | **Media / R2** | `Media` z `normalizeFilenameHook` + `buildOptimizeUploadHook`; **zawsze** `buildR2Storage(['media'], { s3Storage })` w `payload.config.ts` + `@payloadcms/storage-s3` w zależnościach; `R2_*` w `.env.example`; `<MediaPreconnect/>` w layoutcie | `buildR2Storage`, `normalizeFilenameHook`, `MediaPreconnect` | A |
| 10 | **Formularze** | formularze w panelu (kolekcja Forms); jeden `FormRenderer` + jedna akcja `sendForm` → `submitForm`; `forms: {…}` w `ipalKit`; `email: mailAdapter()` | `submitForm`, `useForm`, `isHoneypotTripped`, `mailAdapter` | A, P |
| 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 |
| 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`, `CookieBanner`, `CookieButton`, `Analytics` w layoutcie; ID narzędzi w panelu | consent.md, analytics.md | A, `ipal-consent-check` |
| 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` |
| 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 }))` | `createHealthRoute`, `assertEnv`, `ipalEnvRules` | 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 |
| 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 |
| 18 | **Skalowanie** | `fluid.css` / `fluid-wide.css`, hero na `--ipal-hero-min-h`, lista ekranów §6.11a (w tym 1366×768) | — | A, przeglądarka |
**Turnstile działa sam:** oba klucze w panelu (lub env) → widget się pokazuje, a
`submitForm` **wymaga** tokenu; brak kluczy → widgetu nie ma, formularz działa.
@@ -96,7 +98,63 @@ W `AGENTS.md` projektu, w „Ustaleniach”, jedna linia z kluczami pozycji i po
ipal-audit-skip: mcp, llms-full — klient nie chce udostępniać treści agentom AI (mail 2026-03-02)
```
Klucze: `llms`, `llms-full`, `markdown`, `mcp`, `jsonld`, `r2`, `turnstile`,
`analytics`, `csp`, `twofactor`. Bez tej linii brak pozycji to błąd.
`analytics`, `csp`, `twofactor`, `aibots`, `forms-seed`. Bez tej linii brak pozycji to błąd.
---
## 0c. TREŚĆ POD GOOGLE I AI (SEO + GEO) — jak piszesz i układasz strony
Technika z §0b sprawia, że strona *może* być dobrze widoczna. To, czy Google ją
wypozycjonuje, a asystent AI zacytuje, zależy od treści. Wpisując treść z briefu do
panelu (seed, faza 6 w ipal-site), stosujesz poniższe — nie wymyślając faktów.
### Struktura każdej strony
- **Jedno `h1`** (nagłówek hero/strony), potem `h2` sekcji, `h3` w środku — bez przeskoków
poziomów. `SectionHeader` dostaje `as="h1"` tylko w pierwszej sekcji.
- **Najpierw odpowiedź.** Pierwsze 1–2 zdania sekcji odpowiadają wprost na jej nagłówek
(„Ile kosztuje…?” → „Od 1500 zł netto za…”). AI cytuje dokładnie takie zdania.
- **Nagłówki = pytania i frazy klientów**, nie hasła („Jak przebiega montaż?”, nie „Proces”).
- **Fakty zamiast ogólników:** liczby, zakres, obszar działania, czas realizacji, ceny „od” —
tylko z briefu; brak → `[DO UZUPEŁNIENIA]`. Zero „najlepsza jakość”, „profesjonalne podejście”.
- **Treść w HTML, nie w obrazach.** Kluczowa informacja nie może być tylko na grafice ani w
wideo. `alt` opisuje, co jest na obrazie (nie „zdjęcie1”, nie słowa kluczowe).
- **Każda strona linkuje dalej:** usługa → powiązane usługi + kontakt; wpis → usługa, której
dotyczy. Żadna strona bez linków wewnętrznych (CMSLink).
- **FAQ z prawdziwych pytań** z briefu → blok FAQ + `getPageJsonLd(…, { faq })` (FAQPage).
Pytania i odpowiedzi w JSON-LD = widoczne na stronie, słowo w słowo.
- **Długość:** strona usługi ≥ ~300 słów sensownej treści; krótsza = „cienka” — połącz z inną
albo poproś o materiał.
### Wiarygodność (E-E-A-T) i encja firmy
- Strona **O nas** z ludźmi, doświadczeniem, certyfikatami (z briefu); wpisy z autorem i datą.
- **Te same dane firmy wszędzie** (nazwa, adres, telefon): stopka, kontakt, JSON-LD
(`LocalBusiness`/`Organization`), wizytówka Google. Jeden global Company jako źródło.
- **Site Settings → sameAs:** profile firmy (Google Business Profile, LinkedIn, Facebook…).
- **Site Settings → opis strony** (2–3 zdania: kto, co, gdzie) — zasila llms.txt, MCP i meta.
- **`aiSummary`** ważnych stron: popraw auto-fill, gdy streszczenie jest słabe (1–3 zdania, fakty).
### Meta w zakładce SEO
Tytuł ≤ 60 znaków, unikalny, fraza na początku; opis ≤ 155 znaków, z konkretem i zachętą;
obraz udostępniania (1200×630) na stronach z ofertą — reszta dziedziczy domyślny z Site Settings.
### noindex — kiedy TAK, kiedy NIE
| Strona | noindex? |
|---|---|
| „Dziękujemy” po formularzu, strona potwierdzenia | **tak** |
| wyniki wewnętrznej wyszukiwarki, strony filtrów/parametrów | **tak** (+ `disallowParams` w robots) |
| strona testowa, robocza, landing tylko dla kampanii płatnej | **tak** |
| staging, preview, kopia testowa całej strony | **`IPAL_NOINDEX=1` w env tego środowiska** — nie checkbox |
| strona główna, archiwa (blog, realizacje) | **nigdy** — panel zablokuje zapis |
| usługi, oferta, kontakt, o nas, wpisy | **nigdy** |
| polityka prywatności, cookies, regulamin | **nie** domyślnie (to sygnał wiarygodności, nie szkodzą); `noindex` tylko na prośbę klienta |
| 404 | nie dotyczy — plugin wyklucza ją z sitemapy i zwraca prawdziwe 404 |
noindex **nie** zastępuje przekierowania ani usunięcia: stary adres → zmiana sluga (308 z
`trackSlugHistoryHook`), strona do skasowania → usuń ją. Treść roboczą trzymasz jako **draft**
(niepublikowana nie jest dostępna publicznie), nie jako opublikowaną stronę z noindex.
Kontrole: `ipal-seo-check` (jedno h1, kolejność nagłówków, alt, obraz OG, cienkie strony,
linki wewnętrzne, noindex w sitemapie).
---
@@ -315,7 +373,11 @@ Domyślnie: `pages`, `media` + globale pluginu (`site-settings`,
`site-integrations`, Notifications, Cookie Settings) + globale projektu
(nawigacja, stopka, firma). Nic więcej, dopóki klient jawnie nie wymaga.
**NIGDY:** `users` (wbudowane w Payload), druga `media`, `daneFirmy`/`settings`/
**`users`** wstrzykuje `ipalKit` (kolekcja auth z `roles` i 2FA) — nie twórz jej, chyba
że potrzebujesz dodatkowych pól (wtedy własna `Users.ts` ze slugiem z `access.authCollection`;
plugin doda do niej role i 2FA).
**NIGDY:** druga `media`, `daneFirmy`/`settings`/
`navigation`/`footer` jako kolekcje (to globale), FAQ/hero/features jako kolekcje
(to bloki), kolekcja dla jednej rzeczy (to strona albo global).
@@ -352,6 +414,23 @@ Trzy problemy, których nie wolno powtarzać: **zoo pól CTA** (`ctaLabel`,
`cta2Text`, `buttonUrl`…), **pliki jako tekst** (`pdfUrl: '/files/x.pdf'`),
**sekcja-monolit** (200–400 linii z kartami, ikonami SVG i stylami przycisków).
### 6.0 Dziesięć zasad komponentu (skrót — szczegóły niżej)
1. **Mały:** `Component.tsx` sekcji ≤ ~80 linii JSX; element listy > 5 linii → własny `XxxCard.tsx`.
2. **Jedna rzecz = jeden komponent, stylowany RAZ.** Przycisk to `Button` (wygląd) + `CMSLink`
(cel z panelu) — w sekcjach nigdy własne klasy przycisku. Zmiana wyglądu wszystkich
przycisków = jedna zmiana w `Button.tsx`. To samo: obraz → `Media`, nagłówek → `SectionHeader`.
3. **Powtarzalne = tablica „+ Add …”**, nigdy numerowane pola. Przyciski: `buildLinksField()` →
redaktor klika „Add Button” tyle razy, ile potrzebuje (`maxRows` = ile mieści projekt).
`cta1`/`cta2`/`cta3`, `feature1Title`…, `image2` = błąd audytu.
4. **Panel czytelny bez znajomości kodu:** etykiety EN 1–3 słowa, zwinięte wiersze z treścią
(`rowLabel`), ≤ 6 pozycji widocznych po dodaniu bloku, ustawienia techniczne w sidebarze.
5. **Wariant zamiast kopii:** inny wygląd tej samej sekcji = `variant` (select), nie drugi blok.
6. **Zero tekstu, linku i obrazu w JSX** — wszystko z panelu, w każdym języku.
7. **Puste pole = element się nie renderuje** (nie „Lorem”, nie pusty `<div>`).
8. **Serwer domyślnie;** interakcja w osobnym, małym pliku `'use client'` z prostymi propsami.
9. **Typy z `@/payload-types`**, eksport nazwany, import z `@/…`, bez barreli.
10. **Każdy nowy blok:** test pustego bloku w panelu (§6.5a) + `ipal-audit --quick`.
### 6.1 Trzy warstwy
```
WARSTWA 1 — wspólne pola: linki z pluginu (buildLinkField, buildLinksField)
@@ -613,6 +692,43 @@ bloku nie importował Reacta). Kod: [kod-sekcji.md](./skills/ipal-block/resource
- Warianty → `Record<Variant, string>`, nie łańcuchy ternary.
Przykładowy `styles.css`: [kod-sekcji.md](./skills/ipal-block/resources/kod-sekcji.md).
### 6.11a Skalowanie (fluid / responsive) — od 360 px do 1920 px
- **Skala z pluginu:** `fluid.css` (rośnie do 1280 px) albo `fluid-wide.css` (rośnie do 1920 px —
wybierz, gdy projekt ma wyglądać inaczej na 13″ laptopie i 27″ monitorze). Zero `clamp()` w
komponentach; liczby z `DESIGN.md` → nadpisz `--ipal-*` w `:root`.
- **Wysokość ekranu:** zamiast `h-screen` / `100vh` → `min-h-[var(--ipal-hero-min-h)]` (svh, z
limitem). Nagłówek hero `--ipal-fs-display-fit`, odstępy hero `--ipal-space-section-fit` — na
1366×768 CTA hero musi być widoczne bez przewijania.
- **Szerokości:** kontener `max-w-[var(--ipal-container)]` + `px-gutter`; tekst ciągły
`max-w-[var(--ipal-measure)]` (~68 znaków w linii). Żadnych stałych `w-[640px]`, `h-[500px]`
w sekcjach — `min()`, `%`, `aspect-*`, `max-w-*`.
- **Siatki:** `grid-cols-[repeat(auto-fit,minmax(min(100%,18rem),1fr))]` albo breakpointy;
karta reaguje na swoją kolumnę: container queries (`@container` + `@md:`), nie tylko na ekran.
- **Obrazy kadrowane** (`object-cover`) mają punkt ostrości z panelu (`focalPoint: true` w
Media → `object-position` z `mediaImageProps`).
- **Ekrany testowe** (każda strona, przeglądarka / Playwright): 360×740, 390×844, 768×1024,
1024×768, **1280×800, 1366×768, 1440×900** (laptopy 13–15″), 1536×864, 1920×1080, plus
zoom 125 % i 150 % na 1366 (częsty na Windows). Zero poziomego scrolla, tekst bez ucięć,
menu działa, CTA hero widoczne.
### 6.11b Szybkość (Core Web Vitals)
| Co | Jak | Zakaz |
|---|---|---|
| obraz LCP (pierwszy widoczny, zwykle hero) | `<Media priority>` — dokładnie jeden na stronę | `priority` na wielu obrazach, hero jako CSS `background-image` |
| każdy inny obraz | `<Media sizes={MEDIA_SIZES.third}>` — `sizes` = szerokość na ekranie | brak `sizes` (pobiera pełną szerokość), `<img>` |
| placeholder | `buildMediaPlaceholderHook` + pole w Media (blur + kolor) | puste pudełka „wskakujące” przy ładowaniu |
| wideo w tle | `videoMode="background"`, MP4 H.264 ≤ 20 MB, bez dźwięku, z plakatem | wideo jako hero bez plakatu, `autoplay` z dźwiękiem |
| wideo z treścią | `videoMode="player"` (ładuje się po kliknięciu) | `preload="auto"` |
| YouTube | `<YouTubeEmbed>` z `/client` (iframe dopiero po kliknięciu) | gołe `<iframe src="youtube.com/embed…">` |
| next.config | `images: { ...buildImagesConfig() }` (AVIF/WebP, R2) | brak `remotePatterns` → obrazy z R2 bez optymalizacji |
| fonty | `next/font`, maks. 2 rodziny × 2–3 grubości, `subsets: ['latin', 'latin-ext']` (PL), `display: 'swap'` | `<link>` do Google Fonts, 6 grubości „na zapas” |
| skrypty firm trzecich | `Analytics`/`ConsentScript` z pluginu (po zgodzie, `defer`) | widgety czatu/map ładowane na starcie |
| komponenty klienckie | małe, tylko interakcja (§6.9) | cała sekcja `'use client'` |
Cel na zbudowanej stronie (mobile, Lighthouse/PageSpeed): LCP < 2,5 s, CLS < 0,1, INP < 200 ms.
Kontrole: `ipal-audit` (img/video poza Media, wiele `priority`, `h-screen`, stałe szerokości,
`<iframe>` YouTube) i `ipal-seo-check` (obrazy bez wymiarów, obraz LCP bez priorytetu).
### 6.12 Eksporty i importy
- **Eksporty nazwane** (`export function Hero`). `export default` tylko tam,
@@ -660,8 +776,8 @@ Przykładowy `styles.css`: [kod-sekcji.md](./skills/ipal-block/resources/kod-sek
**Compliance (PL/EU) — mechanizm z pluginu, treść od klienta:** strony polityk
jako System Pages, `CookieBanner` + `CookieButton`, checkbox `consent` w
formularzach (enforcement server-side), dane administratora w globalu, polityki z
`noindex`. Treści prawnych nie piszesz. Widget dostępności — tylko gdy klient
formularzach (enforcement server-side), dane administratora w globalu, tabela
ciasteczek z panelu (`<CookieTable>`, skan: ipal-consent-check). Treści prawnych nie piszesz. Widget dostępności — tylko gdy klient
wymaga (accessibility.md).
**Bezpieczeństwo:** 2FA wymuszone (`ipalKit({ twoFactor: { issuer, plugin:
@@ -670,6 +786,32 @@ payloadTotp } })`, nigdy `twoFactor: false` bez decyzji klienta). CSP: najpierw
---
## 8a. TESTY — co sprawdzasz i jak
Testujesz **zachowanie, które klient i Google widzą**, nie implementację pluginu (ten ma
własne testy). Kolejność od najtańszych:
| Poziom | Co | Kiedy |
|---|---|---|
| Typy | `pnpm generate:types && pnpm tsc --noEmit` | po każdej zmianie schematu |
| Reguły | `ipal-audit --quick` (hardkody, komplet §0b, panel) | po każdym bloku / kolekcji |
| Build | `pnpm build` — trasy stron `●` (SSG), nie `ƒ` | przed każdym „gotowe” |
| Smoke (Playwright) | `ipal-audit/resources/smoke.spec.template.ts` → `tests/smoke.spec.ts`: wszystkie URL-e z sitemapy 200 + tytuł + jedno h1, 404, trasy GEO, baner, formularz end-to-end | przed oddaniem i po każdej aktualizacji ipal-kit |
| Strona w przeglądarce | `ipal-seo-check`, `ipal-consent-check`, `cookie-scan` | przed oddaniem, po deployu |
| Logika projektu | vitest dla własnych funkcji (mapowanie danych firmy na JSON-LD, helpery, hooki, skrypty migracji z `--dry-run`) | gdy piszesz logikę, której plugin nie ma |
| Panel | test redaktora (§11) i test pustego bloku (§6.5a) | każdy nowy blok / global |
Zasady:
- **Test niezależny od treści** — szuka elementów po rolach i `data-ipal`, URL-i z sitemapy, nie po
tekstach, które redaktor zmieni jutro.
- **Każdy naprawiony błąd = test**, który by go złapał (smoke albo vitest), żeby nie wrócił.
- **Formularz testujesz naprawdę**: wysyłka → rekord w Form Submissions → mail do firmy **i**
potwierdzenie do klienta (lokalnie: Site Integrations → Send test + logi adaptera).
- **Nie testujesz pluginu w projekcie** (np. czy `submitForm` waliduje) — to robi ipal-kit. Gdy
zachowanie pluginu jest złe: ipal-plugin-gap.
- Testy w CI projektu: typy + audit `--quick` + build na każdy push; smoke na stagingu
(`IPAL_NOINDEX=1`) przed wdrożeniem produkcji.
## 8. STANDARDY KODU
**Typy**
@@ -0,0 +1,78 @@
/**
* Smoke tests of a client site (Playwright) — the few things that must never
* break: every language's homepage, a real 404, the form end to end, the
* language switch, the GEO routes. Copy to tests/smoke.spec.ts and run against
* a production build:
*
* pnpm add -D @playwright/test && pnpm exec playwright install chromium
* pnpm build && pnpm start &
* BASE_URL=http://localhost:3000 pnpm exec playwright test tests/smoke.spec.ts
*
* Content-agnostic on purpose: it reads locales from the sitemap and finds the
* form by its renderer, so it survives editors changing texts in the panel.
* Turnstile: run with the test keys in Site Integrations (1x00000000000000000000AA /
* 1x0000000000000000000000000000000AA) or without keys.
*/
import { expect, test } from '@playwright/test'
const BASE = (process.env.BASE_URL ?? 'http://localhost:3000').replace(/\/$/, '')
async function sitemapUrls(): Promise<string[]> {
const xml = await (await fetch(`${BASE}/sitemap.xml`)).text()
return [...xml.matchAll(/<loc>\s*([^<\s]+)\s*<\/loc>/g)].map((m) => m[1].replace(/^https?:\/\/[^/]+/, BASE))
}
test('every sitemap URL answers 200 with a title and one h1', async ({ page }) => {
const urls = (await sitemapUrls()).slice(0, 30)
expect(urls.length).toBeGreaterThan(0)
for (const url of urls) {
const res = await page.goto(url)
expect(res?.status(), url).toBe(200)
await expect(page, url).toHaveTitle(/\S/)
expect(await page.locator('h1').count(), `${url}: exactly one h1`).toBe(1)
}
})
test('unknown URL is a real 404', async ({ request }) => {
const res = await request.get(`${BASE}/this-page-does-not-exist-${Date.now()}`, { maxRedirects: 5 })
expect(res.status()).toBe(404)
})
test('GEO routes answer', async ({ request }) => {
for (const path of ['/robots.txt', '/sitemap.xml', '/llms.txt', '/llms-full.txt', '/api/health']) {
expect((await request.get(`${BASE}${path}`)).status(), path).toBe(200)
}
const mcp = await request.post(`${BASE}/api/mcp`, { data: { id: 1, jsonrpc: '2.0', method: 'tools/list' } })
expect(((await mcp.json()) as { result: { tools: unknown[] } }).result.tools.length).toBeGreaterThan(0)
})
test('cookie banner: reject hides it and survives a reload', async ({ page }) => {
await page.goto(BASE)
await page.locator('[data-ipal="reject"]').click()
await expect(page.locator('[data-ipal="banner"]')).toBeHidden()
await page.reload()
await expect(page.locator('[data-ipal="banner"]')).toBeHidden()
})
test('the first form on the site submits and shows the confirmation', async ({ page }) => {
const urls = await sitemapUrls()
let found = false
for (const url of urls) {
await page.goto(url)
const form = page.locator('form').filter({ has: page.locator('[type="submit"]') }).first()
if (!(await form.count())) {continue}
found = true
await page.locator('[data-ipal="reject"]').click().catch(() => {})
for (const input of await form.locator('input:not([type=hidden]):not([type=checkbox]), textarea').all()) {
const type = await input.getAttribute('type')
if (await input.getAttribute('name') === 'company_url') {continue} // honeypot stays empty
await input.fill(type === 'email' ? '[email protected]' : type === 'number' ? '1' : 'Smoke test')
}
for (const box of await form.locator('input[type=checkbox]').all()) {await box.check()}
for (const select of await form.locator('select').all()) {await select.selectOption({ index: 1 }).catch(() => {})}
await form.locator('[type="submit"]').click()
await expect(page.locator('[role="status"], [role="alert"]').first()).toBeVisible({ timeout: 15_000 })
break
}
test.skip(!found, 'no form on the site')
})
+33 -4
View File
@@ -105,12 +105,27 @@ if [ -n "$BLOCKS" ]; then
report ERROR "hardcoded href/src/file paths in blocks" "§2, §6 use CMSLink / Media" \
"$(g 'href=\{?["`]/|<img |/files/|/images/|\.pdf' $BLOCKS --include=*.tsx | nc '(href|<img|/files/|/images/|\.pdf)')"
report WARNING "button styled inside a section" "§6.0 style buttons once in Button.tsx — sections render <CMSLink> (appearance from the panel)" \
"$(g '<button[^>]*className=[^>]*(bg-|rounded|px-[0-9])' $BLOCKS --include=*.tsx)"
report ERROR "raw <a>/<Link> in blocks" "§6.3 links from the panel render via CMSLink" \
"$(g '<(a|Link)[ >]' $BLOCKS --include=*.tsx)"
report ERROR "hardcoded text in blocks" "§2 every visible text comes from the panel (localized field)" \
"$(node "$(dirname "$0")/jsx-text.mjs" $BLOCKS 2>/dev/null)"
report WARNING "<video> outside <Media>" "§6.11b videoMode background|player via Media (videoProps)" \
"$(g '<video[ >]' $BLOCKS --include=*.tsx)"
report WARNING "priority outside the hero" "§6.11b exactly one LCP image per page — priority only in the first section" \
"$(g '<Media[^>]*\bpriority\b' $BLOCKS --include=*.tsx | grep -viE '/hero')"
report WARNING "<Media> without sizes" "§6.11b sizes = width on screen (MEDIA_SIZES.*) — without it the full-width file downloads" \
"$(g '<Media[^>]*/>' $BLOCKS --include=*.tsx | grep -v 'sizes=')"
report WARNING "raw YouTube iframe" "§6.11b <YouTubeEmbed> (iframe only after click, no cookies before)" \
"$(g '<iframe[^>]*youtube' src --include=*.tsx)"
report WARNING "inline <svg> in blocks" "§6.10 icons via media upload or Icon map" \
"$(g '<svg[ >]' $BLOCKS --include=*.tsx)"
@@ -127,6 +142,12 @@ if [ -d src/components ]; then
fi
if [ -n "$UI" ]; then
report WARNING "100vh / h-screen" "§6.11a use min-h-[var(--ipal-hero-min-h)] (svh, capped) — 100vh overflows on laptops and mobile bars" \
"$(g '\b(h-screen|min-h-screen|h-\[100vh\]|min-h-\[100vh\])' $UI --include=*.tsx)"
report WARNING "fixed pixel widths/heights" "§6.11a no w-[640px]/h-[500px] in sections — max-w-*, %, aspect-*, min()" \
"$(g '\b(w|h|min-w|min-h)-\[[0-9]{3,}px\]' $UI --include=*.tsx)"
report ERROR "hex colors in classes" "§6.11 use design tokens (bg-primary…)" \
"$(g '(bg|text|border|from|to|via|fill|stroke)-\[#' $UI --include=*.tsx)"
@@ -142,8 +163,10 @@ fi
# --- Collections (§5.3) ---
if [ -d src/collections ]; then
report ERROR "forbidden collection" "§5.3 users are built in; settings/nav/footer are globals; FAQ/hero are blocks" \
"$(ls src/collections | grep -iE '^(users|user|settings|navigation|nav|footer|header|faq|hero|company|danefirmy)\.ts$')"
report ERROR "forbidden collection" "§5.3 settings/nav/footer are globals; FAQ/hero are blocks" \
"$(ls src/collections | grep -iE '^(settings|navigation|nav|footer|header|faq|hero|company|danefirmy)\.ts$')"
report WARNING "own users collection" "§5.3 ipalKit injects the auth collection — keep your own only to add fields (roles + 2FA still attach)" \
"$(ls src/collections | grep -iE '^(users|user)\.ts$')"
report WARNING "collections present — confirm each passed the §5.3 test" "minimum: Pages, Media" \
"$(ls src/collections | grep -viE '^(pages|media|users|user|settings|navigation|nav|footer|header|faq|hero|company|danefirmy)\.ts$')"
fi
@@ -202,7 +225,8 @@ if [ -n "$APP" ]; then
# 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 → createMarkdownRenderer + markdownResponse" 'createMarkdownRenderer' src/app
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 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
@@ -218,7 +242,9 @@ if [ -n "$APP" ]; then
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
# Forms
need ERROR '' "form submission via the plugin" "server action sendForm → submitForm (ipal-form)" 'submitForm' src
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
need WARNING '' "images preset" "next.config.ts → images: { ...buildImagesConfig() } (AVIF/WebP, R2 domain)" 'buildImagesConfig' next.config.ts next.config.mjs next.config.js
fi
if [ -n "$CFG" ]; then
@@ -230,6 +256,9 @@ if [ -n "$CFG" ]; then
report WARNING "robots blocks AI bots" "§0b.8 — only with the client's decision in AGENTS.md" \
"$(skipped aibots || g "aiBots: *'(disallow|block-training)'" src --include=*.ts)"
fi
if [ -n "$CFG" ] && grep -qE 'forms *:' "$CFG" 2>/dev/null && ! ls scripts/seed-form* >/dev/null 2>&1 && ! skipped forms-seed; then
report WARNING "no form seed" "ipal-form §5 — every form from scripts/seed-form-*.ts (notification + sender confirmation, all languages)" "scripts/seed-form-*.ts"
fi
need WARNING r2 "R2 env in .env.example" ".env.example lists R2_BUCKET, R2_ENDPOINT, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, R2_PUBLIC_URL" 'R2_BUCKET' .env.example
need WARNING '' "IPAL_IP_HEADER in .env.example" "header the rate limit trusts, e.g. cf-connecting-ip (forms.md)" 'IPAL_IP_HEADER' .env.example
@@ -137,40 +137,40 @@ export function buttonClass(appearance: LinkAppearance): string {
}
```
`src/components/ui/Media.tsx` — **każdy** obraz/wideo z panelu:
`src/components/ui/Media.tsx` — **każdy** obraz/wideo z panelu. Szybkość liczy plugin
(`mediaImageProps`, `videoProps`), wygląd zostaje tutaj:
```tsx
import Image from 'next/image'
import { mediaImageProps, MEDIA_SIZES, videoProps, type VideoMode } from '@intecion/ipal-kit'
import type { Media as MediaDoc } from '@/payload-types'
type Props = {
resource: MediaDoc | string | number | null | undefined
/** Szerokość NA EKRANIE — MEDIA_SIZES.half / .third / własny string. Bez tego pobiera się pełna szerokość. */
sizes?: string
/** Tylko pierwszy widoczny obraz strony (hero, LCP). Reszta ładuje się leniwie. */
priority?: boolean
className?: string
/** Poster image URL for videos (shown before playback). */
poster?: string
/** Wideo: 'background' (pętla bez dźwięku) albo 'player' (kontrolki, ładowanie po kliknięciu). */
videoMode?: VideoMode
/** Plakat wideo — upload z panelu. */
poster?: MediaDoc | string | number | null
}
export function Media({ resource, sizes = '100vw', priority = false, className, poster }: Props) {
if (!resource || typeof resource !== 'object' || !resource.url) return null
const { url, alt, width, height, mimeType } = resource
if (mimeType?.startsWith('video/')) {
// preload="metadata": the browser fetches only headers until playback, not the whole file
return (
<video src={url} className={className} poster={poster} preload="metadata" autoPlay muted loop playsInline />
)
}
if (!width || !height) return null // non-image file (PDF) — use CMSLink type 'file'
return (
<Image src={url} alt={alt ?? ''} width={width} height={height}
sizes={sizes} priority={priority} className={className} />
)
export function Media({ resource, sizes = MEDIA_SIZES.full, priority = false, className, videoMode = 'player', poster }: Props) {
const video = videoProps(resource, { mode: videoMode, poster })
if (video) return <video {...video} className={className} />
const img = mediaImageProps(resource, { priority, sizes })
if (!img) return null // PDF / plik — link typu 'file' (CMSLink), nie <Media>
return <Image {...img} className={className} />
}
```
Media w kolekcji: `upload: { focalPoint: true, … }` (punkt ostrości → `object-position`) oraz
placeholder z pluginu: `hooks.beforeOperation: [buildOptimizeUploadHook(), buildMediaPlaceholderHook()]`,
pole `buildMediaPlaceholderField()` (rozmyty podgląd + kolor podczas ładowania).
`Section.tsx` i `SectionHeader.tsx`:
```tsx
@@ -37,3 +37,34 @@ się załadować wcześniej tylko z sygnałem Consent Mode „denied” i bez ci
Skrypt wymaga przycisków z `data-ipal="accept"` / `"reject"` — ma je
`CookieBanner` z pluginu. Własny baner w projekcie to naruszenie AGENT.md §7.
## Lista ciasteczek do polityki cookies (cookie-scan)
Po każdej zmianie narzędzi (nowy piksel, czat, mapa, wideo) i przed oddaniem strony:
1. Skan działającej strony (bez zgody i po „Akceptuj wszystko”, strona główna + do 10 stron z sitemapy):
```bash
node .agents/skills/ipal-consent-check/scripts/cookie-scan.mjs http://localhost:3000 --lang pl
```
Wynik: `cookie-scan/cookies.json` i `cookie-scan/cookies.md` (tabela). `[ERROR]` = ciasteczko
**nie-niezbędne ustawione przed zgodą** — napraw jak w tabeli wyżej. `[WARNING] unknown` —
ustal dostawcę i cel, wpisz `category` (`necessary|functional|analytics|marketing`) i `purpose`
w `cookies.json`. Nie zgaduj — zapytaj, jeśli nie wiesz.
2. Import do panelu (Cookie Settings → Cookies), każdy język osobno (skan z `--lang en` dla angielskiego):
```bash
LOCALE=pl pnpm payload run .agents/skills/ipal-consent-check/scripts/import-cookies.ts cookie-scan/cookies.json
```
Łączy po nazwie, nie nadpisuje zmian redaktora (`OVERWRITE=1` wymusza). Nie usuwa ciasteczek,
których skan nie widział — to robi redaktor w panelu.
3. Strona polityki cookies pokazuje tabelę z panelu — **nie wklejaj listy do treści polityki**:
```tsx
import { getCookieTable, getConsentTexts } from '@intecion/ipal-kit'
import { CookieTable } from '@intecion/ipal-kit/rsc'
const rows = await getCookieTable({ payload, locale })
<CookieTable rows={rows} categories={texts.categories} labels={/* nagłówki kolumn z panelu */} />
```
Tabela bez stylów (`classNames` per element). Blok w panelu typu „Cookie table” na stronie
polityki to dobre miejsce — wtedy redaktor decyduje, gdzie się pojawi.
Czas życia: Chrome skraca każde ciasteczko do maks. 400 dni (13 mies.) — skan pokazuje to, co
realnie zostaje w przeglądarce. `ipal-a11y` i inne klucze localStorage są wymienione osobno.
@@ -0,0 +1,176 @@
#!/usr/bin/env node
// ipal cookie-scan — lists every cookie (and localStorage key) a running site sets, for the cookie policy.
// node cookie-scan.mjs <baseUrl> [--pages 10] [--lang pl|en] [--out cookie-scan] [--wait 3000]
// Two fresh browser profiles: before any decision, and after "Accept all" (data-ipal="accept").
// Pages: the base URL + up to --pages URLs from /sitemap.xml.
// Writes <out>/cookies.json (import into the panel: import-cookies.ts) and <out>/cookies.md (table).
// Needs Playwright: pnpm add -D playwright && pnpm exec playwright install chromium
// Exit code: 0 = ok, 1 = non-necessary cookies set BEFORE consent, 2 = setup problem.
import { mkdirSync, writeFileSync } from 'node:fs'
import path from 'node:path'
const args = process.argv.slice(2)
if (!args[0] || args.includes('--help') || args.includes('-h')) {
console.log('Usage: cookie-scan.mjs <baseUrl> [--pages N] [--lang pl|en] [--out dir] [--wait ms]')
process.exit(args[0] ? 0 : 2)
}
const opt = (name, def) => {
const i = args.indexOf(`--${name}`)
return i >= 0 ? args[i + 1] : def
}
const base = args[0].replace(/\/$/, '')
const MAX = Number(opt('pages', 10)) || 10
const LANG = opt('lang', 'pl') === 'en' ? 'en' : 'pl'
const OUT = opt('out', 'cookie-scan')
const WAIT = Number(opt('wait', 3000)) || 3000
let pw
for (const mod of ['playwright', 'playwright-core', '@playwright/test']) {
try { pw = await import(mod); break } catch { /* next */ }
}
if (!pw) {
console.error('cookie-scan: Playwright not found. Install: pnpm add -D playwright && pnpm exec playwright install chromium')
process.exit(2)
}
const { chromium } = pw.default ?? pw
// Known cookies → provider, consent category, purpose. `*` = prefix.
const T = (pl, en) => ({ en, pl })
const CATALOG = [
['cookie-consent', 'this site', 'necessary', T('Zapamiętuje Twoją decyzję w sprawie plików cookies.', 'Stores your cookie consent decision.')],
['NEXT_LOCALE', 'this site', 'functional', T('Zapamiętuje wybrany język strony.', 'Remembers the selected site language.')],
['payload-token', 'this site', 'necessary', T('Sesja zalogowanego redaktora (panel administracyjny).', 'Logged-in editor session (admin panel).')],
['__cf_bm', 'Cloudflare', 'necessary', T('Ochrona przed botami.', 'Bot protection.')],
['_cfuvid', 'Cloudflare', 'necessary', T('Ochrona przed nadużyciami i limit zapytań.', 'Abuse protection and rate limiting.')],
['cf_clearance', 'Cloudflare', 'necessary', T('Potwierdzenie przejścia weryfikacji Cloudflare.', 'Proof of passing a Cloudflare challenge.')],
['_ga', 'Google', 'analytics', T('Google Analytics: rozróżnia użytkowników w statystykach.', 'Google Analytics: distinguishes users in statistics.')],
['_ga_*', 'Google', 'analytics', T('Google Analytics: stan sesji w statystykach.', 'Google Analytics: session state for statistics.')],
['_gid', 'Google', 'analytics', T('Google Analytics: rozróżnia użytkowników (24 h).', 'Google Analytics: distinguishes users (24 h).')],
['_gat*', 'Google', 'analytics', T('Google Analytics: ogranicza liczbę zapytań.', 'Google Analytics: throttles request rate.')],
['_gcl_*', 'Google', 'marketing', T('Google Ads: przypisanie konwersji do reklam.', 'Google Ads: attributes conversions to ads.')],
['_fbp', 'Meta', 'marketing', T('Meta Pixel: pomiar i dopasowanie reklam.', 'Meta Pixel: ad measurement and targeting.')],
['_fbc', 'Meta', 'marketing', T('Meta Pixel: zapamiętuje kliknięcie w reklamę.', 'Meta Pixel: stores the ad click.')],
['_clck', 'Microsoft Clarity', 'analytics', T('Clarity: identyfikator użytkownika w analizie zachowań.', 'Clarity: user id for behaviour analytics.')],
['_clsk', 'Microsoft Clarity', 'analytics', T('Clarity: łączy odsłony w jedną sesję.', 'Clarity: joins page views into a session.')],
['CLID', 'Microsoft Clarity', 'analytics', T('Clarity: identyfikator użytkownika.', 'Clarity: user id.')],
['MUID', 'Microsoft', 'marketing', T('Microsoft: identyfikator przeglądarki dla reklam.', 'Microsoft: browser id for advertising.')],
['_uetsid', 'Microsoft Ads', 'marketing', T('Microsoft Ads: pomiar konwersji (sesja).', 'Microsoft Ads: conversion tracking (session).')],
['_uetvid', 'Microsoft Ads', 'marketing', T('Microsoft Ads: pomiar konwersji (użytkownik).', 'Microsoft Ads: conversion tracking (user).')],
['li_fat_id', 'LinkedIn', 'marketing', T('LinkedIn Insight: przypisanie konwersji.', 'LinkedIn Insight: conversion attribution.')],
['lidc', 'LinkedIn', 'marketing', T('LinkedIn: wybór centrum danych.', 'LinkedIn: data-center routing.')],
['bcookie', 'LinkedIn', 'marketing', T('LinkedIn: identyfikator przeglądarki.', 'LinkedIn: browser id.')],
['bscookie', 'LinkedIn', 'marketing', T('LinkedIn: bezpieczny identyfikator przeglądarki.', 'LinkedIn: secure browser id.')],
['UserMatchHistory', 'LinkedIn', 'marketing', T('LinkedIn Ads: synchronizacja identyfikatorów.', 'LinkedIn Ads: id sync.')],
['AnalyticsSyncHistory', 'LinkedIn', 'marketing', T('LinkedIn: synchronizacja z analityką.', 'LinkedIn: analytics sync.')],
['_ttp', 'TikTok', 'marketing', T('TikTok Pixel: pomiar reklam.', 'TikTok Pixel: ad measurement.')],
['_tt_enable_cookie', 'TikTok', 'marketing', T('TikTok Pixel: sprawdza obsługę cookies.', 'TikTok Pixel: cookie support check.')],
['_hj*', 'Hotjar', 'analytics', T('Hotjar: analiza zachowań użytkowników.', 'Hotjar: behaviour analytics.')],
['YSC', 'YouTube', 'marketing', T('YouTube: statystyki odtworzeń osadzonych filmów.', 'YouTube: embedded video statistics.')],
['VISITOR_INFO1_LIVE', 'YouTube', 'marketing', T('YouTube: szacuje przepustowość, preferencje odtwarzacza.', 'YouTube: bandwidth estimate, player preferences.')],
['VISITOR_PRIVACY_METADATA', 'YouTube', 'marketing', T('YouTube: stan zgody użytkownika.', 'YouTube: user consent state.')],
]
const match = (name) =>
CATALOG.find(([pattern]) => (pattern.endsWith('*') ? name.startsWith(pattern.slice(0, -1)) : name === pattern))
const human = (expires) => {
if (!expires || expires < 0) {return LANG === 'pl' ? 'sesja' : 'session'}
const days = Math.round((expires * 1000 - Date.now()) / 86_400_000)
if (days < 1) {
const h = Math.max(1, Math.round((expires * 1000 - Date.now()) / 3_600_000))
return LANG === 'pl' ? `${h} godz.` : `${h} h`
}
if (days < 60) {return LANG === 'pl' ? `${days} dni` : `${days} days`}
const months = Math.round(days / 30)
if (months < 24) {return LANG === 'pl' ? `${months} mies.` : `${months} months`}
const years = Math.round(days / 365)
return LANG === 'pl' ? `${years} ${years < 5 ? 'lata' : 'lat'}` : `${years} years`
}
// Pages to visit
const pages = [base]
try {
const xml = await (await fetch(`${base}/sitemap.xml`)).text()
for (const m of xml.matchAll(/<loc>\s*([^<\s]+)\s*<\/loc>/g)) {
if (pages.length > MAX) {break}
if (!pages.includes(m[1])) {pages.push(m[1])}
}
} catch { /* no sitemap — base only */ }
let browser
try {
browser = await chromium.launch()
} catch (err) {
console.error(`cookie-scan: cannot start Chromium — run: pnpm exec playwright install chromium\n${err.message?.split('\n')[0] ?? err}`)
process.exit(2)
}
const host = new URL(base).hostname.replace(/^www\./, '')
async function visit(accept) {
const ctx = await browser.newContext()
const page = await ctx.newPage()
const storage = new Set()
try {
for (const [i, url] of pages.entries()) {
await page.goto(url, { waitUntil: 'networkidle', timeout: 30_000 }).catch(() => {})
if (accept && i === 0) {
const btn = page.locator('[data-ipal="accept"]')
if (await btn.count()) {await btn.first().click().catch(() => {})}
}
await page.waitForTimeout(WAIT)
for (const k of await page.evaluate(() => Object.keys(localStorage)).catch(() => [])) {storage.add(k)}
}
return { cookies: await ctx.cookies(), storage: [...storage] }
} finally {
await ctx.close()
}
}
const before = await visit(false)
const after = await visit(true)
await browser.close()
const beforeNames = new Set(before.cookies.map((c) => c.name))
const seen = new Map()
for (const c of [...before.cookies, ...after.cookies]) {
if (seen.has(c.name)) {continue}
const known = match(c.name)
const firstParty = c.domain.replace(/^\./, '').endsWith(host)
seen.set(c.name, {
category: known?.[2] ?? 'unknown',
domain: c.domain.replace(/^\./, ''),
duration: human(c.expires),
firstParty,
name: c.name,
provider: known ? (known[1] === 'this site' ? (LANG === 'pl' ? 'ta strona' : 'this site') : known[1]) : firstParty ? (LANG === 'pl' ? 'ta strona' : 'this site') : c.domain.replace(/^\./, ''),
purpose: known?.[3][LANG] ?? '',
setBeforeConsent: beforeNames.has(c.name),
})
}
const ORDER = ['necessary', 'functional', 'analytics', 'marketing', 'unknown']
const cookies = [...seen.values()].sort((a, b) => ORDER.indexOf(a.category) - ORDER.indexOf(b.category) || a.name.localeCompare(b.name))
mkdirSync(OUT, { recursive: true })
writeFileSync(path.join(OUT, 'cookies.json'), JSON.stringify({ base, cookies, lang: LANG, localStorage: after.storage, pages, scannedAt: new Date().toISOString() }, null, 2))
const head = LANG === 'pl'
? '| Nazwa | Dostawca | Kategoria | Cel | Czas przechowywania |\n|---|---|---|---|---|'
: '| Name | Provider | Category | Purpose | Duration |\n|---|---|---|---|---|'
const rows = cookies.map((c) => `| \`${c.name}\` | ${c.provider} | ${c.category} | ${c.purpose || '—'} | ${c.duration} |`)
writeFileSync(path.join(OUT, 'cookies.md'), `${head}\n${rows.join('\n')}\n`)
let errors = 0
console.log(`cookie-scan — ${base} (${pages.length} page(s))`)
const early = cookies.filter((c) => c.setBeforeConsent && c.category !== 'necessary')
if (early.length) {
errors += early.length
console.log(`\n[ERROR] set BEFORE consent and not necessary (${early.length}) — GDPR: gate it (ConsentScript / Analytics) or classify it as necessary if it truly is`)
for (const c of early) {console.log(` ${c.name} (${c.domain}, ${c.category})`)}
}
const unknown = cookies.filter((c) => c.category === 'unknown')
if (unknown.length) {
console.log(`\n[WARNING] unknown cookies (${unknown.length}) — find the provider and purpose, set the category in cookies.json before importing`)
for (const c of unknown) {console.log(` ${c.name} (${c.domain})`)}
}
if (after.storage.length) {console.log(`\nlocalStorage keys (mention in the policy if they hold personal data): ${after.storage.join(', ')}`)}
console.log(`\n${cookies.length} cookie(s) → ${path.join(OUT, 'cookies.json')}, ${path.join(OUT, 'cookies.md')}`)
console.log(`Import into the panel: LOCALE=${LANG} pnpm payload run .agents/skills/ipal-consent-check/scripts/import-cookies.ts ${path.join(OUT, 'cookies.json')}`)
process.exit(errors ? 1 : 0)
@@ -0,0 +1,59 @@
/**
* Imports a cookie-scan result into Cookie Settings → Cookies (panel), so the
* cookie policy page (<CookieTable>) lists what the site really sets.
*
* LOCALE=pl pnpm payload run .agents/skills/ipal-consent-check/scripts/import-cookies.ts cookie-scan/cookies.json
* # second language: scan again with --lang en, then import with LOCALE=en
* # (rows are matched by cookie name; only purpose/duration are localized)
*
* Merges by cookie name: an editor's own purpose/duration/provider are kept
* unless OVERWRITE=1. Cookies no longer seen are kept too (remove them in the
* panel) — a scan of a few pages can miss cookies set elsewhere. `unknown`
* category rows are skipped: classify them in cookies.json first.
*/
import config from '@payload-config'
import { readFileSync } from 'node:fs'
import { getPayload } from 'payload'
type Scanned = { category: string; duration?: string; name: string; provider?: string; purpose?: string }
type Row = { category?: string; duration?: null | string; id?: string; name?: string; provider?: null | string; purpose?: null | string }
// `payload run` forwards positional args but not --flags — options come from env.
const file = process.argv.slice(2).find((a) => a.endsWith('.json'))
const locale = process.env.LOCALE
const overwrite = process.env.OVERWRITE === '1'
if (!file || !locale) {
console.error('Usage: LOCALE=<code> [OVERWRITE=1] pnpm payload run import-cookies.ts <cookies.json>')
process.exit(2)
}
const scan = JSON.parse(readFileSync(file, 'utf8')) as { cookies: Scanned[] }
const payload = await getPayload({ config })
const current = (await payload.findGlobal({ slug: 'cookie-settings' as never, depth: 0, locale: locale as never })) as { cookies?: Row[] }
const rows: Row[] = [...(current.cookies ?? [])]
let added = 0
let updated = 0
let skipped = 0
for (const c of scan.cookies) {
if (c.category === 'unknown') {
skipped++
continue
}
const existing = rows.find((r) => r.name === c.name)
if (!existing) {
rows.push({ category: c.category, duration: c.duration, name: c.name, provider: c.provider, purpose: c.purpose })
added++
continue
}
const pick = (mine: null | string | undefined, theirs?: string) => (overwrite || !mine ? (theirs ?? mine) : mine)
existing.provider = pick(existing.provider, c.provider)
existing.purpose = pick(existing.purpose, c.purpose)
existing.duration = pick(existing.duration, c.duration)
if (overwrite) {existing.category = c.category}
updated++
}
await payload.updateGlobal({ slug: 'cookie-settings' as never, data: { cookies: rows } as never, locale: locale as never })
console.log(`Cookie Settings (${locale}): ${added} added, ${updated} updated, ${skipped} unknown skipped. Review them in the panel.`)
process.exit(0)
+24 -5
View File
@@ -38,7 +38,8 @@ weryfikacji nie ma, formularz działa; jeden klucz → wyłączony + alert na da
## 3. Kod (skopiuj z `resources/`, dostosuj tylko klasy)
| Plik | Do projektu | Rola |
|---|---|---|
| `actions.ts` | `src/app/(frontend)/[locale]/actions.ts` | jedna akcja `sendForm`: honeypot → IP (`clientIp`, `IPAL_IP_HEADER`) → `submitForm` → tekst z Notifications |
| `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` |
@@ -65,22 +66,40 @@ 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.
## 5. Panel (zrób sam albo seedem, potem opisz w raporcie)
1. **Forms → nowy formularz**: pola z briefu, `name` po angielsku, małe litery
## 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),
ma wszystkie języki i **oba maile**, o których łatwo zapomnieć:
- **powiadomienie do firmy**: `emailTo` = adres z panelu (global firmy), `replyTo: {{email}}`, treść `{{*:table}}`;
- **potwierdzenie do klienta**: `emailTo: {{email}}`, `replyTo` = adres firmy, temat i treść per język.
```bash
cp .agents/skills/ipal-form/resources/seed-form.template.ts scripts/seed-form-contact.ts
# uzupełnij FORM z briefu (pola, etykiety, komunikaty, tematy maili — każdy język), NOTIFY = global/pole z adresem firmy
pnpm payload run scripts/seed-form-contact.ts
```
Bez adresu powiadomień skrypt **zatrzymuje się** — zapytaj klienta, na jaką skrzynkę mają przychodzić
zgłoszenia (pytanie z listy w ipal-site), wpisz go w panelu i uruchom ponownie. Nie wpisuj adresu w kod.
Skrypt commitujesz — na produkcji uruchamiasz go po migracji. Zmiana formularza: popraw FORM,
`SEED_UPDATE=1 pnpm payload run …` (nadpisuje zmiany redaktora — tylko przed oddaniem).
Szczegóły, które seed już spełnia, a które sprawdzasz po każdej ręcznej zmianie w panelu:
1. **Forms → formularz**: pola z briefu, `name` po angielsku, małe litery
(`name`, `email`, `phone`, `message`, `consent`); etykiety per język.
2. **Zgoda RODO**: checkbox `consent`, etykieta z linkiem do polityki, **nie**
zaznaczony domyślnie (plugin i tak wymusza server-side → `reason: 'consent'`).
3. **Confirmation**: komunikat (per język) albo redirect na stronę „Dziękujemy”
(wtedy ta strona `noindex`).
4. **Emails**: powiadomienie do firmy (`emailTo` z globalu firmy/panelu, `replyTo: {{email}}`,
treść `{{*:table}}`) + opcjonalne potwierdzenie do wysyłającego (`emailTo: {{email}}`).
treść `{{*:table}}`) **i** potwierdzenie do wysyłającego (`emailTo: {{email}}`) — oba obowiązkowe.
Pole e-mail musi mieć `name: 'email'` (plugin przyjmuje w nim dokładnie jeden adres).
5. **Analytics (GTM / dataLayer)**: Event name `generate_lead` / `form_submit`, parametry `form_name`.
6. **Site Integrations**: transport maila (SMTP/Graph) + **Send test**; klucze Turnstile.
7. **Notifications → form.\***: teksty w każdym języku.
## 6. Sprawdź sam, zanim powiesz „gotowe”
- [ ] wysyłka z pustymi wymaganymi polami → błędy przy polach, bez requestu;
- [ ] poprawna wysyłka → potwierdzenie, rekord w **Form Submissions**, mail doszedł
- [ ] poprawna wysyłka → potwierdzenie, rekord w **Form Submissions**, mail do firmy doszedł
**i** potwierdzenie doszło na adres wpisany w formularzu
(Send test w panelu działa = transport OK; brak maila mimo to → zakładka Emails formularza);
- [ ] niezaznaczona zgoda → komunikat z Notifications (nie angielski fallback);
- [ ] 6 szybkich wysyłek → `rate_limited`;
@@ -1,21 +1,9 @@
// src/app/(frontend)/[locale]/actions.ts — ONE server action for every builder form.
// honeypot → client IP (IPAL_IP_HEADER) → submitForm (rate limit, Turnstile,
// validation, GDPR consent, storage) → visitor message from Notifications.
'use server'
import { headers } from 'next/headers'
import { submitForm } from '@intecion/ipal-kit/server'
import { clientIp, isHoneypotTripped, HONEYPOT_FIELD, getNotificationTexts, resolveFormMessage } from '@intecion/ipal-kit'
import { createSubmitAction } from '@intecion/ipal-kit/server'
import { getCachedPayload } from '@/lib/content'
export async function sendForm(
formId: string,
locale: string,
values: Record<string, unknown>,
turnstileToken?: string,
): Promise<{ success: boolean; message: string }> {
const payload = await getCachedPayload()
const texts = (await getNotificationTexts({ payload, locale })).form
if (isHoneypotTripped(values)) return { success: true, message: texts.success } // bot: fake success, nothing stored
const { [HONEYPOT_FIELD]: _hp, ...data } = values
const ip = clientIp(await headers()) || undefined // headers(): fine in a server action — never in the page tree (breaks SSG)
const result = await submitForm({ payload, formId, data, turnstileToken, ip })
return { success: result.success, message: resolveFormMessage(result, texts) }
}
export const sendForm = createSubmitAction({ getCachedPayload, headers })
@@ -0,0 +1,175 @@
/**
* Seed of ONE form in the database — fields, confirmation, and the two e-mails
* every site needs: a notification to the company and a confirmation to the
* person who sent it. Copy to scripts/seed-form-<name>.ts, fill FORM from the
* brief (every language), run:
*
* pnpm payload run scripts/seed-form-contact.ts # creates the form if missing
* SEED_UPDATE=1 pnpm payload run scripts/seed-form-contact.ts # also overwrites an existing one
*
* Nothing about the company lives in this file. The notification address comes
* from the panel — NOTIFY.global / NOTIFY.field below (the project's company
* global) — or SEED_NOTIFY_EMAIL for a first run. Without an address the script
* stops: a form whose submissions reach nobody is a bug, not a default.
*
* Safe to send to {{email}}: submitForm accepts exactly one address in an
* `email` field (no extra recipients, no header injection).
*/
import config from '@payload-config'
import { getPayload } from 'payload'
// ─── fill from the brief ────────────────────────────────────────────────────
const FORM = {
/** Unique, not shown to visitors — the seed finds the form by it. */
title: 'Contact form',
fields: [
{ blockType: 'text', name: 'name', required: true, width: 50, label: { pl: 'Imię i nazwisko', en: 'Full name' } },
{ 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' } },
// GDPR consent — name MUST stay `consent`; never pre-ticked (the plugin enforces it server-side).
{
blockType: 'checkbox',
name: 'consent',
required: true,
width: 100,
label: {
pl: 'Zgadzam się na przetwarzanie moich danych w celu odpowiedzi na wiadomość.',
en: 'I agree to the processing of my data to answer this message.',
},
},
],
submitButtonLabel: { pl: 'Wyślij', en: 'Send' },
confirmation: {
pl: 'Dziękujemy! Odpowiemy najszybciej, jak to możliwe.',
en: 'Thank you! We will get back to you as soon as possible.',
},
/** E-mail to the company. {{*:table}} = every field as a table. */
notification: {
subject: { pl: 'Nowa wiadomość ze strony od {{name}}', en: 'New website message from {{name}}' },
message: { pl: 'Nowe zgłoszenie z formularza:\n\n{{*:table}}', en: 'New form submission:\n\n{{*:table}}' },
},
/** E-mail to the sender. */
confirmationEmail: {
subject: { pl: 'Otrzymaliśmy Twoją wiadomość', en: 'We received your message' },
message: {
pl: 'Dzień dobry {{name}},\n\ndziękujemy za wiadomość — odpowiemy wkrótce.\n\nTwoje zgłoszenie:\n{{*:table}}',
en: 'Hello {{name}},\n\nthank you for your message — we will reply shortly.\n\nYour submission:\n{{*:table}}',
},
},
} as const
/** Where the company's address lives in the panel (project global + field). */
const NOTIFY = { global: 'company', field: 'email' }
// ────────────────────────────────────────────────────────────────────────────
type Localized = Readonly<Record<string, string>>
/** Plain text (with blank-line paragraphs) → Lexical rich text, as form-builder messages expect. */
function richText(text: string) {
return {
root: {
children: text.split(/\n{2,}/).map((para) => ({
children: para.split('\n').flatMap((line, i) => [
...(i ? [{ type: 'linebreak', version: 1 }] : []),
{ detail: 0, format: 0, mode: 'normal', style: '', text: line, type: 'text', version: 1 },
]),
direction: 'ltr',
format: '',
indent: 0,
type: 'paragraph',
version: 1,
})),
direction: 'ltr',
format: '',
indent: 0,
type: 'root',
version: 1,
},
}
}
const payload = await getPayload({ config })
const locales = (payload.config.localization ? payload.config.localization.localeCodes : ['pl']) as string[]
const defaultLocale = (payload.config.localization ? payload.config.localization.defaultLocale : locales[0]) as string
const pick = (value: Localized, locale: string) => value[locale] ?? value[defaultLocale] ?? Object.values(value)[0]
// Notification address — from the panel, never from this file.
let notifyTo = process.env.SEED_NOTIFY_EMAIL?.trim() ?? ''
if (!notifyTo) {
try {
const g = (await payload.findGlobal({ slug: NOTIFY.global as never, depth: 0 })) as Record<string, unknown>
notifyTo = typeof g[NOTIFY.field] === 'string' ? (g[NOTIFY.field] as string).trim() : ''
} catch {
// no such global — handled below
}
}
if (!/^[^\s@,;]+@[^\s@,;]+\.[^\s@,;]+$/.test(notifyTo)) {
console.error(
`[seed-form] No notification address. Fill ${NOTIFY.global} → ${NOTIFY.field} in the panel ` +
'(or run with SEED_NOTIFY_EMAIL=…). Ask the client which inbox gets the submissions — do not guess.',
)
process.exit(1)
}
/** Form data in one locale (localized fields resolved for it). */
function dataFor(locale: string) {
return {
confirmationMessage: richText(pick(FORM.confirmation, locale)),
confirmationType: 'message',
emails: [
{
emailTo: notifyTo,
replyTo: '{{email}}',
message: richText(pick(FORM.notification.message, locale)),
subject: pick(FORM.notification.subject, locale),
},
{
emailTo: '{{email}}',
replyTo: notifyTo,
message: richText(pick(FORM.confirmationEmail.message, locale)),
subject: pick(FORM.confirmationEmail.subject, locale),
},
],
fields: FORM.fields.map(({ label, ...field }) => ({ ...field, label: pick(label, locale) })),
submitButtonLabel: pick(FORM.submitButtonLabel, locale),
title: FORM.title,
}
}
const existing = await payload.find({ collection: 'forms' as never, limit: 1, where: { title: { equals: FORM.title } } })
let id = existing.docs[0]?.id as number | string | undefined
if (id && process.env.SEED_UPDATE !== '1') {
console.log(`[seed-form] "${FORM.title}" exists (id ${id}) — unchanged. SEED_UPDATE=1 overwrites it.`)
process.exit(0)
}
if (!id) {
const created = await payload.create({ collection: 'forms' as never, data: dataFor(defaultLocale) as never, locale: defaultLocale as never })
id = created.id
} else {
await payload.update({ collection: 'forms' as never, data: dataFor(defaultLocale) as never, id, locale: defaultLocale as never })
}
// Other languages: same rows (ids kept), localized texts per locale.
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 }[]
}
const d = dataFor(locale)
await payload.update({
collection: 'forms' as never,
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 })),
} as never,
id,
locale: locale as never,
})
}
console.log(`[seed-form] "${FORM.title}" ready (id ${id}) in ${locales.join(', ')} — notifications to ${notifyTo}, confirmation to the sender.`)
console.log('Next: place the form in a Form block on the contact page, then Site Integrations → Send test.')
process.exit(0)
@@ -98,7 +98,7 @@ for (let i = 0; sample.length < Math.min(MAX, urls.length); i++) {
const multiLocale = hasAlternates || byLocale.size > 1
const urlSet = new Set(urls.map(norm))
const titles = new Map()
const issues = { status: [], noHead: [], body: [], title: [], longTitle: [], desc: [], canonical: [], canonSelf: [], noindex: [], hreflang: [], xdefault: [], reciprocal: [], favicon: [], jsonLd: [], mdAlt: [] }
const issues = { status: [], noHead: [], body: [], title: [], longTitle: [], desc: [], canonical: [], canonSelf: [], noindex: [], hreflang: [], xdefault: [], reciprocal: [], favicon: [], jsonLd: [], mdAlt: [], h1: [], headingSkip: [], alt: [], imgSize: [], lcp: [], ogImage: [], thin: [], noLinks: [], xRobots: [] }
const checkedPaths = []
for (const url of sample) {
@@ -135,6 +135,33 @@ for (const url of sample) {
if (!/<link[^>]+type="text\/markdown"/i.test(head)) issues.mdAlt.push(url)
checkedPaths.push(new URL(url).pathname)
// --- content & performance (AGENT.md §0c, §6.11b) ---
if (/noindex/i.test(page.res.headers.get('x-robots-tag') ?? '')) issues.xRobots.push(url)
const main = body.replace(/<script[\s\S]*?<\/script>|<style[\s\S]*?<\/style>|<template[\s\S]*?<\/template>/gi, '')
const h1s = (main.match(/<h1[\s>]/gi) ?? []).length
if (h1s !== 1) issues.h1.push(`${url} (${h1s} h1)`)
let prev = 0
for (const m of main.matchAll(/<h([1-6])[\s>]/gi)) {
const level = Number(m[1])
if (prev && level > prev + 1) { issues.headingSkip.push(`${url} (h${prev} → h${level})`); break }
prev = level
}
const imgs = tags(main, /<img\b[^>]*>/gi)
const noAlt = imgs.filter((t) => !/\salt\s*=/.test(t))
if (noAlt.length) issues.alt.push(`${url} (${noAlt.length} img)`)
const noSize = imgs.filter((t) => !/\swidth\s*=/.test(t) || !/\sheight\s*=/.test(t)).filter((t) => !/data-nimg="fill"/.test(t))
if (noSize.length) issues.imgSize.push(`${url} (${noSize.length} img)`)
if (imgs.length && !/fetchpriority="high"/i.test(imgs[0]) && !/<link[^>]+rel="preload"[^>]+as="image"/i.test(head)) issues.lcp.push(url)
if (!/<meta[^>]+property="og:image"/i.test(head)) issues.ogImage.push(url)
const words = main.replace(/<[^>]+>/g, ' ').replace(/&[a-z#0-9]+;/gi, ' ').split(/\s+/).filter((w) => /\p{L}{2,}/u.test(w)).length
if (words < 150) issues.thin.push(`${url} (${words} words)`)
const own = new URL(url).host
const internal = tags(main, /<a\b[^>]*href="([^"#]+)"[^>]*>/gi).filter((t) => {
const href = attr(t, 'href') ?? ''
try { const u = new URL(href, url); return u.host === own && norm(u.pathname) !== norm(new URL(url).pathname) } catch { return false }
})
if (internal.length === 0) issues.noLinks.push(url)
if (multiLocale) {
const alts = tags(head, /<link[^>]+hreflang="[^"]+"[^>]*>/gi).map((t) => ({ lang: attr(t, 'hreflang'), href: attr(t, 'href') }))
if (alts.length === 0) issues.hreflang.push(url)
@@ -161,6 +188,15 @@ if (issues.desc.length) report('WARNING', 'missing meta description', 'fill SEO
if (dupTitles.length) report('WARNING', 'duplicate titles', 'unique meta titles per page', dupTitles)
if (issues.longTitle.length) report('WARNING', 'titles over 65 chars (truncated in results)', 'shorten in the SEO tab', issues.longTitle)
if (issues.favicon.length) report('WARNING', 'no favicon link in head', 'buildIconsMetadata(settings.favicon) in root generateMetadata', issues.favicon.slice(0, 3))
if (issues.xRobots.length) report('ERROR', 'X-Robots-Tag: noindex on pages', 'IPAL_NOINDEX is set in this environment — remove it in production', issues.xRobots.slice(0, 3))
if (issues.h1.length) report('ERROR', 'not exactly one h1', 'one h1 per page — SectionHeader as="h1" only in the first section (AGENT.md §0c)', issues.h1)
if (issues.alt.length) report('ERROR', 'images without alt', 'alt from the Media document; decorative: alt=""', issues.alt)
if (issues.headingSkip.length) report('WARNING', 'heading levels skipped', 'h1 → h2 → h3, no jumps (AGENT.md §0c)', issues.headingSkip)
if (issues.imgSize.length) report('WARNING', 'images without width/height (layout shift)', '<Media> via mediaImageProps (AGENT.md §6.11b)', issues.imgSize)
if (issues.lcp.length) report('WARNING', 'first image not prioritised (LCP)', '<Media priority> on the hero image (AGENT.md §6.11b)', issues.lcp)
if (issues.ogImage.length) report('WARNING', 'no og:image', 'share image in the SEO tab or Site Settings → Default share image', issues.ogImage.slice(0, 5))
if (issues.thin.length) report('WARNING', 'thin pages (< 150 words)', 'add real content from the brief or merge pages (AGENT.md §0c)', issues.thin)
if (issues.noLinks.length) report('WARNING', 'pages without internal links', 'link related pages and contact (AGENT.md §0c)', issues.noLinks)
if (!skipped('jsonld') && issues.jsonLd.length) report('ERROR', 'no JSON-LD structured data', '<JsonLdGraph> WebSite + Organization in [locale]/layout.tsx (AGENT.md §0b.4)', issues.jsonLd.slice(0, 5))
if (!skipped('markdown') && issues.mdAlt.length) report('WARNING', 'no text/markdown alternate link in head', 'createContentHelpers({ markdownAlternate: true }) (AGENT.md §0b.6)', issues.mdAlt.slice(0, 3))
+19 -10
View File
@@ -5,7 +5,7 @@ description: Sets up a new client project on Payload 3 + Next 16 + @intecion/ipa
# ipal-setup
**Cel: OBOWIĄZKOWY KOMPLET z AGENT.md §0b — wszystkie 16 pozycji.** Wszystko
**Cel: OBOWIĄZKOWY KOMPLET z AGENT.md §0b — wszystkie 18 pozycji.** Wszystko
sprawdza etap 11; nie kończysz z brakami (chyba że `ipal-audit-skip` z decyzji klienta).
Kod i szczegóły: `node_modules/@intecion/ipal-kit/docs/dev/PROGRAMISTA.md` §1–2
@@ -27,23 +27,32 @@ tylko, gdy użytkownik o to poprosi. Pełna budowa strony: skill **ipal-site**.
3. **Konfiguracja** — `src/i18n.config.ts` (`as const satisfies I18nConfig`),
`payload.config.ts` wg PROGRAMISTA §2.3: `twoFactor` z **wstrzykniętym**
`payloadTotp`, `whiteLabel: true`, `email: mailAdapter()`, `forms: {…}`,
**`buildR2Storage(['media'], { s3Storage })` zawsze** (bez `R2_*` w dev = dysk lokalny).
`.env.example` z `R2_*`, `IPAL_IP_HEADER`, `NEXT_PUBLIC_SERVER_URL`.
**`buildR2Storage(['media'], { s3Storage })` zawsze** (bez `R2_*` w dev = dysk lokalny),
`indexNow: true`, `consentLog: true`.
`.env.example` z `R2_*`, `IPAL_IP_HEADER`, `NEXT_PUBLIC_SERVER_URL`, `IPAL_NOINDEX` (puste; `1` na stagingu).
4. **Rdzeń** — wspólne pola i prymitywy (`../ipal-block/resources/kod-sekcji.md`), `Pages` (z `buildSummaryField()` — GEO), `Media`
z `normalizeFilenameHook` + `buildOptimizeUploadHook`/`buildOptimizeUploadField` (PROGRAMISTA §2.4, storage.md). Żadnych innych kolekcji.
z `focalPoint: true`, `normalizeFilenameHook`, `buildOptimizeUploadHook`/`buildOptimizeUploadField`,
`buildMediaPlaceholderHook`/`buildMediaPlaceholderField`; prymityw `Media` przez `mediaImageProps`/`videoProps`
(PROGRAMISTA §2.4, storage.md). Żadnych innych kolekcji (`users` wstrzykuje plugin).
5. **Style** — `styles.css` z `@theme` z `DESIGN.md` (jeśli brak — zapytaj o
Impeccable albo załóż neutralne tokeny), `@source` na plugin (AGENT.md §6.11, przykład w `../ipal-block/resources/kod-sekcji.md`).
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 i `Analytics` (PROGRAMISTA §2.8), catch-all z ISR + `generateStaticParams` + `resolveRedirect`,
(`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`,
(z `force-dynamic`), `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`,
`api/mcp/route.ts` (publiczny), `summaryField: 'aiSummary'` w trasach AI; robots
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
wpuszcza boty AI (PROGRAMISTA §2.8, AGENT.md §0b.5–8).
9. **Formularze** — skill **ipal-form** (renderer + akcja raz; formularze w panelu).
9. **Formularze** — skill **ipal-form**: renderer + `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**.
11. **Kontrola kompletu** — `pnpm generate:types`, `pnpm payload generate:importmap`,
**ipal-audit** (pełny) = 0 błędów, w tym sekcja „missing: …” (§0b); po
+3 -2
View File
@@ -25,7 +25,7 @@ między fazami. Przed fazą przejdź tabelę „Przewidujesz” z AGENT.md §0a.
1. Języki strony? (pl + en — jak w briefie)
2. Domena produkcyjna? (placeholder w .env, canonical ustawię po wdrożeniu)
3. Dane firmy: NIP, adres, telefon? ([DO UZUPEŁNIENIA] w panelu)
4. Na jaki adres wysyłać zgłoszenia z formularza? ([DO UZUPEŁNIENIA] w Forms → Emails)
4. Na jaki adres wysyłać zgłoszenia z formularza? (bez tego seed formularza się nie uruchomi — to jedyne pytanie, bez którego nie oddam formularzy)
5. Analityka: ID GA4/GTM/pikseli? (wyłączona do czasu wpisania ID w panelu)
6. Dane R2: bucket, endpoint, klucze, domena mediów? (R2 jest wpięty zawsze; do czasu kluczy media lokalnie w dev)
7. Klucze Turnstile? (testowe w dev; produkcyjne wpiszesz w Site Integrations)
@@ -57,7 +57,8 @@ Każdy blok: schemat ze słownika pól, kompozycja prymitywów, zero tekstu w JS
(`ipal-audit --quick` po każdym bloku — błędy naprawiasz od razu).
## Faza 5 — Formularze → **ipal-form**
Formularze tworzysz w panelu (albo seedem) — kod piszesz raz. **Nigdy** własny
Każdy formularz = seed z `ipal-form/resources/seed-form.template.ts` (pola, potwierdzenie, mail do
firmy **i** potwierdzenie do klienta, każdy język) — kod renderera i akcji piszesz raz. **Nigdy** własny
formularz z polami w JSX, trasa `api/contact`, `nodemailer`, reCAPTCHA (AGENT.md §0b).
## Faza 6 — Treść w panelu, każdy język
+22
View File
@@ -204,3 +204,25 @@ chcesz zachować sprzątanie locale (albo zaimportuj `LOCALE_COOKIE_NAME` i doda
> Mechanizm zgody dla locale jest opisany też od strony i18n:
> [i18n.md](./i18n.md#cookie-locale-a-zgoda-rodo).
## Wersja polityki, wycofanie zgody, rejestr zgód, tabela ciasteczek (1.9.1)
- **Ponowna zgoda po zmianie polityki:** Cookie Settings → *Policy version* (sidebar). Podnieś o 1
po dodaniu narzędzia albo zmianie polityki — każdy odwiedzający zobaczy baner ponownie.
`getConsentTexts` przekazuje wersję do `<ConsentProvider texts>` automatycznie.
- **Wycofanie zgody kasuje ciasteczka narzędzi** (`_ga`, `_ga_*`, `_gid`, `_fbp`, `_gcl_*`, Clarity,
LinkedIn, TikTok, Hotjar…) — także na domenie nadrzędnej (`.klient.pl`), gdzie zapisuje je GA.
Własne ciasteczka projektu: `<ConsentProvider cookieMap={{ marketing: ['_my*'] }}>` (dopisywane do
listy domyślnej, `*` = prefiks).
- **Równy wybór:** `<CookieBanner equalChoice />` — „Odrzuć” wygląda jak „Akceptuj wszystko”
(wymóg UODO/EDPB: odmowa równie łatwa jak zgoda). Domyślnie wyłączone, żeby nie zmieniać wyglądu
istniejących stron; **w nowych projektach włączaj**.
- **Rejestr zgód (dowód zgody, art. 7 ust. 1 RODO):** `ipalKit({ consentLog: true })` +
`<ConsentProvider logEndpoint="/api/ipal/consent">`. Zapisuje losowy identyfikator (ten sam co w
ciasteczku), wybory, wersję polityki i czas — **bez IP i user-agenta**. Kolekcja *Consent records*
(tylko admin), automatyczne czyszczenie po `retentionDays` (domyślnie 1095). Postgres: `migrate:create`.
- **Tabela ciasteczek** dla strony polityki: Cookie Settings → *Cookies* (wypełniana skanem,
skill `ipal-consent-check` → cookie-scan) + `getCookieTable` + `<CookieTable>` z `/rsc`.
- Ciasteczko zgody ma `Secure` na HTTPS.
- Global Privacy Control nie jest potrzebny: w UE wszystko poza niezbędnymi i tak jest domyślnie
wyłączone do czasu zgody.
+62 -19
View File
@@ -120,7 +120,7 @@ import { Pages } from '@/collections/Pages'
import { Media } from '@/collections/Media'
export default buildConfig({
collections: [Pages, Media], // users wbudowane — nie twórz
collections: [Pages, Media], // users wstrzykuje ipalKit (własna tylko dla dodatkowych pól)
email: mailAdapter(), // bez tego maile form-buildera nie wyjdą
plugins: [
ipalKit({
@@ -132,6 +132,8 @@ export default buildConfig({
forms: { redirectRelationships: ['pages'] },
twoFactor: { issuer: 'Nazwa Klienta', plugin: payloadTotp },
whiteLabel: true, // logo/nazwa z Site Settings w panelu
indexNow: true, // publikacja → Bing / ChatGPT Search (produkcja)
consentLog: true, // dowód zgody (RODO art. 7 ust. 1), bez danych osobowych
// adminRoute: '/its', // + przenieś app/(payload)/admin → its
}),
buildR2Storage(['media'], { s3Storage }), // ZAWSZE — R2 przy komplecie R2_* w env, dysk lokalny bez nich
@@ -177,7 +179,10 @@ export default { plugins: { '@tailwindcss/postcss': {} } }
}
```
`fluid.css` to same zmienne `clamp()` (360 → 1280 px, w `rem`) — klasy `text-h1`,
`py-section`, `px-gutter`. Liczby z `DESIGN.md` nadpisujesz w `:root` projektu
`py-section`, `px-gutter`. `fluid-wide.css` — te same zmienne, skala do 1920 px (13″ ≠ 27″);
importujesz jeden z dwóch. Oba mają też zmienne wysokości i szerokości: `--ipal-hero-min-h`,
`--ipal-fs-display-fit`, `--ipal-space-section-fit`, `--ipal-measure`, `--ipal-container`
(AGENT.md §6.11a). Liczby z `DESIGN.md` nadpisujesz w `:root` projektu
(`--ipal-fs-h1: clamp(…)`); formuł nie piszesz od zera.
Bez `@source` komponenty pluginu (baner cookies, Turnstile) są bez stylów.
Kolory komponentów pluginu: `--ipal-primary`, `--ipal-radius` (consent.md).
@@ -209,7 +214,7 @@ import { i18nConfig } from '@/i18n.config'
import { contentConfig } from '@/content.config'
export const {
getCachedPayload, getSettings, getConfiguredLocales, resolveRoute, getEntries,
getCachedPayload, getSettings, getConfiguredLocales, resolveRoute, getEntries, getPageJsonLd,
generatePageMetadata, getNotFoundPage, generateStaticParams, sitemap, robots,
} = createContentHelpers({
config,
@@ -217,6 +222,7 @@ export const {
i18n: i18nConfig,
baseUrl: process.env.NEXT_PUBLIC_SERVER_URL,
markdownAlternate: true, // GEO: <link rel="alternate" type="text/markdown"> w każdej stronie
// pageJsonLd: { faq: (doc) => …mapowanie bloku FAQ na { question, answer }… },
})
```
@@ -225,7 +231,7 @@ export const {
// src/app/(frontend)/[locale]/layout.tsx
import { notFound } from 'next/navigation'
import {
buildOrganizationJsonLd, buildWebSiteJsonLd, getAnalyticsConfig, getConsentTexts, getTurnstileConfig,
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'
@@ -249,7 +255,10 @@ export default async function LocaleLayout({ children, params }: Props) {
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 })] : []
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)
return (
<html lang={locale}>
@@ -257,11 +266,11 @@ export default async function LocaleLayout({ children, params }: Props) {
<body>
<MediaPreconnect />
<JsonLdGraph schemas={schemas} />
<ConsentProvider texts={texts}>
<ConsentProvider texts={texts} logEndpoint="/api/ipal/consent">
<TurnstileProvider siteKey={turnstile.siteKey}> {/* zawsze — sam się wyłącza bez kluczy */}
<main>{children}</main>
</TurnstileProvider>
<CookieBanner />
<CookieBanner equalChoice />
<CookieButton />
<Analytics {...analytics} /> {/* wewnątrz providera; opcja defer — analytics.md */}
</ConsentProvider>
@@ -275,11 +284,11 @@ export default async function LocaleLayout({ children, params }: Props) {
// src/app/(frontend)/[locale]/[[...slug]]/page.tsx — PODWÓJNE nawiasy
import { notFound, permanentRedirect } from 'next/navigation'
import type { Metadata } from 'next'
import { RenderBlocks } from '@intecion/ipal-kit/rsc'
import { JsonLdGraph, RenderBlocks } from '@intecion/ipal-kit/rsc'
import { resolveRedirect } from '@intecion/ipal-kit'
import { i18nConfig } from '@/i18n.config'
import { blockRegistry } from '@/blocks/registry'
import { generatePageMetadata, getCachedPayload, resolveRoute } from '@/lib/content'
import { generatePageMetadata, getCachedPayload, getPageJsonLd, resolveRoute } from '@/lib/content'
export { generateStaticParams } from '@/lib/content' // SSG → <head> synchroniczny
export const revalidate = 3600 // ISR
@@ -302,7 +311,12 @@ export default async function Page({ params }: Args) {
}
const enhanceProps = () => ({ locale }) // locale dla CMSLink w blokach
const doc = route.doc as { layout?: unknown[] }
return <RenderBlocks blocks={doc.layout as never} components={blockRegistry} enhanceProps={enhanceProps} />
return (
<>
<JsonLdGraph schemas={await getPageJsonLd(locale, slug)} /> {/* WebPage/BlogPosting, okruszki, FAQ */}
<RenderBlocks blocks={doc.layout as never} components={blockRegistry} enhanceProps={enhanceProps} />
</>
)
}
```
Opcje `resolveRedirect` (`collections`, `homeSlug`): content.md.
@@ -333,15 +347,17 @@ 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
import { createMarkdownRenderer, markdownResponse } from '@intecion/ipal-kit'
// 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'
const render = createMarkdownRenderer({ content: contentConfig })
export const dynamic = 'force-dynamic'
export async function GET(_req: Request, { params }: { params: Promise<{ locale: string; slug?: string[] }> }) {
const { locale, slug } = await params
return markdownResponse(await render({ payload: await getCachedPayload(), locale, slug }))
}
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 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'
@@ -364,15 +380,16 @@ przez `createContentHelpers({ sitemapStyle })` (seo.md).
```ts
// next.config.ts
import { withPayload } from '@payloadcms/next/withPayload'
import { buildSecurityHeaders } from '@intecion/ipal-kit'
import { buildImagesConfig, buildSecurityHeaders, buildUploadSecurityHeaders } from '@intecion/ipal-kit'
const securityHeaders = buildSecurityHeaders({ hsts: process.env.NODE_ENV === 'production' })
export default withPayload({
images: { ...buildImagesConfig() }, // AVIF/WebP, domena R2 (R2_PUBLIC_URL), cache 31 dni
htmlLimitedBots:
/Googlebot|Google-InspectionTool|Storebot-Google|Bingbot|Yandex|DuckDuckBot|Baiduspider|Screaming Frog|AhrefsBot|SemrushBot/i,
async headers() {
return [{ source: '/:path*', headers: securityHeaders }]
return [{ source: '/:path*', headers: securityHeaders }, ...buildUploadSecurityHeaders()]
},
})
```
@@ -411,6 +428,8 @@ pnpm dev
| `NEXT_PUBLIC_SERVER_URL` | ✅ | publiczny URL (canonical, hreflang, OG); bez niego linki względne |
| `GRAPH_TENANT_ID`, `GRAPH_CLIENT_ID`, `GRAPH_CLIENT_SECRET`, `GRAPH_SENDER` | ⬜ | email przez Microsoft Graph |
| `R2_BUCKET`, `R2_ENDPOINT`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`, `R2_PUBLIC_URL` | ✅ prod | media w Cloudflare R2 — na produkcji zawsze (brak → dysk kontenera, pliki znikają przy redeployu); w dev mogą być puste |
| `IPAL_NOINDEX` | ⬜ | `1` **tylko na stagingu / preview** — cała strona poza Google (robots, meta, nagłówek) |
| `INDEXNOW_KEY` | ⬜ | klucz IndexNow, gdy nie z panelu (Site Integrations → IndexNow generuje sam) |
| `IPAL_IP_HEADER` | ✅ prod | nagłówek z prawdziwym IP dla rate limitu: `cf-connecting-ip` za Cloudflare, `x-forwarded-for` za samym Traefikiem/nginx (forms.md) |
| `NEXT_PUBLIC_TURNSTILE_SITE_KEY`, `TURNSTILE_SECRET_KEY` | ⬜ | fallback, gdy kluczy Turnstile nie ma w panelu |
@@ -542,6 +561,12 @@ Rób po jednej pozycji, buduj, sprawdzaj. Kolejność wg wagi:
| 19 | **1.9.0** — `twoFactor: { issuer }` bez `plugin` | dopisz `plugin: payloadTotp` (fallback z dynamicznym importem usunięty — start kończy się błędem) | security.md |
| 20 | **1.9.0** — IP w akcji formularza liczone ręcznie z `x-forwarded-for` | `clientIp(await headers())` + `IPAL_IP_HEADER` w env produkcji | forms.md |
| 21 | **1.9.0** — media bez R2 na produkcji / brak `buildR2Storage` | wpnij `buildR2Storage(['media'], { s3Storage })`, ustaw `R2_*` | storage.md |
| 22 | **1.9.1** — ręczny `actions.ts` / trasa `md` / brak seeda formularza | `createSubmitAction`, `createMarkdownRoute`, seed z `ipal-form` (mail do firmy + do klienta) | forms.md, content.md |
| 23 | **1.9.1** — `createProxy` bez `markdown: true` | dopisz — inaczej `/md/…` przekierowuje na `/pl/md/…` | content.md |
| 24 | **1.9.1** — JSON-LD strony składany ręcznie | `getPageJsonLd`, `buildNavigationJsonLd`, `sameAsUrls`, `formatOpeningHours` | seo.md |
| 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 |
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`.
@@ -615,6 +640,24 @@ wersji z czerwonymi testami. `prepare` buduje paczkę przy instalacji z gita.
Przed commitem: `pnpm typecheck && pnpm lint && pnpm test:int` (to samo puszcza CI
w `.gitea/workflows/ci.yml` na każdy push i PR).
### 8.1a Testy pluginu
`test/` (poza `src`, nie trafia do `dist`), vitest: `pnpm test:int` (raz), `pnpm test:watch`.
| Rodzaj | Gdzie | Dla czego |
|---|---|---|
| jednostkowe | `test/<moduł>.test.ts` | czyste funkcje: ścieżki, metadata, robots, CSP, parsery (godziny, Markdown), walidacja |
| z atrapą Payloada | `test/helpers.ts` → `fakePayload()` | logika na Local API bez bazy: `submitForm`, Turnstile, MCP, IndexNow |
| integracyjne | `test/integration.test.ts`, `test/drafts.test.ts` — **prawdziwy Payload + SQLite w pamięci** | dostęp (access), hooki, schemat pól, drafty, globale — wszystko, czego atrapa nie odda |
| kontrakt pakietu | `test/exports.test.ts` | każda ścieżka `@intecion/ipal-kit/…` z docs istnieje w `exports` |
Zasady: **każdy naprawiony błąd = test regresyjny** (sprawdź, że na starym kodzie pada);
zero sieci (`vi.spyOn(globalThis, 'fetch')`); env przez `vi.stubEnv` + `unstubAllEnvs`;
`server-only` mockowane (`vi.mock('server-only', () => ({}))`); test zmiany zachowania
widocznej dla projektów → wpis w `docs/CHANGELOG.md`. Skrypty skilli (`audit.sh`,
`seo-check.mjs`, `cookie-scan.mjs`) testujesz na atrapie strony/projektu w scratchpadzie:
pusty projekt (same błędy) i kompletny (0 błędów). CI (`.gitea/workflows/ci.yml`) puszcza
typecheck, lint, testy i build na każdy push.
### 8.2 package.json pluginu
- `"files": ["dist", "docs", "bin"]` — **docs i komenda `ipal-skills` jadą w pakiecie**; agenci w projektach
czytają `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md`. Bez `docs` nie mają nic.
+14
View File
@@ -436,3 +436,17 @@ const label = resolveLocalized(topic.label, locale)
Turnstile wstrzykuje ukryte pole `cf-turnstile-response`. Plugin je toleruje
(nie odrzuca jako `unknown_fields`) — bo sam obsługuje Turnstile. Nie musisz go
filtrować w kliencie.
## 1.9.1 — gotowa akcja, seed formularza, walidacja typów
- **`createSubmitAction({ getCachedPayload, headers })`** z `/server` zastępuje ręczny `actions.ts`:
`export const sendForm = createSubmitAction({ getCachedPayload, headers })` (`headers` z
`next/headers`, wstrzyknięty). Honeypot → `clientIp` → `submitForm` → tekst z Notifications;
wynik `{ success, message, reason?, field? }`.
- **Seed formularza** (`ipal-form/resources/seed-form.template.ts`): pola, potwierdzenie, mail do firmy
(adres z panelu) i potwierdzenie do klienta (`{{email}}`), każdy język, idempotentny. Obowiązkowy.
- **Walidacja po typie pola z panelu:** email = jeden adres (bez `a@x, b@y`, bez CR/LF), select/radio
tylko wartości z panelu, liczby, checkbox `true/false`, obiekty i tablice odrzucane, znaki
sterujące i bidi usuwane. Błąd: `reason: 'validation'`, `kind: 'invalid_format'`, `field`.
- **Dostęp:** zgłoszenia czytają tylko `editor`/`admin` (wcześniej każde konto), usuwa `admin`;
zakładka Emails formularza (adresy odbiorców) ukryta w publicznym `GET /api/forms`.
+11
View File
@@ -322,3 +322,14 @@ Wybrany, bo wrapuje ACCESS CONTROL (TOTP przed dostępem do danych) + forceSetup
(wymuszenie dla wszystkich). Inne pluginy 2FA dla Payload gatują tylko nawigację
/admin — user z hasłem może omijać przez REST/GraphQL/Bearer. @clocklimited chroni
dostęp do danych, nie tylko UI.
## 1.9.1 — wyniki przeglądu bezpieczeństwa
- Drafty nigdy nieopublikowane nie są już dostępne publicznie (`resolveRoute`, Markdown, MCP,
metadata) ani na listach archiwów (`getArchiveEntries`). Podgląd: `resolveRoute({ draft: true })`,
`getArchiveEntries({ draft: true })` w trybie `draftMode()`.
- Linki z CMS: tylko `http(s)`, `mailto`, `tel`, `sms`, `#`, `/` (`safeHref`); `javascript:` i `data:` odrzucane.
- ID analityki walidowane (panel i przed wysłaniem do przeglądarki).
- Zgłoszenia formularzy: odczyt `editor+`; adresy z zakładki Emails niewidoczne publicznie.
- Uploady: `buildUploadSecurityHeaders()` w `next.config.ts` (SVG nie uruchomi skryptu na domenie strony).
- `users`: plugin wstrzykuje kolekcję auth, gdy projekt jej nie ma (role i 2FA zawsze się wpinają).
+34
View File
@@ -1168,3 +1168,37 @@ W markupie projektu oznacz pasujące elementy (np. `className="speakable"` albo
sekcja `.lead` ze streszczeniem). Selektory nietrafiające w nic są ignorowane —
nie wskazuj nawigacji ani boilerplate'u, tylko samodzielny, czytelny tekst.
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`:
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)} />`.
- **`buildNavigationJsonLd({ items: header.navItems, baseUrl, locale, config, homeSlug })`** — nawigacja z
globala nagłówka (linki stron per język, tylko własna domena, bez duplikatów). Inny kształt globala:
`getLink` / `getChildren`.
- **`buildLocalBusinessJsonLd({ type: 'Dentist', openingHours: company.hours, … })`** — `type` dowolny
schema.org; godziny jako tekst redaktora (PL/EN/DE: „Pn-Pt: 8-17, Sob: 9-13, Nd nieczynne”) →
`formatOpeningHours` → `['Mo-Fr 08:00-17:00', 'Sa 09:00-13:00']`. Nieczytelny tekst jest pomijany.
- **Site Settings → sameAs** (profile firmy) → `sameAsUrls(settings)` do Organization/LocalBusiness.
- **Site Settings → Default share image** działa jako obraz OG stron bez własnego (wcześniej ignorowany).
Metadata ma kartę X/Twitter, wymiary i alt obrazu, a wpisy `og:type=article` z datami.
- **Sitemap z obrazami** (`<image:image>`): domyślnie obraz SEO strony; własne źródło:
`createContentHelpers({ sitemapImages: (doc) => [...] })`.
- **IndexNow:** `ipalKit({ indexNow: true })` + trasa `src/app/indexnow-key.txt/route.ts`
(`createIndexNowKeyRoute`). Po publikacji strony/wpisu adresy we wszystkich językach idą do Bing &
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.
- **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`.
## noindex — staging, Markdown, ochrona (1.9.1)
- **`IPAL_NOINDEX=1`** w env stagingu/preview: robots `Disallow: /`, `noindex, nofollow` w meta,
`X-Robots-Tag` w `buildSecurityHeaders`. Nigdy na produkcji (`ipal-seo-check` zgłasza).
- Wersje Markdown (`/md/…`) i pliki llms mają `X-Robots-Tag: noindex`; Markdown dodatkowo
`Link: <html-url>; rel="canonical"` — AI czyta, Google nie widzi duplikatów.
- `buildNoindexField` nie pozwala zaznaczyć noindex na stronie głównej i stronach-archiwach.
- Kiedy noindex: tabela w AGENT.md §0c. Polityki prawne zostają indeksowane domyślnie.
+12
View File
@@ -309,3 +309,15 @@ env, komponent podąża automatycznie.
> NIE hardkoduj `<link rel="preconnect" href="https://media.klient.pl">` ręcznie
> w layoutcie — to zaszywa domenę klienta w kodzie. Użyj MediaPreconnect, który
> bierze ją z env.
## 1.9.1 — szybkość mediów (narzędzia do własnego `<Media>`)
- `mediaImageProps(resource, { sizes, priority, alt })` → propsy `next/image`: wymiary z dokumentu,
`lazy` domyślnie, obraz LCP `preload` + `fetchPriority="high"` + `eager` (Next 16), focal point →
`object-position`, placeholder blur + kolor. `MEDIA_SIZES` — podpowiedzi `sizes`.
- `videoProps(resource, { mode: 'background' | 'player', poster, reducedMotion })`.
- `buildMediaPlaceholderHook()` + `buildMediaPlaceholderField()` w Media — podgląd liczony przy
uploadzie przez `sharp` z configu. Postgres: `migrate:create`.
- `buildImagesConfig()` → `next.config.ts images` (AVIF/WebP, `remotePatterns` z `R2_PUBLIC_URL`).
- `<YouTubeEmbed videoId title playLabel note poster>` z `/client` — iframe po kliknięciu.
- `buildUploadSecurityHeaders()` → sandbox CSP dla `/api/media/file/*` (SVG z uploadu bez skryptów).
+10 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@intecion/ipal-kit",
"version": "1.9.0",
"version": "1.9.1",
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
"license": "MIT",
"repository": {
@@ -38,12 +38,19 @@
"import": "./dist/exports/admin.js",
"types": "./dist/exports/admin.d.ts",
"default": "./dist/exports/admin.js"
}
},
"./env": {
"import": "./dist/exports/env.js",
"types": "./dist/exports/env.d.ts",
"default": "./dist/exports/env.js"
},
"./fluid.css": "./dist/styles/fluid.css",
"./fluid-wide.css": "./dist/styles/fluid-wide.css"
},
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"bin": {
"ipal-skills": "./bin/ipal-skills.mjs"
"ipal-skills": "bin/ipal-skills.mjs"
},
"files": [
"dist",
+1
View File
@@ -62,6 +62,7 @@ export {
export type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js'
export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js'
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 type { TurnstileProps } from '../modules/turnstile/client.js'
+2
View File
@@ -12,6 +12,8 @@ export type {
EnhanceProps,
RenderBlocksProps,
} from '../modules/blocks/index.js'
export { CookieTable } from '../modules/consent/CookieTable.js'
export type { CookieTableLabels } from '../modules/consent/CookieTable.js'
export { RenderRichText } from '../modules/richtext/index.js'
export type { RenderRichTextProps } from '../modules/richtext/index.js'
export { JsonLdGraph } from '../modules/seo/index.js'
+2
View File
@@ -1,5 +1,7 @@
export { sendEmail } from '../modules/email/index.js'
export type { SendEmailArgs, SendEmailResult } from '../modules/email/index.js'
export { createSubmitAction } from '../modules/forms/createSubmitAction.js'
export type { SubmitActionResult } from '../modules/forms/createSubmitAction.js'
export { submitForm } from '../modules/forms/index.js'
export type { SubmitFormArgs, SubmitFormResult } from '../modules/forms/index.js'
/**
+42
View File
@@ -9,6 +9,19 @@ import { CONSENT_CATEGORIES } from '../../modules/consent/categories.js'
* truth. Only the link's visible text lives here (privacyLinkLabel).
*/
export const cookieSettingsFields: Field[] = [
{
name: 'policyVersion',
type: 'number',
admin: {
description:
'Raise by 1 when you add a tool or change the cookie policy — every visitor is asked for consent again.',
position: 'sidebar',
step: 1,
},
defaultValue: 1,
min: 1,
required: true,
},
{
name: 'message',
type: 'textarea',
@@ -65,4 +78,33 @@ export const cookieSettingsFields: Field[] = [
{ name: 'description', type: 'textarea', localized: true },
],
},
{
name: 'cookies',
type: 'array',
admin: {
description:
'Cookies the site uses — shown on the cookie policy page (<CookieTable>). Fill it from a scan: ipal-consent-check → cookie-scan.',
initCollapsed: true,
},
fields: [
{
type: 'row',
fields: [
{ name: 'name', type: 'text', admin: { width: '40%' }, required: true },
{ name: 'provider', type: 'text', admin: { description: 'e.g. Google, this site', width: '30%' } },
{
name: 'category',
type: 'select',
admin: { width: '30%' },
defaultValue: 'necessary',
options: CONSENT_CATEGORIES.map((c) => ({ label: c, value: c })),
required: true,
},
],
},
{ name: 'purpose', type: 'textarea', localized: true },
{ name: 'duration', type: 'text', admin: { description: 'e.g. "2 years", "session"' }, localized: true },
],
labels: { plural: 'Cookies', singular: 'Cookie' },
},
]
@@ -1,5 +1,7 @@
import type { Field } from 'payload'
import { validateAnalyticsId } from '../../../modules/analytics/idFormats.js'
/**
* Analytics / marketing tag IDs. All are PUBLIC (exposed client-side), so no
* read restriction. Google tags (GA4/GTM) use Consent Mode; the rest load only
@@ -13,6 +15,7 @@ export const analyticsFields: Field[] = [
description: 'Google Analytics 4 Measurement ID. (Google — Consent Mode)',
placeholder: 'G-XXXXXXXXXX',
},
validate: validateAnalyticsId('ga4MeasurementId', 'G-XXXXXXXXXX'),
},
{
name: 'gtmContainerId',
@@ -21,6 +24,7 @@ export const analyticsFields: Field[] = [
description: 'Google Tag Manager container ID. (Google — Consent Mode)',
placeholder: 'GTM-XXXXXXX',
},
validate: validateAnalyticsId('gtmContainerId', 'GTM-XXXXXXX'),
},
{
name: 'metaPixelId',
@@ -29,6 +33,7 @@ export const analyticsFields: Field[] = [
description: 'Meta (Facebook) Pixel ID. Loads only after MARKETING consent.',
placeholder: '1234567890123456',
},
validate: validateAnalyticsId('metaPixelId', '1234567890123456'),
},
{
name: 'clarityProjectId',
@@ -37,6 +42,7 @@ export const analyticsFields: Field[] = [
description: 'Microsoft Clarity project ID (heatmaps). Loads only after ANALYTICS consent.',
placeholder: 'abcdefghij',
},
validate: validateAnalyticsId('clarityProjectId', 'abcdefghij'),
},
{
name: 'linkedInPartnerId',
@@ -45,6 +51,7 @@ export const analyticsFields: Field[] = [
description: 'LinkedIn Insight Tag partner ID. Loads only after MARKETING consent.',
placeholder: '1234567',
},
validate: validateAnalyticsId('linkedInPartnerId', '1234567'),
},
{
name: 'tiktokPixelId',
@@ -53,5 +60,6 @@ export const analyticsFields: Field[] = [
description: 'TikTok Pixel ID. Loads only after MARKETING consent.',
placeholder: 'CXXXXXXXXXXXXXXXXXXX',
},
validate: validateAnalyticsId('tiktokPixelId', 'CXXXXXXXXXXXXXXXXXXX'),
},
]
+2
View File
@@ -1,6 +1,7 @@
import type { Field, GlobalConfig } from 'payload'
import { isAdmin } from '../../modules/access/index.js'
import { indexNowFields } from '../../modules/seo/indexNow.js'
import { analyticsFields } from './fields/analytics.js'
import { smtpFields } from './fields/smtp.js'
import { turnstileFields } from './fields/turnstile.js'
@@ -43,6 +44,7 @@ export function buildSiteIntegrations({
{ fields: analyticsFields, label: 'Analytics' },
{ fields: turnstileFields, label: 'Turnstile' },
{ fields: smtpFields, label: 'SMTP' },
{ fields: indexNowFields, label: 'IndexNow' },
...(additionalFields?.length
? [{ fields: additionalFields, label: 'Custom' }]
: []),
@@ -68,6 +68,17 @@ export const generalFields: Field[] = [
},
relationTo: 'media',
},
{
name: 'sameAs',
type: 'array',
admin: {
description:
'Official profiles of this business (Google Business Profile, LinkedIn, Facebook, Wikipedia…). Tells search engines and AI which entity the site belongs to.',
initCollapsed: true,
},
fields: [{ name: 'url', type: 'text', required: true, validate: (v: unknown) => (typeof v === 'string' && /^https?:\/\/\S+$/.test(v)) || 'Full URL, e.g. https://www.linkedin.com/company/acme' }],
labels: { plural: 'Profiles', singular: 'Profile' },
},
{
name: 'favicon',
type: 'upload',
+34 -6
View File
@@ -21,19 +21,24 @@ export type { AnalyticsConfig } from './modules/analytics/index.js'
export { getAnalyticsConfig } from './modules/analytics/index.js'
export {
ACCEPT_ALL_CONSENT,
buildConsentLogCollection,
buildConsentLogEndpoint,
CONSENT_CATEGORIES,
CONSENT_COOKIE,
CONSENT_LOG_SLUG,
CONSENT_MAX_AGE,
CONSENT_VERSION,
DEFAULT_CONSENT,
getConsentTexts,
getCookieTable,
parseConsent,
readConsentRecord,
REJECT_ALL_CONSENT,
serializeConsent,
setDefaultConsent,
updateConsent,
} from './modules/consent/index.js'
export type { ConsentCategory, ConsentState, ConsentTexts } from './modules/consent/index.js'
export type { ConsentCategory, ConsentLogOptions, ConsentState, ConsentTexts, CookieTableRow } from './modules/consent/index.js'
export type { ContentCollectionOption, ContentOption, ResolvedRoute } from './modules/content/index.js'
export {
archiveFieldName,
@@ -41,6 +46,7 @@ export {
buildArchivePath,
buildEntryPath,
createMarkdownRenderer,
createMarkdownRoute,
createSearchRoute,
getArchiveEntries,
listContent,
@@ -93,6 +99,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 { createContentHelpers } from './modules/frontend/index.js'
// Healthcheck route (Coolify/Docker liveness with a real DB round-trip).
export { createHealthRoute } from './modules/health/index.js'
@@ -119,7 +126,7 @@ 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 } from './modules/links/index.js'
export { buildLinkField, buildLinksField, resolveLinkHref, safeHref } from './modules/links/index.js'
export type {
BuildLinkFieldOptions,
BuildLinksFieldOptions,
@@ -131,6 +138,14 @@ export type {
export { createMcpRoute } from './modules/mcp/index.js'
export { buildOptimizeUploadField, buildOptimizeUploadHook, normalizeFilename, normalizeFilenameHook } from './modules/media/index.js'
export type { OptimizeUploadOptions } from './modules/media/index.js'
export {
buildMediaPlaceholderField,
buildMediaPlaceholderHook,
MEDIA_SIZES,
mediaImageProps,
videoProps,
} from './modules/media/index.js'
export type { MediaImageOptions, MediaImageProps, VideoMode, VideoProps } from './modules/media/index.js'
export { getNotificationTexts, NOTIFICATION_FALLBACK, resolveFormMessage } from './modules/notifications/index.js'
export type { FormNotificationTexts, NotificationTexts } from './modules/notifications/index.js'
export type { PagesOption, SystemPageRole } from './modules/pages/index.js'
@@ -145,11 +160,12 @@ export {
} from './modules/payload/index.js'
// Lexical → Markdown (pure, no React) — for AI-readable output.
export { lexicalToMarkdown } from './modules/richtext/index.js'
export { buildSecurityHeaders, buildUploadSecurityHeaders } from './modules/security/index.js'
export { buildSecurityHeaders } from './modules/security/index.js'
export { buildCsp } from './modules/security/index.js'
export type { BuildCspArgs } from './modules/security/index.js'
export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'
export type { OgImage } from './modules/seo/buildMetadata.js'
export type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js'
export {
buildHreflangAlternates,
@@ -159,6 +175,16 @@ export {
slugsAcrossLocales,
} from './modules/seo/index.js'
export type { SiteMetaConfig } from './modules/seo/index.js'
export { collectSiteIndex } from './modules/seo/index.js'
export {
buildIndexNowHook,
createIndexNowKeyRoute,
getIndexNowKey,
INDEXNOW_KEY_ENV,
INDEXNOW_KEY_PATH,
submitToIndexNow,
} from './modules/seo/index.js'
export type { CollectSiteIndexArgs, SiteIndexEntry } from './modules/seo/index.js'
export type { AutoFillMapping, RobotsOptions, RobotsRules, SitemapEntry } from './modules/seo/index.js'
export {
AI_ASSISTANT_BOTS,
@@ -171,20 +197,22 @@ export {
injectAutoFillMeta,
} from './modules/seo/index.js'
export { createLlmsTxtRoute, createManifestHandler, createSitemapRouteHandler } from './modules/seo/index.js'
export { buildIconsMetadata, buildOrganizationJsonLd, validateFaviconField } from './modules/seo/index.js'
export { buildIconsMetadata, buildOrganizationJsonLd, sameAsUrls, validateFaviconField } from './modules/seo/index.js'
export { buildNoindexField } from './modules/seo/index.js'
export { buildSpeakableJsonLd } from './modules/seo/index.js'
export { buildSummaryField } from './modules/seo/index.js'
export { buildBreadcrumbJsonLd, buildSiteNavigationJsonLd, buildWebSiteJsonLd } from './modules/seo/index.js'
export { buildBreadcrumbJsonLd, buildNavigationJsonLd, buildSiteNavigationJsonLd, buildWebSiteJsonLd } from './modules/seo/index.js'
// Local SEO structured data — LocalBusiness (map pack), Service (offering), FAQPage.
export { buildFaqJsonLd, buildLocalBusinessJsonLd, buildServiceJsonLd } from './modules/seo/index.js'
export { buildArticleJsonLd } from './modules/seo/index.js'
export { buildArticleJsonLd, buildWebPageJsonLd, formatOpeningHours } from './modules/seo/index.js'
export { buildLlmsTxt } from './modules/seo/index.js'
export { buildSitemapCss, buildSitemapXml, DEFAULT_SITEMAP_CREDIT, SITEMAP_STYLE_PARAM } from './modules/seo/index.js'
export type { SitemapRouteOptions, SitemapStyleOptions } from './modules/seo/index.js'
export { clientIp, setRateLimitStore } from './modules/shared/rateLimit.js'
export type { ClientIpOptions, RateLimitStore } from './modules/shared/rateLimit.js'
export { buildSlugField, toSlug } from './modules/slug/index.js'
export { buildImagesConfig } from './modules/storage/buildImagesConfig.js'
export type { ImagesConfig } from './modules/storage/buildImagesConfig.js'
export { buildR2Storage } from './modules/storage/index.js'
// Imported from the file, not the turnstile barrel — that one re-exports verify,
// which imports 'server-only'.
+7 -6
View File
@@ -3,6 +3,7 @@ import type { BasePayload } from 'payload'
import type { AnalyticsConfig } from './types.js'
import { getSiteIntegrations } from '../payload/index.js'
import { validAnalyticsId } from './idFormats.js'
/**
* Reads the public analytics / marketing tag IDs from SiteIntegrations,
@@ -12,11 +13,11 @@ import { getSiteIntegrations } from '../payload/index.js'
export async function getAnalyticsConfig(payload: BasePayload): Promise<AnalyticsConfig> {
const integrations = await getSiteIntegrations<AnalyticsConfig>(payload)
return {
clarityProjectId: integrations.clarityProjectId ?? null,
ga4MeasurementId: integrations.ga4MeasurementId ?? null,
gtmContainerId: integrations.gtmContainerId ?? null,
linkedInPartnerId: integrations.linkedInPartnerId ?? null,
metaPixelId: integrations.metaPixelId ?? null,
tiktokPixelId: integrations.tiktokPixelId ?? null,
clarityProjectId: validAnalyticsId('clarityProjectId', integrations.clarityProjectId),
ga4MeasurementId: validAnalyticsId('ga4MeasurementId', integrations.ga4MeasurementId),
gtmContainerId: validAnalyticsId('gtmContainerId', integrations.gtmContainerId),
linkedInPartnerId: validAnalyticsId('linkedInPartnerId', integrations.linkedInPartnerId),
metaPixelId: validAnalyticsId('metaPixelId', integrations.metaPixelId),
tiktokPixelId: validAnalyticsId('tiktokPixelId', integrations.tiktokPixelId),
}
}
+28
View File
@@ -0,0 +1,28 @@
/**
* Formats of the tag IDs typed into Site Integrations. Used twice: as field
* validation in the panel (typos caught on save) and when the IDs are handed to
* the browser (getAnalyticsConfig) — a malformed value from an import or an old
* version is dropped instead of being put into a script URL.
*/
export const ANALYTICS_ID_FORMATS = {
clarityProjectId: /^[a-z0-9]{5,20}$/i,
ga4MeasurementId: /^G-[A-Z0-9]{4,20}$/,
gtmContainerId: /^GTM-[A-Z0-9]{4,12}$/,
linkedInPartnerId: /^\d{3,12}$/,
metaPixelId: /^\d{5,20}$/,
tiktokPixelId: /^[A-Z0-9]{10,30}$/i,
} as const
export type AnalyticsIdField = keyof typeof ANALYTICS_ID_FORMATS
/** The trimmed ID when it matches its format, else null. */
export function validAnalyticsId(field: AnalyticsIdField, value: unknown): null | string {
const v = typeof value === 'string' ? value.trim() : ''
return v && ANALYTICS_ID_FORMATS[field].test(v) ? v : null
}
/** Payload field `validate` for an ID field. */
export const validateAnalyticsId =
(field: AnalyticsIdField, example: string) =>
(value: null | string | undefined): string | true =>
!value?.trim() || validAnalyticsId(field, value) !== null || `Unexpected format — expected something like ${example}`
+29 -2
View File
@@ -2,6 +2,7 @@
import { createContext, type ReactNode, use } from 'react'
import type { ConsentTexts } from './texts.js'
import type { ConsentCookieMap } from './useConsent.js'
import { useConsent } from './useConsent.js'
@@ -9,8 +10,34 @@ type ConsentContextValue = { texts: ConsentTexts } & ReturnType<typeof useConsen
const ConsentContext = createContext<ConsentContextValue | null>(null)
export function ConsentProvider({ children, texts }: { children: ReactNode; texts: ConsentTexts }) {
const consent = useConsent()
type ConsentProviderProps = {
children: ReactNode
/** Extra cookies per category to delete when consent is withdrawn — merged with the built-in list. */
cookieMap?: ConsentCookieMap
/**
* Consent log endpoint (createConsentLogEndpoint, e.g. '/api/ipal/consent'):
* every decision is POSTed — random id, choices, policy version, no personal
* data — so the site can demonstrate consent (GDPR Art. 7(1)). Off when omitted.
*/
logEndpoint?: string
texts: ConsentTexts
}
export function ConsentProvider({ children, cookieMap, logEndpoint, texts }: ConsentProviderProps) {
const consent = useConsent({
cookieMap,
onDecision: logEndpoint
? (record) => {
void fetch(logEndpoint, {
body: JSON.stringify(record),
headers: { 'content-type': 'application/json' },
keepalive: true,
method: 'POST',
}).catch(() => {})
}
: undefined,
version: texts.version,
})
return <ConsentContext value={{ ...consent, texts }}>{children}</ConsentContext>
}
+12 -2
View File
@@ -53,7 +53,17 @@ const strongText =
const mutedText =
'text-[var(--ipal-text-muted,#737373)] dark:text-[var(--ipal-text-muted-dark,#a3a3a3)]'
export function CookieBanner({ classNames }: { classNames?: CookieBannerClassNames } = {}) {
type CookieBannerProps = {
classNames?: CookieBannerClassNames
/**
* Style "Reject" like "Accept all" (primary). Polish and EU regulators (UODO,
* EDPB) expect refusing to be as easy and visible as accepting. Default false
* keeps the existing look; recommended true.
*/
equalChoice?: boolean
}
export function CookieBanner({ classNames, equalChoice = false }: CookieBannerProps = {}) {
const isMounted = useIsMounted()
const { acceptAll, decided, rejectAll, savePreferences, state, texts } = useConsentContext()
const [showSettings, setShowSettings] = useState(false)
@@ -104,7 +114,7 @@ export function CookieBanner({ classNames }: { classNames?: CookieBannerClassNam
<button className={secondaryClass} data-ipal="settings" onClick={() => setShowSettings(true)} type="button">
{texts.buttons.settings}
</button>
<button className={secondaryClass} data-ipal="reject" onClick={rejectAll} type="button">
<button className={equalChoice ? primaryClass : secondaryClass} data-ipal="reject" onClick={rejectAll} type="button">
{texts.buttons.reject}
</button>
<button className={primaryClass} data-ipal="accept" onClick={acceptAll} type="button">
+61
View File
@@ -0,0 +1,61 @@
import type { CookieTableRow } from './getConsentTexts.js'
import type { ConsentTexts } from './texts.js'
export type CookieTableLabels = {
category: string
duration: string
name: string
provider: string
purpose: string
}
type CookieTableProps = {
/** Optional caption above the table. */
caption?: string
/** Category names — pass `texts.categories` from getConsentTexts so they match the banner. */
categories?: ConsentTexts['categories']
/** Classes per element; nothing is styled by default. */
classNames?: Partial<Record<'caption' | 'table' | 'td' | 'th' | 'tr', string>>
/** Column headings in the page's language — from the project (panel field or page content). */
labels: CookieTableLabels
/** From getCookieTable({ payload, locale }) — Cookie Settings → Cookies. */
rows: CookieTableRow[]
}
/**
* The cookie list for the cookie-policy page, straight from the panel — no copy
* pasted into the policy text, so it can't go stale. Plain semantic <table>,
* unstyled: classNames per element, or style it from the page's CSS. Server
* component (no state).
*
* const rows = await getCookieTable({ payload, locale })
* <CookieTable rows={rows} labels={…from the panel…} categories={texts.categories} />
*/
export function CookieTable({ caption, categories, classNames = {}, labels, rows }: CookieTableProps) {
if (rows.length === 0) {return null}
return (
<table className={classNames.table}>
{caption ? <caption className={classNames.caption}>{caption}</caption> : null}
<thead>
<tr className={classNames.tr}>
<th className={classNames.th} scope="col">{labels.name}</th>
<th className={classNames.th} scope="col">{labels.provider}</th>
<th className={classNames.th} scope="col">{labels.category}</th>
<th className={classNames.th} scope="col">{labels.purpose}</th>
<th className={classNames.th} scope="col">{labels.duration}</th>
</tr>
</thead>
<tbody>
{rows.map((row) => (
<tr className={classNames.tr} key={`${row.category}:${row.name}`}>
<td className={classNames.td}><code>{row.name}</code></td>
<td className={classNames.td}>{row.provider ?? ''}</td>
<td className={classNames.td}>{categories?.[row.category]?.title ?? row.category}</td>
<td className={classNames.td}>{row.purpose ?? ''}</td>
<td className={classNames.td}>{row.duration ?? ''}</td>
</tr>
))}
</tbody>
</table>
)
}
+2 -1
View File
@@ -5,4 +5,5 @@ export { CookieBanner } from './CookieBanner.js'
export type { CookieBannerClassNames } from './CookieBanner.js'
export { CookieButton } from './CookieButton.js'
// Client-only consent exports — hook, provider, and UI components.
export { useConsent } from './useConsent.js'
export { DEFAULT_COOKIE_MAP, useConsent } from './useConsent.js'
export type { ConsentCookieMap } from './useConsent.js'
+110
View File
@@ -0,0 +1,110 @@
import type { CollectionConfig, Endpoint, PayloadRequest } from 'payload'
import { isAdmin } from '../access/predicates.js'
import { clientIp, consumeRateLimit } from '../shared/rateLimit.js'
import { CONSENT_CATEGORIES } from './categories.js'
/**
* Consent log — proof of consent (GDPR Art. 7(1): the controller must be able
* to demonstrate it). Each banner decision is stored as: random consent id (the
* same one kept in the visitor's cookie), the choices, the policy version and
* the time. NO IP address, user agent or other personal data — the id alone
* links a record to the browser that holds the cookie.
*
* Opt-in: `ipalKit({ consentLog: true })` adds the collection and the endpoint
* POST /api/ipal/consent; the layout passes `<ConsentProvider logEndpoint="/api/ipal/consent">`.
* Records older than `retentionDays` (default 3 years) are purged automatically.
*/
export const CONSENT_LOG_SLUG = 'consent-records'
export type ConsentLogOptions = {
/** Days a record is kept. Default 1095 (3 years). */
retentionDays?: number
}
export function buildConsentLogCollection(): CollectionConfig {
return {
slug: CONSENT_LOG_SLUG,
access: {
// Written only by the endpoint (Local API); read and pruned by admins.
create: () => false,
delete: ({ req: { user } }) => isAdmin(user),
read: ({ req: { user } }) => isAdmin(user),
update: () => false,
},
admin: {
defaultColumns: ['consentId', 'version', 'createdAt'],
description: 'Proof of cookie consent: random id (also in the visitor cookie), choices, policy version, time. No personal data.',
group: 'Settings',
useAsTitle: 'consentId',
},
fields: [
{ name: 'consentId', type: 'text', index: true, required: true },
{ name: 'version', type: 'number', required: true },
{
name: 'choices',
type: 'group',
fields: CONSENT_CATEGORIES.map((c) => ({ name: c, type: 'checkbox' as const })),
},
],
labels: { plural: 'Consent records', singular: 'Consent record' },
timestamps: true,
}
}
let lastPurge = 0
export function buildConsentLogEndpoint({ retentionDays = 1095 }: ConsentLogOptions = {}): Endpoint {
return {
handler: async (req: PayloadRequest) => {
const limit = await consumeRateLimit({ key: clientIp(req as unknown as Request), max: 20, scope: 'consent' })
if (!limit.ok) {return Response.json({ ok: false }, { status: 429 })}
let body: unknown
try {
body = await (req as unknown as Request).json()
} catch {
return Response.json({ ok: false }, { status: 400 })
}
const b = body as { id?: unknown; state?: Record<string, unknown>; version?: unknown }
const valid =
typeof b.id === 'string' &&
/^[0-9a-f]{16,64}$/.test(b.id) &&
typeof b.version === 'number' &&
Number.isInteger(b.version) &&
b.version >= 1 &&
b.state !== null &&
typeof b.state === 'object' &&
CONSENT_CATEGORIES.every((c) => typeof b.state![c] === 'boolean')
if (!valid) {return Response.json({ ok: false }, { status: 400 })}
try {
await req.payload.create({
collection: CONSENT_LOG_SLUG as never,
data: {
choices: Object.fromEntries(CONSENT_CATEGORIES.map((c) => [c, b.state![c] === true])),
consentId: b.id,
version: b.version,
} as never,
overrideAccess: true,
})
const now = Date.now()
if (now - lastPurge > 24 * 60 * 60 * 1000) {
lastPurge = now
await req.payload.delete({
collection: CONSENT_LOG_SLUG as never,
overrideAccess: true,
where: { createdAt: { less_than: new Date(now - retentionDays * 86_400_000).toISOString() } },
})
}
return Response.json({ ok: true }, { status: 201 })
} catch (err) {
req.payload.logger.error(`[ipal] consent log write failed: ${err instanceof Error ? err.message : String(err)}`)
return Response.json({ ok: false }, { status: 500 })
}
},
method: 'post',
path: '/ipal/consent',
}
}
+33 -1
View File
@@ -6,7 +6,7 @@ import type { ConsentTexts } from './texts.js'
import { resolveLocalized } from '../i18n/resolveLocalized.js'
import { getSystemPagePath } from '../pages/index.js'
import { getGlobal } from '../payload/index.js'
import { CONSENT_CATEGORIES } from './categories.js'
import { CONSENT_CATEGORIES, type ConsentCategory } from './categories.js'
/** English fallback used when the global has no value for a field. */
const FALLBACK: ConsentTexts = {
@@ -39,7 +39,9 @@ const FALLBACK_PRIVACY_LABEL = 'Privacy policy'
type CookieSettingsData = {
buttons?: null | Partial<ConsentTexts['buttons']>
categories?: Array<{ description?: null | string; key: string; title?: null | string }> | null
cookies?: Array<{ category?: null | string; duration?: null | string; name?: null | string; provider?: null | string; purpose?: null | string }> | null
message?: null | string
policyVersion?: null | number
privacyLinkLabel?: null | string
settingsTitle?: null | string
}
@@ -141,5 +143,35 @@ export async function getConsentTexts({
message: g.message || FALLBACK.message,
privacyLink,
settingsTitle: g.settingsTitle || FALLBACK.settingsTitle,
...(typeof g.policyVersion === 'number' && g.policyVersion >= 1 ? { version: Math.trunc(g.policyVersion) } : {}),
}
}
export type CookieTableRow = {
category: ConsentCategory
duration?: string
name: string
provider?: string
purpose?: string
}
/**
* Rows of Cookie Settings → Cookies in one language, for the cookie policy page
* (<CookieTable rows={…}>). Server-side; never throws (empty list).
*/
export async function getCookieTable({ locale, payload }: { locale?: string; payload: BasePayload }): Promise<CookieTableRow[]> {
try {
const g = await getGlobal<CookieSettingsData>(payload, 'cookie-settings', { locale })
return (g.cookies ?? [])
.filter((c) => typeof c.name === 'string' && c.name.trim())
.map((c) => ({
name: c.name!.trim(),
category: (CONSENT_CATEGORIES as readonly string[]).includes(c.category ?? '') ? (c.category as ConsentCategory) : 'necessary',
...(c.provider?.trim() ? { provider: c.provider.trim() } : {}),
...(c.purpose?.trim() ? { purpose: c.purpose.trim() } : {}),
...(c.duration?.trim() ? { duration: c.duration.trim() } : {}),
}))
} catch {
return []
}
}
+6 -1
View File
@@ -8,13 +8,18 @@ export {
REJECT_ALL_CONSENT,
} from './categories.js'
export type { ConsentCategory, ConsentState } from './categories.js'
export { getConsentTexts } from './getConsentTexts.js'
export { buildConsentLogCollection, buildConsentLogEndpoint, CONSENT_LOG_SLUG } from './consentLog.js'
export type { ConsentLogOptions } from './consentLog.js'
export { getConsentTexts, getCookieTable } from './getConsentTexts.js'
export type { CookieTableRow } from './getConsentTexts.js'
export { setDefaultConsent, updateConsent } from './googleConsent.js'
export {
CONSENT_COOKIE,
CONSENT_MAX_AGE,
CONSENT_VERSION,
newConsentId,
parseConsent,
readConsentRecord,
serializeConsent,
} from './storage.js'
export type { ConsentTexts } from './texts.js'
+26 -8
View File
@@ -3,41 +3,59 @@ import type { ConsentState } from './categories.js'
import { CONSENT_CATEGORIES, DEFAULT_CONSENT } from './categories.js'
/**
* Consent persistence in a cookie. Stored with a version so we can invalidate
* old consents when the policy changes, and a timestamp (GDPR: consent must be
* dated). Readable both client-side (banner) and server-side (script gating).
* Consent persistence in a cookie. Stored with a version so old consents can be
* invalidated when the policy changes (Cookie Settings → Policy version in the
* panel), a timestamp (GDPR: consent must be dated) and a random id that links
* the visitor's choice to the optional server-side consent record. Readable both
* client-side (banner) and server-side (script gating, proxy).
*/
export const CONSENT_COOKIE = 'cookie-consent'
/** Default policy version — the panel's Cookie Settings → Policy version overrides it. */
export const CONSENT_VERSION = 1
export const CONSENT_MAX_AGE = 60 * 60 * 24 * 180 // 180 days
type StoredConsent = {
/** Random id of this decision (no personal data) — matches the consent record. */
id?: string
state: ConsentState
timestamp: string
version: number
}
export function serializeConsent(state: ConsentState): string {
/** Random id for a consent decision. */
export function newConsentId(): string {
const bytes = new Uint8Array(12)
globalThis.crypto.getRandomValues(bytes)
return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')
}
export function serializeConsent(state: ConsentState, version: number = CONSENT_VERSION, id?: string): string {
const payload: StoredConsent = {
...(id ? { id } : {}),
state,
timestamp: new Date().toISOString(),
version: CONSENT_VERSION,
version,
}
return encodeURIComponent(JSON.stringify(payload))
}
export function parseConsent(raw: string | undefined): ConsentState | null {
/** Full stored record (id, timestamp, version) — null when missing, unreadable or from another policy version. */
export function readConsentRecord(raw: string | undefined, version: number = CONSENT_VERSION): ({ state: ConsentState } & StoredConsent) | null {
if (!raw) {return null}
try {
const parsed = JSON.parse(decodeURIComponent(raw)) as StoredConsent
if (parsed.version !== CONSENT_VERSION) {return null}
if (parsed.version !== version) {return null}
const state = { ...DEFAULT_CONSENT }
for (const cat of CONSENT_CATEGORIES) {
if (typeof parsed.state?.[cat] === 'boolean') {state[cat] = parsed.state[cat]}
}
state.necessary = true
return state
return { ...parsed, state }
} catch {
return null
}
}
export function parseConsent(raw: string | undefined, version: number = CONSENT_VERSION): ConsentState | null {
return readConsentRecord(raw, version)?.state ?? null
}
+2
View File
@@ -13,4 +13,6 @@ export type ConsentTexts = {
/** null = no privacy-policy link shown */
privacyLink: { href: string; label: string } | null
settingsTitle: string
/** Policy version from the panel — a stored consent from another version asks again. */
version?: number
}
+81 -25
View File
@@ -1,69 +1,125 @@
'use client'
import { useCallback, useEffect, useState } from 'react'
import { useCallback, useEffect, useMemo, useState } from 'react'
import type { ConsentCategory, ConsentState } from './categories.js'
import { LOCALE_COOKIE_NAME } from '../i18n/index.js'
import { ACCEPT_ALL_CONSENT, DEFAULT_CONSENT, REJECT_ALL_CONSENT } from './categories.js'
import { updateConsent } from './googleConsent.js'
import { CONSENT_COOKIE, CONSENT_MAX_AGE, parseConsent, serializeConsent } from './storage.js'
import { CONSENT_COOKIE, CONSENT_MAX_AGE, CONSENT_VERSION, newConsentId, readConsentRecord, serializeConsent } from './storage.js'
export type ConsentCookieMap = Partial<Record<ConsentCategory, string[]>>
/**
* Cookies to delete when consent for a category is withdrawn. Keyed by
* category. The plugin knows about its own functional cookie (locale); clients
* can extend this via the `cookieMap` arg to useConsent if they set their own.
* Cookies deleted when consent for a category is withdrawn (GDPR: withdrawing
* must stop the processing). `name*` matches a prefix (`_ga_*` → _ga_ABC123).
* Covers the plugin's own functional cookie and the tools Analytics can load;
* projects add theirs through <ConsentProvider cookieMap> (merged, not replaced).
*/
const DEFAULT_COOKIE_MAP: Partial<Record<ConsentCategory, string[]>> = {
export const DEFAULT_COOKIE_MAP: ConsentCookieMap = {
analytics: ['_ga', '_ga_*', '_gid', '_gat*', '_clck', '_clsk', 'CLID', '_hj*'],
functional: [LOCALE_COOKIE_NAME],
marketing: ['_fbp', '_fbc', '_gcl_*', '_ttp', 'li_fat_id', '_uetsid', '_uetvid'],
}
/** Expire a cookie now, across the whole site. */
function mergeCookieMaps(extra?: ConsentCookieMap): ConsentCookieMap {
if (!extra) {return DEFAULT_COOKIE_MAP}
const out: ConsentCookieMap = { ...DEFAULT_COOKIE_MAP }
for (const [cat, names] of Object.entries(extra) as [ConsentCategory, string[]][]) {
out[cat] = [...new Set([...(out[cat] ?? []), ...names])]
}
return out
}
/** Names of cookies currently set that match a pattern (`name` or prefix `name*`). */
function matchingCookies(pattern: string): string[] {
const names = document.cookie.split('; ').map((c) => c.split('=')[0]).filter(Boolean)
return pattern.endsWith('*') ? names.filter((n) => n.startsWith(pattern.slice(0, -1))) : names.filter((n) => n === pattern)
}
/**
* Expire a cookie on this host AND every parent domain — GA, Meta and others
* set theirs on the registrable domain (.acme.pl), which a host-only delete
* leaves behind.
*/
function deleteCookie(name: string) {
document.cookie = `${name}=;path=/;max-age=0;samesite=lax`
const parts = location.hostname.split('.')
const domains = [''] // host-only
for (let i = 0; i < parts.length - 1; i++) {domains.push(`;domain=.${parts.slice(i).join('.')}`)}
for (const domain of domains) {document.cookie = `${name}=;path=/;max-age=0;samesite=lax${domain}`}
}
export function useConsent(
cookieMap: Partial<Record<ConsentCategory, string[]>> = DEFAULT_COOKIE_MAP,
) {
type UseConsentOptions = {
/** Extra cookies per category to delete on withdrawal — merged with DEFAULT_COOKIE_MAP. */
cookieMap?: ConsentCookieMap
/**
* Called after every decision with the consent id and choices — e.g. POST to
* the consent log (createConsentLogEndpoint). Never blocks the banner.
*/
onDecision?: (record: { id: string; state: ConsentState; version: number }) => void
/** Policy version from the panel (Cookie Settings). A stored consent from another version asks again. */
version?: number
}
export function useConsent(options: ConsentCookieMap | UseConsentOptions = {}) {
// Backwards compatible: the old signature took the cookie map directly.
const opts: UseConsentOptions =
'cookieMap' in options || 'version' in options || 'onDecision' in options
? (options)
: { cookieMap: options as ConsentCookieMap }
const version = opts.version ?? CONSENT_VERSION
// Merge once per distinct map (props may pass a new object each render).
const cookieMapKey = JSON.stringify(opts.cookieMap ?? null)
const cookieMap = useMemo(() => mergeCookieMaps(opts.cookieMap), [cookieMapKey])
const { onDecision } = opts
const [state, setState] = useState<ConsentState>(DEFAULT_CONSENT)
const [decided, setDecided] = useState(false)
const [consentId, setConsentId] = useState<string | undefined>(undefined)
useEffect(() => {
const raw = document.cookie
.split('; ')
.find((c) => c.startsWith(`${CONSENT_COOKIE}=`))
?.split('=')[1]
const parsed = parseConsent(raw)
if (parsed) {
setState(parsed)
const record = readConsentRecord(raw, version)
if (record) {
setState(record.state)
setDecided(true)
setConsentId(record.id)
}
}, [])
}, [version])
const persist = useCallback(
(next: ConsentState) => {
// Withdrawal cleanup: for any category flipping true → false, delete the
// cookies tied to it. GDPR: withdrawing consent must stop the processing,
// so a functional cookie (e.g. locale) written under consent has to go when
// that consent is revoked. Uses the current `state` as the previous value.
// cookies tied to it. GDPR: withdrawing consent must stop the processing.
for (const cat of Object.keys(cookieMap) as ConsentCategory[]) {
const wasGranted = state[cat] === true
const nowDenied = next[cat] !== true
if (wasGranted && nowDenied) {
for (const name of cookieMap[cat] ?? []) {deleteCookie(name)}
if (state[cat] === true && next[cat] !== true) {
for (const pattern of cookieMap[cat] ?? []) {
for (const name of matchingCookies(pattern)) {deleteCookie(name)}
}
}
}
document.cookie = `${CONSENT_COOKIE}=${serializeConsent(next)};path=/;max-age=${CONSENT_MAX_AGE};samesite=lax`
const id = consentId ?? newConsentId()
const secure = location.protocol === 'https:' ? ';secure' : ''
document.cookie = `${CONSENT_COOKIE}=${serializeConsent(next, version, id)};path=/;max-age=${CONSENT_MAX_AGE};samesite=lax${secure}`
setState(next)
setDecided(true)
setConsentId(id)
// Tell Google right away. Tags are already on the page holding whatever
// defaults Analytics set at load; without this update they keep them for
// the rest of the session and never write their cookies — the banner would
// look like it worked while nothing changed.
updateConsent(next)
try {
onDecision?.({ id, state: next, version })
} catch {
// a logging hook must never break the banner
}
},
[state, cookieMap],
[state, consentId, version, onDecision, cookieMap],
)
const acceptAll = useCallback(() => persist(ACCEPT_ALL_CONSENT), [persist])
@@ -75,5 +131,5 @@ export function useConsent(
)
const reopen = useCallback(() => setDecided(false), [])
return { acceptAll, decided, rejectAll, reopen, savePreferences, state }
return { acceptAll, consentId, decided, rejectAll, reopen, savePreferences, state }
}
+66 -2
View File
@@ -6,11 +6,21 @@ import { blocksToMarkdown } from './blocksToMarkdown.js'
import { resolveRoute } from './resolveRoute.js'
type CreateMarkdownRendererArgs = {
/**
* Absolute origin. With it the frontmatter carries `url:` — the canonical page
* address an assistant should cite (instead of the /md/… mirror).
*/
baseUrl?: string
/** Pages collection. Default 'pages'. */
collection?: string
/**
* i18n config — only to know a single-locale site has no /{locale} prefix in
* its URLs (for `url:`). Omit on multilingual sites if you like.
*/
config?: { locales: readonly unknown[] }
/** Archive-backed collections, same value as the plugin option (optional). */
content?: ContentOption
/** Prepend a YAML frontmatter block (title/description/locale). Default true. */
/** Prepend a YAML frontmatter block (title, description, url, updated, locale). Default true. */
frontmatter?: boolean
/** Field holding the block layout. Default 'layout'. */
layoutField?: string
@@ -31,6 +41,7 @@ type DocShape = {
[key: string]: unknown
meta?: { description?: null | string } | null
title?: null | string
updatedAt?: string
}
function yamlEscape(v: string): string {
@@ -62,7 +73,9 @@ function yamlEscape(v: string): string {
*/
export function createMarkdownRenderer(args: CreateMarkdownRendererArgs = {}) {
const {
baseUrl,
collection = 'pages',
config,
content,
frontmatter = true,
layoutField = 'layout',
@@ -92,6 +105,9 @@ export function createMarkdownRenderer(args: CreateMarkdownRendererArgs = {}) {
const fm = ['---', `locale: ${locale}`]
if (title) {fm.push(`title: ${yamlEscape(title)}`)}
if (description) {fm.push(`description: ${yamlEscape(description)}`)}
const url = canonicalOf(baseUrl, config, locale, slug)
if (url) {fm.push(`url: ${url}`)}
if (typeof doc.updatedAt === 'string') {fm.push(`updated: ${doc.updatedAt.slice(0, 10)}`)}
fm.push('---')
parts.push(fm.join('\n'))
}
@@ -109,7 +125,7 @@ export function createMarkdownRenderer(args: CreateMarkdownRendererArgs = {}) {
* Wraps a Markdown string in a `text/markdown` Response, or a 404 when null.
* Uses the global Response — no next/server import.
*/
export function markdownResponse(md: null | string): Response {
export function markdownResponse(md: null | string, options: { canonical?: string } = {}): Response {
if (md == null) {
return new Response('Not found', { headers: { 'content-type': 'text/plain' }, status: 404 })
}
@@ -117,7 +133,55 @@ export function markdownResponse(md: null | string): Response {
headers: {
'cache-control': 'public, max-age=0, s-maxage=3600, stale-while-revalidate=86400',
'content-type': 'text/markdown; charset=utf-8',
// A mirror of an HTML page: AI agents read it, search engines must not
// index it as a duplicate — and should credit the HTML page instead.
'x-robots-tag': 'noindex',
...(options.canonical ? { link: `<${options.canonical}>; rel="canonical"` } : {}),
},
status: 200,
})
}
/** Canonical HTML URL of a Markdown page — same rule as the frontmatter `url:`. */
function canonicalOf(baseUrl: string | undefined, config: { locales: readonly unknown[] } | undefined, locale: string, slug?: string[]) {
if (!baseUrl) {return undefined}
const segments = config?.locales.length === 1 ? (slug ?? []) : [locale, ...(slug ?? [])]
return `${baseUrl.replace(/\/$/, '')}/${segments.join('/')}`.replace(/\/$/, '')
}
type MarkdownRouteContext = { params: Promise<{ locale: string; slug?: string[] }> }
/**
* The whole Markdown route in one call — same options as createMarkdownRenderer
* plus `getCachedPayload`:
*
* // src/app/md/[locale]/[[...slug]]/route.ts
* import { createMarkdownRoute } from '@intecion/ipal-kit'
* import { getCachedPayload } from '@/lib/content'
* import { contentConfig } from '@/content.config'
* import { i18nConfig } from '@/i18n.config'
* export const dynamic = 'force-dynamic'
* export const { GET } = createMarkdownRoute({ getCachedPayload, content: contentConfig,
* config: i18nConfig, baseUrl: process.env.NEXT_PUBLIC_SERVER_URL })
*
* 404 for unknown/unpublished pages; a database error returns a generic 503
* (details only in the server log).
*/
export function createMarkdownRoute(
args: { getCachedPayload: () => Promise<BasePayload> } & CreateMarkdownRendererArgs,
): { GET: (req: Request, ctx: MarkdownRouteContext) => Promise<Response> } {
const { getCachedPayload, ...rendererArgs } = args
const render = createMarkdownRenderer(rendererArgs)
return {
GET: async (_req, { params }) => {
try {
const { slug, locale } = await params
const md = await render({ slug, locale, payload: await getCachedPayload() })
return markdownResponse(md, { canonical: canonicalOf(rendererArgs.baseUrl, rendererArgs.config, locale, slug) })
} catch (err) {
console.warn('[ipal] createMarkdownRoute: render failed:', err)
return new Response('Service unavailable', { headers: { 'content-type': 'text/plain' }, status: 503 })
}
},
}
}
+14 -4
View File
@@ -15,6 +15,8 @@ type GetArchiveEntriesArgs = {
collection: string
/** Relationship depth. Defaults to 1 — enough for a cover image. */
depth?: number
/** Preview (draftMode): include unpublished entries and latest drafts. Default false. */
draft?: boolean
locale: string
/** 1-based. Values below 1 are clamped. */
page?: number
@@ -30,9 +32,10 @@ type GetArchiveEntriesArgs = {
/**
* Fetches one page of a collection's entries for an archive listing.
*
* Only published documents are returned when the collection has drafts enabled;
* Payload's `where` on `_status` is left to the caller, since a collection
* without drafts has no such field.
* Only published documents are returned when the collection has drafts enabled
* (the `_status` filter is added automatically — only then, since a collection
* without drafts has no such field and querying it would throw). Pass
* `draft: true` for a preview.
*
* Returns pagination facts rather than markup — the listing itself belongs to
* the client (as a block on the archive page, most likely), because how a list
@@ -41,6 +44,7 @@ type GetArchiveEntriesArgs = {
export async function getArchiveEntries<T = Record<string, unknown>>({
collection,
depth = 1,
draft = false,
locale,
page = 1,
payload,
@@ -48,14 +52,20 @@ export async function getArchiveEntries<T = Record<string, unknown>>({
sort = '-createdAt',
where,
}: GetArchiveEntriesArgs): Promise<ArchiveEntries<T>> {
const versions = payload.collections?.[collection as never]?.config?.versions as { drafts?: unknown } | false | undefined
const hasDrafts = Boolean(versions && versions.drafts)
const published = !draft && hasDrafts ? { _status: { equals: 'published' } } : undefined
const fullWhere = published && where ? { and: [published, where] } : (published ?? where)
const result = await payload.find({
collection: collection as never,
depth,
draft,
limit: perPage,
locale: locale as never,
page: Math.max(1, page),
sort,
...(where ? { where: where as never } : {}),
...(fullWhere ? { where: fullWhere as never } : {}),
})
return {
+1 -1
View File
@@ -1,6 +1,6 @@
export { buildArchiveFields } from './archiveFields.js'
export { blocksToMarkdown } from './blocksToMarkdown.js'
export { createMarkdownRenderer, markdownResponse } from './createMarkdownRenderer.js'
export { createMarkdownRenderer, createMarkdownRoute, markdownResponse } from './createMarkdownRenderer.js'
export { createSearchRoute } from './createSearchRoute.js'
export { getArchiveEntries } from './getArchiveEntries.js'
export type { ArchiveEntries } from './getArchiveEntries.js'
+25 -3
View File
@@ -31,6 +31,12 @@ export type ResolvedRoute =
type ResolveRouteArgs = {
content?: ContentOption
/**
* Preview (Next draftMode): return the latest draft instead of the published
* version, and resolve never-published pages. Default false — public
* requests only ever see published content.
*/
draft?: boolean
locale: string
/** Page number from the query string (?page=2). Defaults to 1. */
page?: number
@@ -72,8 +78,20 @@ type ResolveRouteArgs = {
* make canonical and hreflang ambiguous (the same entry reachable under several
* URLs).
*/
/**
* Payload's `find` returns never-published documents from the main collection
* (with `_status: 'draft'`) unless asked otherwise — public routing must drop
* them, or an unpublished page is reachable by its URL.
*/
function isPublic(doc: unknown, draft: boolean): boolean {
if (draft || !doc || typeof doc !== 'object') {return Boolean(doc)}
const status = (doc as { _status?: unknown })._status
return status === undefined || status === null || status === 'published'
}
export async function resolveRoute({
content,
draft = false,
locale,
page = 1,
pagesSlug = 'pages',
@@ -107,10 +125,11 @@ export async function resolveRoute({
id: homepageId,
collection: pagesSlug,
depth: 2,
draft,
locale: locale as never,
})
return doc ? { type: 'home', doc: doc as Record<string, unknown> } : null
return doc && isPublic(doc, draft) ? { type: 'home', doc: doc as Record<string, unknown> } : null
}
const [first, ...rest] = segments
@@ -122,6 +141,7 @@ export async function resolveRoute({
const archiveDoc = archive as ArchivePage
if (archiveDoc.slug !== first) {continue}
if (!isPublic(archiveDoc, draft)) {return null}
// /pl/artykuly → the archive page itself.
if (rest.length === 0) {
@@ -139,12 +159,13 @@ export async function resolveRoute({
const found = await payload.find({
collection: collection.slug as never,
depth: 2,
draft,
limit: 1,
locale: locale as never,
where: { slug: { equals: rest[0] } },
})
const entry = found.docs[0]
if (!entry) {return null}
if (!entry || !isPublic(entry, draft)) {return null}
return {
type: 'entry',
@@ -162,12 +183,13 @@ export async function resolveRoute({
const found = await payload.find({
collection: pagesSlug as never,
depth: 2,
draft,
limit: 1,
locale: locale as never,
where: { slug: { equals: segments.join('/') } },
})
const doc = found.docs[0]
if (!doc) {return null}
if (!doc || !isPublic(doc, draft)) {return null}
// The page assigned as 404 in System Pages must not be reachable as a normal
// 200 URL (/pl/strona-nie-znaleziona) — that's a soft-404 / duplicate. Treat
+92
View File
@@ -0,0 +1,92 @@
import 'server-only'
import type { BasePayload } from 'payload'
import type { ClientIpOptions } from '../shared/rateLimit.js'
import type { SubmitFormArgs, SubmitFormResult } from './submitForm.js'
import { getNotificationTexts } from '../notifications/getNotificationTexts.js'
import { resolveFormMessage } from '../notifications/resolveFormMessage.js'
import { clientIp } from '../shared/rateLimit.js'
import { HONEYPOT_FIELD, isHoneypotTripped } from './honeypot.js'
import { submitForm } from './submitForm.js'
type CreateSubmitActionArgs = {
/** Optional: IP options (default IPAL_IP_HEADER env / clientIp defaults). */
clientIp?: ClientIpOptions
getCachedPayload: () => Promise<BasePayload>
/**
* `headers` from 'next/headers', INJECTED (the plugin never imports next/*,
* same pattern as NextResponse in createProxy). Called inside the action only.
*/
headers: () => Headers | Promise<Headers>
/** Honeypot field name. Default HONEYPOT_FIELD. */
honeypotField?: string
} & Pick<SubmitFormArgs, 'consentFieldName' | 'maxPerMinute' | 'turnstileOnConfigError'>
export type SubmitActionResult = {
field?: string
/** Text for the visitor, from Notifications in this locale. */
message: string
/** Why it failed — for the renderer to mark a field (`field`) or reset Turnstile. */
reason?: Exclude<SubmitFormResult, { success: true }>['reason']
success: boolean
}
/**
* The one server action every panel form posts to — honeypot → client IP →
* submitForm (rate limit, Turnstile, schema validation, GDPR consent, storage)
* → the visitor message from Notifications in the page's locale.
*
* // src/app/(frontend)/[locale]/actions.ts
* 'use server'
* import { headers } from 'next/headers'
* import { createSubmitAction } from '@intecion/ipal-kit/server'
* import { getCachedPayload } from '@/lib/content'
* export const sendForm = createSubmitAction({ getCachedPayload, headers })
*
* Signature matches the ipal-form FormRenderer: `sendForm(formId, locale, values,
* turnstileToken?)` — bind formId and locale in the block (`sendForm.bind(null, id, locale)`).
* A tripped honeypot gets a fake success and stores nothing.
*/
export function createSubmitAction({
clientIp: ipOptions,
consentFieldName,
getCachedPayload,
headers,
honeypotField = HONEYPOT_FIELD,
maxPerMinute,
turnstileOnConfigError,
}: CreateSubmitActionArgs) {
return async function sendForm(
formId: string,
locale: string,
values: Record<string, unknown>,
turnstileToken?: string,
): Promise<SubmitActionResult> {
const payload = await getCachedPayload()
const texts = (await getNotificationTexts({ locale, payload })).form
const data = values && typeof values === 'object' ? values : {}
if (isHoneypotTripped(data, honeypotField)) {return { message: texts.success, success: true }}
const { [honeypotField]: _honeypot, ...fields } = data
const ip = clientIp(await headers(), ipOptions) || undefined
const result = await submitForm({
consentFieldName,
data: fields,
formId: String(formId),
ip,
maxPerMinute,
payload,
turnstileOnConfigError,
turnstileToken: typeof turnstileToken === 'string' ? turnstileToken.trim() || undefined : undefined,
})
const message = resolveFormMessage(result, texts)
if (result.success) {return { message, success: true }}
return {
message,
reason: result.reason,
success: false,
...('field' in result && result.field ? { field: result.field } : {}),
}
}
}
+33 -2
View File
@@ -1,11 +1,38 @@
import type { Plugin } from 'payload'
import type { Field, Plugin } from 'payload'
import { formBuilderPlugin } from '@payloadcms/plugin-form-builder'
import type { FormsOption } from './types.js'
import { hasMinimumRole, isAdmin } from '../access/predicates.js'
type AccessArgs = { req: { user?: unknown } }
/** REST/GraphQL: only logged-in users. Local API (submitForm) is unaffected. */
const submissionsCreateAccess = ({ req }: { req: { user?: unknown } }) => Boolean(req.user)
const submissionsCreateAccess = ({ req }: AccessArgs) => Boolean(req.user)
/**
* Submissions are visitors' personal data: editors and admins only. The
* form-builder default lets ANY account of the admin collection read them —
* including a plain 'user' from an open sign-up.
*/
const submissionsReadAccess = ({ req }: AccessArgs) => hasMinimumRole(req.user as never, 'editor')
const submissionsDeleteAccess = ({ req }: AccessArgs) => isAdmin(req.user as never)
/**
* Forms stay publicly readable (their fields render the form), but the Emails
* tab — recipient addresses, templates — is for logged-in staff only, so
* GET /api/forms doesn't hand out the company's inboxes to spammers.
*/
function hideEmails(fields: Field[]): Field[] {
return fields.map((field) =>
'name' in field && field.name === 'emails'
? ({
...field,
access: { ...(field as { access?: object }).access, read: ({ req }: AccessArgs) => Boolean(req.user) },
} as Field)
: field,
)
}
/**
* Configures @payloadcms/plugin-form-builder from IPAL's FormsOption.
@@ -48,12 +75,16 @@ export function buildFormsPlugin(forms: FormsOption): Plugin {
labels: { plural: 'Forms', singular: 'Form' },
...forms.formOverrides,
admin: { ...group, ...forms.formOverrides?.admin },
fields: ({ defaultFields }) =>
hideEmails(forms.formOverrides?.fields ? forms.formOverrides.fields({ defaultFields }) : defaultFields),
},
formSubmissionOverrides: {
labels: { plural: 'Submissions', singular: 'Submission' },
...forms.formSubmissionOverrides,
access: {
create: submissionsCreateAccess,
delete: submissionsDeleteAccess,
read: submissionsReadAccess,
...forms.formSubmissionOverrides?.access,
},
admin: { ...group, defaultColumns: ['form', 'createdAt'], ...forms.formSubmissionOverrides?.admin },
+1 -1
View File
@@ -61,7 +61,7 @@ export type SubmitFailure =
/** The offending field's name, when one field is at fault. */
field?: string
/** What was wrong with it. */
kind?: 'required' | 'too_long' | 'unknown_fields'
kind?: 'invalid_format' | 'required' | 'too_long' | 'unknown_fields'
reason: 'validation'
success: false
}
+64 -3
View File
@@ -5,6 +5,8 @@ type FormField = {
blockType?: string
label?: string
name?: string
/** select / radio choices defined in the panel. */
options?: { value?: unknown }[] | null
required?: boolean | null
}
@@ -24,7 +26,7 @@ export type FormValidationResult =
| {
/** Offending field, when a single field is at fault. */
field?: string
kind: 'required' | 'too_long' | 'unknown_fields'
kind: 'invalid_format' | 'required' | 'too_long' | 'unknown_fields'
ok: false
reason: 'invalid'
}
@@ -47,6 +49,60 @@ const CAPTCHA_KEYS = new Set(['cf-turnstile-response', 'g-recaptcha-response'])
/** Hard ceiling on a single field's length, independent of the form config. */
const MAX_FIELD_LENGTH = 5000
/**
* ONE address, nothing else. The form-builder can send a confirmation to
* `{{email}}`, so a value like "[email protected], [email protected]" or one with a line break would
* turn the site into a spam relay (and CR/LF into header injection). Commas,
* semicolons, whitespace and angle brackets are rejected outright.
*/
const EMAIL = /^[^\s@,;<>"()[\]\\]+@[^\s"(),;<>@[\\\]][^\s"(),.;<>@[\\\]]*\.[^\s"(),;<>@[\\\]]{2,}$/
const MAX_EMAIL_LENGTH = 254
// Control characters except tab and line breaks (U+0000–U+001F, U+007F), plus
// bidi overrides that can disguise text in the admin panel and e-mails.
// 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-checks one value against its field's block type, as defined in the
* panel, and normalizes it. Anything not a plain value for that type is
* rejected — a hand-crafted request can't smuggle objects, extra recipients or
* values outside a select's options.
*/
function checkValue(field: FormField, value: unknown): Checked {
if (value === undefined || value === null || value === '') {return { value }}
switch (field.blockType) {
case 'checkbox':
return typeof value === 'boolean' ? { value } : { error: 'invalid_format' }
case 'email': {
if (typeof value !== 'string') {return { error: 'invalid_format' }}
const email = value.trim()
return email.length <= MAX_EMAIL_LENGTH && EMAIL.test(email) ? { value: email } : { error: 'invalid_format' }
}
case 'number': {
const n = typeof value === 'number' ? value : typeof value === 'string' && value.trim() !== '' ? Number(value) : NaN
return Number.isFinite(n) ? { value: n } : { error: 'invalid_format' }
}
case 'radio':
case 'select': {
if (typeof value !== 'string' && typeof value !== 'number') {return { error: 'invalid_format' }}
const allowed = (field.options ?? []).map((o) => String(o?.value))
// No options configured → nothing to compare against; still a plain value.
return allowed.length === 0 || allowed.includes(String(value)) ? { value } : { error: 'invalid_format' }
}
case 'textarea':
return typeof value === 'string' ? { value: value.replace(CONTROL, '') } : { error: 'invalid_format' }
default:
// text, country, state and custom blocks: one line of plain text.
if (typeof value === 'number') {return { value }}
return typeof value === 'string'
? { value: value.replace(CONTROL, '').replace(/[\r\n]+/g, ' ') }
: { error: 'invalid_format' }
}
}
/**
* Default name for a GDPR consent field. A checkbox with this name is treated
* as a consent gate: it MUST be checked for the submission to go through,
@@ -116,10 +172,15 @@ export async function validateSubmission(
return { field: field.name, kind: 'too_long', ok: false, reason: 'invalid' }
}
const checked = field.name === consentFieldName ? { value } : checkValue(field, value)
if (checked.error) {
return { field: field.name, kind: checked.error, ok: false, reason: 'invalid' }
}
// Only carry through keys that belong to the form — unknown keys from a
// hand-crafted request are dropped, not stored.
if (value !== undefined) {
cleaned[field.name] = value
if (checked.value !== undefined) {
cleaned[field.name] = checked.value
}
}
+107 -1
View File
@@ -9,7 +9,8 @@ import type { PageMetadata, RobotsOptions, RobotsRules, SitemapEntry, SitemapSty
import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js'
import { MARKDOWN_PREFIX, markdownHref } from '../content/markdownNegotiation.js'
import { buildRobots, buildSitemapEntries, createPageMetadata, createSitemapRouteHandler } from '../seo/index.js'
import { buildWebPageJsonLd } from '../seo/buildWebPageJsonLd.js'
import { buildArticleJsonLd, buildBreadcrumbJsonLd, buildFaqJsonLd, buildRobots, buildSitemapEntries, createPageMetadata, createSitemapRouteHandler } from '../seo/index.js'
type CreateContentHelpersArgs = {
/**
@@ -38,6 +39,8 @@ type CreateContentHelpersArgs = {
* (content.md). Indexable pages only.
*/
markdownAlternate?: boolean | string
/** Defaults for getPageJsonLd — each call can override them. */
pageJsonLd?: PageJsonLdOptions
/** Pages collection slug. Defaults to 'pages'. */
pagesSlug?: string
/**
@@ -48,6 +51,8 @@ type CreateContentHelpersArgs = {
robots?: RobotsOptions
/** SiteSettings global slug. Defaults to 'site-settings'. */
settingsSlug?: string
/** Image URLs of a document for the sitemap (Google Images). Default: its SEO share image. */
sitemapImages?: (doc: Record<string, unknown>) => (null | string | undefined)[]
/**
* Browser look of `sitemapRoute` (/sitemap.xml). Default: built-in style,
* header "XML Sitemap", credit "Technology by Intecion.com". `false` = raw XML.
@@ -55,6 +60,20 @@ type CreateContentHelpersArgs = {
sitemapStyle?: false | SitemapStyleOptions
}
export type PageJsonLdOptions = {
/** BreadcrumbList (home › archive › page) from the real route. Default true. */
breadcrumbs?: boolean
/** schema.org type of archive entries. Default 'BlogPosting'. */
entryType?: 'Article' | 'BlogPosting' | 'NewsArticle'
/**
* Q&A visible on this page (e.g. from its FAQ block) → FAQPage. The project
* knows its block shape, so it maps it: `(doc) => doc.layout…map(i => ({ question, answer }))`.
*/
faq?: (doc: Record<string, unknown>) => { answer: string; question: string }[]
/** schema.org type of ordinary pages, per document (e.g. 'ContactPage'). Default 'WebPage'. */
pageType?: (doc: Record<string, unknown>) => string | undefined
}
/**
* Bundles the per-request data helpers a frontend needs — the same cached
* wrappers every project was writing by hand (getPayload, settings, locale
@@ -87,9 +106,11 @@ export function createContentHelpers({
content,
i18n,
markdownAlternate,
pageJsonLd: pageJsonLdDefaults,
pagesSlug = 'pages',
robots: robotsOptions,
settingsSlug = 'site-settings',
sitemapImages,
sitemapStyle,
}: CreateContentHelpersArgs) {
const origin = baseUrl ?? process.env.NEXT_PUBLIC_SERVER_URL ?? ''
@@ -175,6 +196,89 @@ export function createContentHelpers({
}
}
/**
* Per-page structured data — WebPage (BlogPosting for archive entries) with
* language and dates, BreadcrumbList from the actual route, FAQPage when the
* project maps its FAQ block. Built from the same cached route and metadata
* as the page, so it can't disagree with canonical/title. Returns plain nodes
* — render them with <JsonLdGraph schemas={…}> next to the layout's
* WebSite/Organization, add your own, or drop any.
*
* // [[...slug]]/page.tsx
* <JsonLdGraph schemas={await getPageJsonLd(locale, slug)} />
*/
const getPageJsonLd = async (
locale: string,
segments: string[] | undefined,
options: PageJsonLdOptions = {},
): Promise<Record<string, unknown>[]> => {
const opts = { ...pageJsonLdDefaults, ...options }
const [meta, route, settings] = await Promise.all([
generatePageMetadata(locale, segments),
resolveRoute(locale, segments ?? [], 1),
getSettings(locale) as Promise<Record<string, unknown>>,
])
const url = meta.alternates?.canonical
if (!route || !url || meta.robots?.index === false) {return []}
const doc = route.doc
const str = (v: unknown) => (typeof v === 'string' && v.trim() ? v.trim() : undefined)
const name = str(doc.title) ?? meta.title
const siteName = str(settings?.siteName)
const root = new URL(url)
const singleLocale = (i18n?.locales.length ?? 0) === 1
const homeUrl = `${root.origin}${singleLocale ? '' : `/${locale}`}`
const image = meta.openGraph?.images?.[0]?.url
const nodes: (null | Record<string, unknown>)[] = []
if (route.type === 'entry') {
nodes.push(
buildArticleJsonLd({
type: opts.entryType ?? 'BlogPosting',
dateModified: str(doc.updatedAt),
datePublished: str(doc.publishedAt) ?? str(doc.createdAt),
description: meta.description,
headline: name,
image: image ? { url: image } : undefined,
publisherName: siteName,
url,
}),
)
} else {
nodes.push(
buildWebPageJsonLd({
name,
type: route.type === 'archive' ? 'CollectionPage' : (opts.pageType?.(doc) ?? 'WebPage'),
dateModified: str(doc.updatedAt),
description: meta.description,
image,
inLanguage: locale,
url,
websiteUrl: homeUrl,
}),
)
}
if (opts.breadcrumbs !== false && route.type !== 'home') {
const homepage = settings?.homepage as Record<string, unknown> | undefined
const crumbs = [{ name: str(homepage?.title) ?? siteName ?? root.host, url: homeUrl }]
if (route.type === 'entry') {
const archiveName = str(route.archive.title)
if (archiveName) {crumbs.push({ name: archiveName, url: url.replace(/\/[^/]+$/, '') })}
}
crumbs.push({ name, url })
nodes.push(buildBreadcrumbJsonLd(crumbs))
}
const faq = opts.faq?.(doc)?.filter((i) => i.question?.trim() && i.answer?.trim())
if (faq?.length) {nodes.push(buildFaqJsonLd(faq))}
// JsonLdGraph adds the @context once for the whole @graph.
return nodes
.filter((n): n is Record<string, unknown> => Boolean(n))
.map(({ '@context': _context, ...node }) => node)
}
/** ID of the page assigned as 404 — the relation isn't localized, so one read serves every locale. */
const getNotFoundPageId = cache(async (): Promise<null | number | string> => {
const payload = await getCachedPayload()
@@ -259,6 +363,7 @@ export function createContentHelpers({
baseUrl: origin,
config: i18n,
content,
images: sitemapImages,
pagesSlug,
payload: await getCachedPayload(),
settingsSlug,
@@ -424,6 +529,7 @@ export function createContentHelpers({
getConfiguredLocales,
getEntries,
getNotFoundPage,
getPageJsonLd,
getSettings,
resolveRoute,
robots,
+1 -1
View File
@@ -1,4 +1,4 @@
export { buildLinkField, buildLinksField } from './buildLinkField.js'
export type { BuildLinkFieldOptions, BuildLinksFieldOptions, LinkAppearance } from './buildLinkField.js'
export { resolveLinkHref } from './resolveLinkHref.js'
export { resolveLinkHref, safeHref } from './resolveLinkHref.js'
export type { LinkValue, ResolveLinkHrefOptions } from './resolveLinkHref.js'
+16 -1
View File
@@ -6,6 +6,21 @@ import { buildLocalizedPath } from '../i18n/index.js'
* Minimal shape of a link value (the project's generated `CmsLink` fits it).
* The plugin doesn't know the project's types — only this contract.
*/
/**
* Schemes a CMS link may use. The field validates this too, but data can come
* from imports, seeds or older versions — `javascript:`, `data:` and other
* schemes are dropped here so a stored link can never run script on click.
*/
const SAFE_HREF = /^(?:https?:\/\/|mailto:|tel:|sms:|#|\/(?!\/))/i
/** The URL when it's a safe link target, otherwise null (control characters — e.g. "java\tscript:" — reject it). */
export function safeHref(url: null | string | undefined): null | string {
const v = url?.trim()
// eslint-disable-next-line no-control-regex
if (!v || /[\u0000-\u001F\u007F]/.test(v)) {return null}
return SAFE_HREF.test(v) ? v : null
}
export type LinkValue = {
appearance?: null | string
file?: unknown
@@ -43,7 +58,7 @@ export function resolveLinkHref(
): null | string {
if (!link) {return null}
if (link.type === 'external') {return link.url?.trim() || null}
if (link.type === 'external') {return safeHref(link.url)}
if (link.type === 'file') {
const file = link.file
+18 -12
View File
@@ -4,9 +4,10 @@ import type { ContentOption } from '../content/index.js'
import type { I18nConfig } from '../i18n/index.js'
import type { ClientIpOptions } from '../shared/rateLimit.js'
import { createMarkdownRenderer, listContent, searchContent } from '../content/index.js'
import { createMarkdownRenderer, searchContent } from '../content/index.js'
import { getDefaultLocale, isValidLocale } from '../i18n/index.js'
import { readSiteMetaConfig } from '../seo/readSiteMetaConfig.js'
import { collectSiteIndex } from '../seo/siteIndex.js'
import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js'
/**
@@ -103,7 +104,7 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
const rl = args.rateLimit === false ? null : { max: 60, windowMs: 60_000, ...args.rateLimit }
const origin = baseUrl?.replace(/\/$/, '') ?? ''
const renderMarkdown = createMarkdownRenderer({ collection, content, settingsSlug })
const renderMarkdown = createMarkdownRenderer({ baseUrl: origin || undefined, collection, config, content, settingsSlug })
const localeProp = { type: 'string', description: `Locale code (default ${config.defaultLocale})` }
@@ -117,7 +118,7 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
{
name: 'list_pages',
description:
'List all published pages of the site with title, URL and description — the table of contents. Fetch one with get_page.',
'List all published pages and entries (e.g. blog posts) with title, URL and description — the table of contents. Fetch one with get_page.',
inputSchema: {
type: 'object',
properties: {
@@ -189,21 +190,26 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
async function runList(params: Record<string, unknown>): Promise<string> {
const locale = pickLocale(params)
const limit = typeof params.limit === 'number' ? params.limit : 50
const limit = Math.min(Math.max(Math.trunc(typeof params.limit === 'number' ? params.limit : 50) || 50, 1), 200)
const payload = await getCachedPayload()
const meta = await siteMeta(payload, locale)
const results = await listContent({
// Same index as llms.txt and the sitemap rules: pages AND archive entries (blog…).
const index = await collectSiteIndex({
baseUrl: origin,
collection,
config,
homeSlug: meta?.homeSlug,
limit,
locale,
content,
locales: [locale],
pagesSlug: collection,
payload,
settingsSlug,
summaryField,
})
if (results.length === 0) {return 'No published pages.'}
return formatResults(results)
if (index.length === 0) {return 'No published pages.'}
const shown = index.slice(0, limit)
const lines = shown.map(
(e) => `- ${e.title} (${e.url})${e.description ? ` — ${e.description}` : ''}${e.collection === collection ? '' : ` [${e.collectionLabel}]`}`,
)
if (index.length > shown.length) {lines.push(`… ${index.length - shown.length} more — raise limit (max 200) or use search_content.`)}
return lines.join('\n')
}
async function runSearch(params: Record<string, unknown>): Promise<string> {
+3
View File
@@ -1,3 +1,6 @@
export { MEDIA_SIZES, mediaImageProps, videoProps } from './mediaProps.js'
export type { MediaImageOptions, MediaImageProps, VideoMode, VideoProps } from './mediaProps.js'
export { normalizeFilename, normalizeFilenameHook } from './normalizeFilename.js'
export { buildOptimizeUploadField, buildOptimizeUploadHook } from './optimizeUpload.js'
export type { OptimizeUploadOptions } from './optimizeUpload.js'
export { buildMediaPlaceholderField, buildMediaPlaceholderHook } from './placeholder.js'
+136
View File
@@ -0,0 +1,136 @@
/**
* Props for the project's own <Media> — the plugin computes the performance
* details, the project keeps the markup and the look. Nothing here renders,
* styles or limits anything: every value can be overridden by the caller.
*
* // src/components/ui/Media.tsx
* const img = mediaImageProps(resource, { sizes: MEDIA_SIZES.half, priority })
* if (img) return <Image {...img} className={className} />
* const video = videoProps(resource, { mode: 'background' })
* if (video) return <video {...video} className={className} />
*/
type MediaDoc = {
alt?: null | string
focalX?: null | number
focalY?: null | number
height?: null | number
mimeType?: null | string
placeholder?: { blurDataURL?: null | string; color?: null | string } | null
url?: null | string
width?: null | number
}
/**
* Starting points for `sizes` — how wide the image is ON SCREEN at each
* breakpoint, so the browser downloads the right file instead of a full-width
* one. Suggestions only: pass any string that matches the actual layout.
*/
export const MEDIA_SIZES = {
/** Full-bleed hero / background. */
full: '100vw',
/** Half the container from md up (two-column hero, image + text). */
half: '(min-width: 768px) 50vw, 100vw',
/** Card in a 3-column grid from lg, 2 from md. */
third: '(min-width: 1024px) 33vw, (min-width: 768px) 50vw, 100vw',
/** Card in a 4-column grid. */
quarter: '(min-width: 1024px) 25vw, (min-width: 640px) 50vw, 100vw',
/** Thumbnail / avatar / logo up to ~160 px. */
thumb: '160px',
} as const
export type MediaImageOptions = {
/** Alt override (decorative images: ''). Default: the document's alt. */
alt?: string
/**
* The LCP image (first visible image — usually the hero): loads eagerly with
* fetchPriority="high". Exactly one per page; everything else is lazy.
*/
priority?: boolean
/** How wide it is on screen. Required in practice — see MEDIA_SIZES. Default '100vw'. */
sizes?: string
}
export type MediaImageProps = {
alt: string
blurDataURL?: string
fetchPriority?: 'high'
height: number
loading: 'eager' | 'lazy'
placeholder?: 'blur' | 'empty'
/** Next 16: <link rel=preload> for the LCP image (replaces the deprecated `priority`). */
preload?: boolean
sizes: string
src: string
style?: { backgroundColor?: string; objectPosition?: string }
width: number
}
const asDoc = (resource: unknown): MediaDoc | null =>
resource && typeof resource === 'object' && typeof (resource as MediaDoc).url === 'string' ? (resource as MediaDoc) : null
/**
* next/image props for an image upload, or null for anything else (video, PDF,
* a bare id). Width/height always come from the document — no layout shift.
* Focal point (upload `focalPoint: true`) becomes object-position, so a cropped
* image keeps its subject; a placeholder (buildMediaPlaceholderHook) becomes a
* blur-up and background colour.
*/
export function mediaImageProps(resource: unknown, { alt, priority = false, sizes = '100vw' }: MediaImageOptions = {}): MediaImageProps | null {
const doc = asDoc(resource)
if (!doc || doc.mimeType?.startsWith('video/')) {return null}
if (!doc.width || !doc.height) {return null} // PDF or other non-image file — link it instead
const blur = doc.placeholder?.blurDataURL ?? undefined
const color = doc.placeholder?.color ?? undefined
const hasFocal = typeof doc.focalX === 'number' && typeof doc.focalY === 'number' && !(doc.focalX === 50 && doc.focalY === 50)
const style = {
...(hasFocal ? { objectPosition: `${doc.focalX}% ${doc.focalY}%` } : {}),
...(color ? { backgroundColor: color } : {}),
}
return {
alt: alt ?? doc.alt ?? '',
height: doc.height,
sizes,
src: doc.url!,
width: doc.width,
...(priority
? { fetchPriority: 'high' as const, loading: 'eager' as const, preload: true }
: { loading: 'lazy' as const }),
...(blur ? { blurDataURL: blur, placeholder: 'blur' as const } : {}),
...(Object.keys(style).length ? { style } : {}),
}
}
export type VideoMode = 'background' | 'player'
export type VideoProps = {
autoPlay?: boolean
controls?: boolean
loop?: boolean
muted?: boolean
playsInline: true
poster?: string
preload: 'metadata' | 'none'
src: string
}
/**
* <video> attributes for a video upload, or null when it isn't one.
* - 'background': silent loop for heroes/ambience — autoplay, muted, loop, no
* controls. Pass `reducedMotion` (from a client hook) to not autoplay for
* visitors who asked for less motion.
* - 'player': a real video — controls, nothing downloaded until play
* (preload="none"), poster shown meanwhile. Default.
*/
export function videoProps(
resource: unknown,
{ mode = 'player', poster, reducedMotion = false }: { mode?: VideoMode; poster?: unknown; reducedMotion?: boolean } = {},
): null | VideoProps {
const doc = asDoc(resource)
if (!doc || !doc.mimeType?.startsWith('video/')) {return null}
const posterUrl = typeof poster === 'string' ? poster : asDoc(poster)?.url ?? undefined
const base = { playsInline: true as const, src: doc.url!, ...(posterUrl ? { poster: posterUrl } : {}) }
return mode === 'background'
? { ...base, autoPlay: !reducedMotion, loop: true, muted: true, preload: 'metadata' }
: { ...base, controls: true, preload: 'none' }
}
+62
View File
@@ -0,0 +1,62 @@
import type { CollectionBeforeOperationHook, Field } from 'payload'
import { readFile } from 'node:fs/promises'
/**
* Image placeholders computed once, at upload: a ~16 px blurred preview
* (base64 WebP, ~150–400 bytes) and the dominant colour. The page shows them
* while the real image loads — no empty box, no layout "pop" — and Next's
* `placeholder="blur"` needs exactly this. Opt-in, two pieces in the project's
* Media collection:
*
* hooks: { beforeOperation: [buildOptimizeUploadHook(), buildMediaPlaceholderHook()] },
* fields: [ …, buildMediaPlaceholderField() ],
*
* Uses the `sharp` passed to buildConfig({ sharp }) — no extra dependency.
* Existing images get placeholders when re-saved with a new file; without one
* mediaImageProps simply renders no placeholder.
*/
const FIELD = 'placeholder'
/** Hidden group holding the placeholder (read by mediaImageProps). */
export function buildMediaPlaceholderField(name: string = FIELD): Field {
return {
name,
type: 'group',
admin: { hidden: true },
fields: [
{ name: 'blurDataURL', type: 'text' },
{ name: 'color', type: 'text' },
],
}
}
type UploadFile = { data?: Buffer; mimetype: string; tempFilePath?: string }
const RASTER = new Set(['image/avif', 'image/gif', 'image/jpeg', 'image/png', 'image/webp'])
export function buildMediaPlaceholderHook({ field = FIELD, size = 16 }: { field?: string; size?: number } = {}): CollectionBeforeOperationHook {
return async ({ args, operation, req }) => {
if (operation !== 'create' && operation !== 'update') {return}
const file = req.file as undefined | UploadFile
const sharp = req.payload.config.sharp
if (!file || !sharp || !RASTER.has(file.mimetype)) {return}
const data = (args as { data?: Record<string, unknown> }).data
if (!data) {return}
try {
const buffer = file.data && file.data.length > 0 ? file.data : file.tempFilePath ? await readFile(file.tempFilePath) : undefined
if (!buffer) {return}
const tiny = await sharp(buffer).rotate().resize(size, size, { fit: 'inside' }).webp({ quality: 40 }).toBuffer()
const { dominant } = await sharp(buffer).stats()
const hex = (n: number) => Math.round(n).toString(16).padStart(2, '0')
data[field] = {
blurDataURL: `data:image/webp;base64,${tiny.toString('base64')}`,
color: `#${hex(dominant.r)}${hex(dominant.g)}${hex(dominant.b)}`,
}
} catch (err) {
// A placeholder is a nicety — never block the upload.
req.payload.logger.warn(`[ipal] media placeholder skipped: ${err instanceof Error ? err.message : String(err)}`)
}
}
}
+11 -5
View File
@@ -3,7 +3,7 @@ export type BuildCspArgs = {
analytics?: boolean
/** Extra sources per directive, merged with the built-ins. */
extra?: Partial<Record<CspDirective, string[]>>
/** Google Maps embeds — adds maps.google.com / *.gstatic.com. */
/** Google Maps — embeds (iframe) and the Maps JavaScript API, full domain set. Google Fonts are allowed by default. */
googleMaps?: boolean
/** 'enforce' → Content-Security-Policy; 'report-only' → …-Report-Only header. */
mode?: 'enforce' | 'report-only'
@@ -93,12 +93,18 @@ export function buildCsp(args: BuildCspArgs = {}): { key: string; value: string
if (youtube) {
src['frame-src'].push('https://www.youtube.com', 'https://www.youtube-nocookie.com')
src['img-src'].push('https://i.ytimg.com') // YouTubeEmbed poster
}
if (googleMaps) {
src['frame-src'].push('https://www.google.com', 'https://maps.google.com')
src['script-src'].push('https://maps.googleapis.com')
src['img-src'].push('https://maps.gstatic.com', 'https://*.googleapis.com')
// Embeds (iframe) and the Maps JavaScript API — the domain set from Google's
// CSP guide for Maps JS (tiles, markers, Street View images, fonts, workers).
const g = ['https://*.googleapis.com', 'https://*.gstatic.com', 'https://*.google.com', 'https://*.ggpht.com', 'https://*.googleusercontent.com']
src['frame-src'].push('https://www.google.com', 'https://maps.google.com', 'https://*.google.com')
src['script-src'].push(...g)
src['img-src'].push(...g)
src['connect-src'].push('https://*.googleapis.com', 'https://*.google.com', 'https://*.gstatic.com', 'data:', 'blob:')
src['worker-src'].push('blob:')
}
// Merge caller extras.
@@ -108,7 +114,7 @@ export function buildCsp(args: BuildCspArgs = {}): { key: string; value: string
const value = (Object.entries(src) as Array<[CspDirective, string[]]>)
.filter(([, values]) => values.length > 0)
.map(([dir, values]) => `${dir} ${values.join(' ')}`)
.map(([dir, values]) => `${dir} ${[...new Set(values)].join(' ')}`)
.join('; ')
const key = mode === 'report-only' ? 'Content-Security-Policy-Report-Only' : 'Content-Security-Policy'
@@ -1,3 +1,5 @@
import { isSiteNoindex } from '../seo/siteNoindex.js'
/**
* A single HTTP header, in the shape Next.js next.config headers() expects.
*/
@@ -116,6 +118,11 @@ export function buildSecurityHeaders(args: BuildSecurityHeadersArgs = {}): Secur
headers.push({ key: 'Cross-Origin-Opener-Policy', value: coop })
}
// Staging / preview (IPAL_NOINDEX=1): keep every response out of search engines.
if (isSiteNoindex()) {
headers.push({ key: 'X-Robots-Tag', value: 'noindex, nofollow' })
}
// Merge additional: same-key entries override the defaults above.
for (const extra of additional) {
const i = headers.findIndex((h) => h.key.toLowerCase() === extra.key.toLowerCase())
@@ -125,3 +132,30 @@ export function buildSecurityHeaders(args: BuildSecurityHeadersArgs = {}): Secur
return headers
}
/**
* Headers for files served from the upload routes. Media accept `image/*`,
* which includes SVG — and an SVG opened directly from the site's own origin
* can run script (stored XSS from any account that can upload). This CSP lets
* the file display but never execute: no scripts, no plugins, sandboxed.
* Media on R2 come from another domain and are already isolated; local-disk
* media (dev, or sites without R2) need this.
*
* // next.config.ts — next to the site-wide headers
* async headers() {
* return [
* { source: '/:path*', headers: securityHeaders },
* ...buildUploadSecurityHeaders(), // default: /api/media/file/*
* ]
* }
*/
export function buildUploadSecurityHeaders({ collections = ['media'] }: { collections?: string[] } = {}): {
headers: SecurityHeader[]
source: string
}[] {
const headers: SecurityHeader[] = [
{ key: 'Content-Security-Policy', value: "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox" },
{ key: 'X-Content-Type-Options', value: 'nosniff' },
]
return collections.map((slug) => ({ headers, source: `/api/${slug}/file/:path*` }))
}
+1 -1
View File
@@ -1,4 +1,4 @@
export { buildCsp } from './buildCsp.js'
export type { BuildCspArgs } from './buildCsp.js'
export { buildSecurityHeaders } from './buildSecurityHeaders.js'
export { buildSecurityHeaders, buildUploadSecurityHeaders } from './buildSecurityHeaders.js'
export type { BuildSecurityHeadersArgs, SecurityHeader, } from './buildSecurityHeaders.js'
+75 -102
View File
@@ -1,14 +1,23 @@
import type { BasePayload } from 'payload'
import type { ContentOption } from '../content/index.js'
import type { I18nConfig } from '../i18n/index.js'
import type { SiteIndexEntry } from './siteIndex.js'
import { blocksToMarkdown } from '../content/blocksToMarkdown.js'
import { buildLocalizedPath } from '../i18n/index.js'
import { getLocaleDefinition, isValidLocale } from '../i18n/index.js'
import { collectSiteIndex } from './siteIndex.js'
type BuildLlmsTxtArgs = {
/** Absolute site URL (https://…). */
baseUrl: string
config: I18nConfig
/**
* Archive-backed collections (same value as the plugin option). Their entries
* — blog posts, case studies, products — are listed too, grouped under the
* collection's own plural label. Usually the most quotable content on a site.
*/
content?: ContentOption
/**
* Full-content mode (llms-full.txt). When true, each page's full body is
* inlined as Markdown (via blocksToMarkdown) under its heading, so an agent
@@ -18,7 +27,10 @@ type BuildLlmsTxtArgs = {
full?: boolean
/** Field holding the block layout (full mode only). Default 'layout'. */
layoutField?: string
/** Locale for names/descriptions. Defaults to config.defaultLocale. */
/**
* One locale only. Default: every configured locale, each in its own
* section — an agent learns all language versions exist.
*/
locale?: string
/** Pages collection slug. Defaults to 'pages'. */
pagesSlug?: string
@@ -37,15 +49,7 @@ type SettingsShape = {
siteName?: null | string
}
type PageRow = {
[key: string]: unknown
_status?: string
id: number | string
meta?: { description?: unknown; noindex?: boolean } | null
noindex?: boolean | null
slug?: unknown
title?: unknown
}
const day = (iso?: string) => (iso ? iso.slice(0, 10) : undefined)
/**
* Builds the body of /llms.txt — a Markdown file describing the site for AI
@@ -53,32 +57,22 @@ type PageRow = {
* buildSitemapEntries: the plugin already knows the site's name, description,
* and pages, so it can generate this automatically.
*
* Structure (llmstxt.org): H1 site name, a blockquote/summary, then a list of
* key pages as Markdown links with short descriptions. Agents read this to
* understand the site quickly without crawling everything.
* Structure (llmstxt.org): H1 site name, a blockquote summary, then — per
* language when the site has several — one list per collection (pages first,
* then archive collections such as a blog) of Markdown links with descriptions.
* Section names are the project's own locale and collection labels; the plugin
* adds no text of its own.
*
* Wire it as a route that returns text/plain:
* // app/llms.txt/route.ts — use createLlmsTxtRoute (routeHandlers.ts)
*
* // app/llms.txt/route.ts
* import { buildLlmsTxt } from '@intecion/ipal-kit'
* import { getCachedPayload } from '@/lib/content'
* import { i18nConfig } from '@/i18n.config'
* export const dynamic = 'force-dynamic'
* export async function GET() {
* const body = await buildLlmsTxt({
* payload: await getCachedPayload(),
* config: i18nConfig,
* baseUrl: process.env.NEXT_PUBLIC_SERVER_URL!,
* })
* return new Response(body, { headers: { 'Content-Type': 'text/plain; charset=utf-8' } })
* }
*
* Data comes from the panel (siteName, siteDescription, pages) — nothing
* hardcoded. Skips drafts and noindex pages (same as the sitemap).
* Data comes from the panel (siteName, siteDescription, documents) — nothing
* hardcoded. Same rules as the sitemap (collectSiteIndex): drafts, noindex and
* error pages are skipped, the homepage collapses to the language root.
*/
export async function buildLlmsTxt({
baseUrl,
config,
content,
full = false,
layoutField = 'layout',
locale,
@@ -87,89 +81,68 @@ export async function buildLlmsTxt({
settingsSlug = 'site-settings',
summaryField,
}: BuildLlmsTxtArgs): Promise<string> {
const pickDescription = (raw: PageRow): string | undefined => {
if (
summaryField &&
typeof raw[summaryField] === 'string' &&
(raw[summaryField]).trim()
) {
return (raw[summaryField]).trim()
}
return typeof raw.meta?.description === 'string' ? raw.meta.description : undefined
}
const loc = locale ?? config.defaultLocale
const origin = baseUrl.replace(/\/$/, '')
const locales = locale && isValidLocale(locale, config) ? [locale] : config.locales.map((l) => l.code)
const headerLocale = locales.includes(config.defaultLocale) ? config.defaultLocale : locales[0]
const settings = (await payload.findGlobal({
slug: settingsSlug as never,
depth: 0,
locale: loc as never,
})) as SettingsShape
const name = settings.siteName?.trim() || 'Website'
let settings: SettingsShape = {}
try {
settings = (await payload.findGlobal({ slug: settingsSlug as never, depth: 0, locale: headerLocale as never })) as SettingsShape
} catch {
// fresh DB — header falls back to the host name
}
const name = settings.siteName?.trim() || new URL(origin || 'http://localhost').host
const description = settings.siteDescription?.trim()
// NO where:{_status} filter — collections without drafts enabled don't
// register the _status field, and querying it throws
// "path cannot be queried: _status" (a real bug report). Draft filtering
// happens in memory below, which is safe for every collection. Same as
// buildSitemapEntries and generateStaticParams.
// Full mode needs depth:1 so block images/relations populate for the Markdown.
const result = await payload.find({
collection: pagesSlug as never,
const index = await collectSiteIndex({
baseUrl: origin,
config,
content,
depth: full ? 1 : 0,
limit: 1000,
locale: loc as never,
locales,
pagesSlug,
payload,
settingsSlug,
summaryField,
})
const lines: string[] = [`# ${name}`, '']
if (description) {
lines.push(`> ${description}`, '')
}
if (description) {lines.push(`> ${description}`, '')}
if (full) {
// Full-content: each published page inlined as Markdown under its heading.
const sections: string[] = []
for (const raw of result.docs as PageRow[]) {
if (raw._status && raw._status !== 'published') {continue}
if (raw.noindex || raw.meta?.noindex) {continue}
const title = typeof raw.title === 'string' ? raw.title : undefined
const slug = typeof raw.slug === 'string' ? raw.slug : undefined
if (!title || !slug) {continue}
const path = buildLocalizedPath({ config, locale: loc, slugs: { [loc]: slug } })
const body = blocksToMarkdown(raw[layoutField])
const desc = pickDescription(raw)
const parts = [`## ${title}`]
if (path) {parts.push(`${origin}${path}`)}
if (desc) {parts.push(`_${desc}_`)}
if (body) {parts.push(body)}
sections.push(parts.join('\n\n'))
const multi = locales.length > 1
for (const loc of locales) {
const forLocale = index.filter((e) => e.locale === loc)
if (!forLocale.length) {continue}
if (multi) {
const def = getLocaleDefinition(loc, config)
lines.push(`## ${def?.label ?? loc} (${loc})`, '')
}
if (sections.length > 0) {lines.push(sections.join('\n\n---\n\n'), '')}
return lines.join('\n')
}
const level = multi ? '###' : '##'
const pageLinks: string[] = []
for (const raw of result.docs as PageRow[]) {
if (raw._status && raw._status !== 'published') {continue}
if (raw.noindex || raw.meta?.noindex) {continue}
// Group by collection, pages first (collectSiteIndex already orders them so).
const groups = new Map<string, SiteIndexEntry[]>()
for (const e of forLocale) {groups.set(e.collection, [...(groups.get(e.collection) ?? []), e])}
const title = typeof raw.title === 'string' ? raw.title : undefined
const slug = typeof raw.slug === 'string' ? raw.slug : undefined
if (!title || !slug) {continue}
const path = buildLocalizedPath({ config, locale: loc, slugs: { [loc]: slug } })
if (!path) {continue}
const desc = pickDescription(raw)
const pageDesc = desc ? ` — ${desc}` : ''
pageLinks.push(`- [${title}](${origin}${path})${pageDesc}`)
}
if (pageLinks.length > 0) {
lines.push('## Strony', '', ...pageLinks, '')
for (const entries of groups.values()) {
lines.push(`${level} ${entries[0].collectionLabel}`, '')
if (full) {
const sections = entries.map((e) => {
const parts = [`${level}# ${e.title}`, e.url]
const updated = day(e.updatedAt)
if (updated) {parts.push(`Updated: ${updated}`)}
if (e.description) {parts.push(`_${e.description}_`)}
const body = blocksToMarkdown(e.doc[layoutField])
if (body) {parts.push(body)}
return parts.join('\n\n')
})
lines.push(sections.join('\n\n---\n\n'), '')
} else {
for (const e of entries) {
lines.push(`- [${e.title}](${e.url})${e.description ? `: ${e.description}` : ''}`)
}
lines.push('')
}
}
}
return lines.join('\n')
+14 -4
View File
@@ -1,3 +1,5 @@
import { formatOpeningHours } from './formatOpeningHours.js'
type MediaLike = { url?: null | string } | null | undefined
type Address = {
@@ -15,12 +17,18 @@ type LocalBusinessJsonLdArgs = {
image?: MediaLike
logo?: MediaLike
name: string
/** Opening hours, e.g. ['Mo-Fr 08:00-18:00', 'Sa 09:00-14:00']. */
openingHours?: string[]
/**
* Opening hours — schema.org strings (['Mo-Fr 08:00-18:00']) or the editor's
* own text in Polish/English/German ('Pn-Pt: 8-18, Sob: 9-14'); normalized by
* formatOpeningHours. Unreadable text is omitted, never emitted invalid.
*/
openingHours?: readonly string[] | string
priceRange?: string // e.g. '$$'
sameAs?: string[]
/** Business phone, e.g. '+48 123 456 789'. */
telephone?: string
/** schema.org type for this business, e.g. 'LegalService', 'Dentist', 'HVACBusiness'. Default 'LocalBusiness'. */
type?: string
url: string
}
@@ -43,6 +51,7 @@ type LocalBusinessJsonLdArgs = {
*/
export function buildLocalBusinessJsonLd({
name,
type = 'LocalBusiness',
address,
geo,
image,
@@ -53,13 +62,14 @@ export function buildLocalBusinessJsonLd({
telephone,
url,
}: LocalBusinessJsonLdArgs) {
const hours = formatOpeningHours(openingHours)
const logoUrl = logo?.url
const imageUrl = image?.url ?? logoUrl
return {
name,
'@context': 'https://schema.org',
'@type': 'LocalBusiness',
'@type': type,
url,
...(telephone ? { telephone } : {}),
...(imageUrl ? { image: imageUrl.startsWith('http') ? imageUrl : `${url}${imageUrl}` } : {}),
@@ -79,7 +89,7 @@ export function buildLocalBusinessJsonLd({
...(geo
? { geo: { '@type': 'GeoCoordinates', latitude: geo.latitude, longitude: geo.longitude } }
: {}),
...(openingHours && openingHours.length > 0 ? { openingHours } : {}),
...(hours.length > 0 ? { openingHours: hours } : {}),
...(priceRange ? { priceRange } : {}),
...(sameAs && sameAs.length > 0 ? { sameAs } : {}),
}
+39 -4
View File
@@ -5,11 +5,15 @@ import type { SeoMeta } from './types.js'
import { buildLocalizedPath } from '../i18n/index.js'
import { composeTitle } from './composeTitle.js'
import { buildHreflangAlternates } from './hreflang.js'
import { isSiteNoindex } from './siteNoindex.js'
/**
* Subset of Next.js `Metadata` this helper produces. Kept local so the plugin
* doesn't depend on `next` types; the shape is assignable to Next's Metadata.
*/
/** Share image with its size and alt — lets X/LinkedIn/Facebook render the card without guessing. */
export type OgImage = { alt?: string; height?: number; url: string; width?: number }
export type PageMetadata = {
alternates?: {
canonical?: string
@@ -20,8 +24,11 @@ export type PageMetadata = {
description?: string
openGraph?: {
description?: string
images?: { url: string }[]
images?: OgImage[]
locale?: string
/** Article entries: ISO dates (og:article:published_time / modified_time). */
modifiedTime?: string
publishedTime?: string
/** Site/brand name for the OG card. */
siteName?: string
title: string
@@ -45,14 +52,28 @@ export type PageMetadata = {
'max-video-preview'?: number
}
title: string
/** X (Twitter) card — large image when there is one. */
twitter?: {
card: 'summary' | 'summary_large_image'
description?: string
images?: string[]
title: string
}
}
type BuildMetadataArgs = {
/**
* Article dates for archive entries (blog posts…): og:type becomes 'article'
* with published/modified times — a freshness signal for search and AI.
*/
article?: { modifiedTime?: null | string; publishedTime?: null | string }
/** Absolute site origin, e.g. 'https://example.com'. */
baseUrl?: string
config: I18nConfig
/** Home slug that collapses to the locale root. Defaults to 'home'. */
homeSlug?: Record<string, string> | string
/** Resolved OG image with size/alt (wins over imageUrl). */
image?: null | OgImage
/** Resolved OG image URL (page image or site defaultShareImage). */
imageUrl?: null | string
/** Current locale being rendered. */
@@ -113,9 +134,11 @@ type BuildMetadataArgs = {
* in — the plugin composes, it doesn't fetch.
*/
export function buildMetadata({
article,
baseUrl,
config,
homeSlug = 'home',
image,
imageUrl,
locale,
meta,
@@ -152,7 +175,9 @@ export function buildMetadata({
}
}
const images = imageUrl ? [{ url: imageUrl }] : undefined
const ogImage: null | OgImage = image?.url ? image : imageUrl ? { url: imageUrl } : null
const images = ogImage ? [ogImage] : undefined
const isArticle = Boolean(article?.publishedTime || article?.modifiedTime)
return {
title,
@@ -165,15 +190,25 @@ export function buildMetadata({
title,
...(description && { description }),
...(images && { images }),
type: 'website',
type: isArticle ? 'article' : 'website',
locale,
...(siteName ? { siteName } : {}),
...(canonical ? { url: canonical } : {}),
...(article?.publishedTime ? { publishedTime: article.publishedTime } : {}),
...(article?.modifiedTime ? { modifiedTime: article.modifiedTime } : {}),
},
twitter: {
card: ogImage ? 'summary_large_image' : 'summary',
title,
...(description && { description }),
...(ogImage ? { images: [ogImage.url] } : {}),
},
// robots: noindex pages are excluded (follow keeps link authority). Indexed
// pages get generous snippet/preview limits so Google can show rich results
// (long snippets, large image previews, full video previews).
...(noindex || meta?.noindex
...(isSiteNoindex()
? { robots: { follow: false, index: false } }
: noindex || meta?.noindex
? { robots: { follow: true, index: false } }
: {
robots: {
+30
View File
@@ -9,8 +9,17 @@ type BuildNoindexFieldArgs = {
name?: string
/** Extend/override the generated checkbox (position, access, etc.). */
overrides?: Partial<CheckboxField>
/**
* Refuse noindex on the homepage and on archive pages (blog, offers…) — it
* would drop the whole site or the whole section from Google. Default true.
*/
protectSystemPages?: boolean
/** SiteSettings global read for that check. Default 'site-settings'. */
settingsSlug?: string
}
const idOf = (rel: unknown): unknown => (rel && typeof rel === 'object' ? (rel as { id?: unknown }).id : rel)
/**
* A top-level sidebar `noindex` checkbox. When ticked, the page is excluded from
* `sitemap.xml`, `llms.txt`, site search, and gets `robots: noindex, follow` —
@@ -35,8 +44,28 @@ export function buildNoindexField(args: BuildNoindexFieldArgs = {}): Field {
description = 'Check to exclude this page from indexing (robots: noindex, follow), the sitemap, llms.txt and site search.',
label = 'Exclude from indexing (noindex)',
overrides = {},
protectSystemPages = true,
settingsSlug = 'site-settings',
} = args
const validate: CheckboxField['validate'] = async (value, { id, req }) => {
if (!protectSystemPages || value !== true || id === undefined) {return true}
try {
const settings = (await req.payload.findGlobal({ slug: settingsSlug as never, depth: 0, req })) as Record<string, unknown>
if (idOf(settings.homepage) === id) {
return 'This page is the homepage (Site Settings → System Pages). noindex would remove the whole site from Google.'
}
for (const [key, rel] of Object.entries(settings)) {
if (key.endsWith('Archive') && idOf(rel) === id) {
return 'This page is an archive (Site Settings → System Pages). noindex would hide the page that lists all its entries.'
}
}
} catch {
// settings unreadable (fresh DB) — nothing to protect yet
}
return true
}
const { admin: adminOverrides, ...restOverrides } = overrides
return {
@@ -49,6 +78,7 @@ export function buildNoindexField(args: BuildNoindexFieldArgs = {}): Field {
},
defaultValue: false,
label,
validate,
...restOverrides,
} as CheckboxField
}
@@ -42,3 +42,15 @@ export function buildOrganizationJsonLd({ name, logo, sameAs, url }: Organizatio
...(sameAs && sameAs.length > 0 ? { sameAs } : {}),
}
}
/**
* Profile URLs from Site Settings → sameAs (array of { url }), ready for
* buildOrganizationJsonLd / buildLocalBusinessJsonLd. Empty when none.
*/
export function sameAsUrls(settings: null | Record<string, unknown> | undefined): string[] {
const rows = settings?.sameAs
if (!Array.isArray(rows)) {return []}
return rows
.map((r) => (r && typeof r === 'object' ? (r as { url?: unknown }).url : undefined))
.filter((u): u is string => typeof u === 'string' && /^https?:\/\//.test(u))
}
+4
View File
@@ -1,3 +1,5 @@
import { isSiteNoindex } from './siteNoindex.js'
type RobotRule = { allow?: string; disallow?: string[]; userAgent: string | string[] }
/**
@@ -125,6 +127,8 @@ export function buildRobots({
sitemap = true,
}: BuildRobotsArgs): RobotsRules {
const origin = baseUrl.replace(/\/$/, '')
// Staging / preview (IPAL_NOINDEX=1): nothing may be crawled.
if (isSiteNoindex()) {return { rules: { disallow: ['/'], userAgent: '*' } }}
const defaults = [...(adminRoute ? [adminRoute] : []), '/api']
const paramRules = disallowParams
@@ -1,3 +1,8 @@
import type { I18nConfig } from '../i18n/index.js'
import type { LinkValue } from '../links/resolveLinkHref.js'
import { resolveLinkHref } from '../links/resolveLinkHref.js'
type NavItem = {
/** Visible label (e.g. 'Usługi'). */
name: string
@@ -37,3 +42,62 @@ export function buildSiteNavigationJsonLd(items: NavItem[]) {
})),
}
}
type NavSource = Record<string, unknown>
type BuildNavigationJsonLdArgs = {
/** Absolute origin, e.g. 'https://acme.pl'. */
baseUrl: string
config: I18nConfig
/** Child items. Default `item.subItems`. Return [] to list top level only. */
getChildren?: (item: NavSource) => unknown
/** Link of an item. Default `item.link` (ipal-nav template, buildLinkField). */
getLink?: (item: NavSource) => LinkValue | null | undefined
/** Homepage slug(s) so the home link collapses to /{locale}. */
homeSlug?: Record<string, string> | string
/** Menu items straight from the header global (depth ≥ 1, so page links are populated). */
items: null | readonly unknown[] | undefined
locale: string
}
/**
* SiteNavigationElement list straight from the project's header global —
* resolves page links per locale (resolveLinkHref), keeps only links on this
* site (external and file links are skipped), de-duplicates, and labels each
* item with the link label from the panel.
*
* const nav = buildNavigationJsonLd({ items: header.navItems, baseUrl, locale, config: i18nConfig, homeSlug })
* <JsonLdGraph schemas={[website, org, nav]} />
*/
export function buildNavigationJsonLd({
baseUrl,
config,
getChildren = (item) => item.subItems,
getLink = (item) => item.link as LinkValue | undefined,
homeSlug,
items,
locale,
}: BuildNavigationJsonLdArgs) {
const origin = baseUrl.replace(/\/$/, '')
const out: NavItem[] = []
const seen = new Set<string>()
const walk = (list: unknown) => {
if (!Array.isArray(list)) {return}
for (const raw of list) {
if (!raw || typeof raw !== 'object') {continue}
const item = raw as NavSource
const link = getLink(item)
if (link && link.type !== 'external' && link.type !== 'file') {
const href = resolveLinkHref(link, { config, homeSlug, locale })
const name = typeof link.label === 'string' ? link.label.trim() : ''
if (href && name && href.startsWith('/') && !seen.has(href)) {
seen.add(href)
out.push({ name, url: `${origin}${href}` })
}
}
walk(getChildren(item))
}
}
walk(items)
return buildSiteNavigationJsonLd(out)
}
+24 -1
View File
@@ -18,6 +18,8 @@ import { buildHreflangAlternates } from './hreflang.js'
export type SitemapEntry = {
alternates?: { languages: Record<string, string> }
changeFrequency?: 'always' | 'daily' | 'hourly' | 'monthly' | 'never' | 'weekly' | 'yearly'
/** Absolute image URLs on this page (Google Images). Next renders them as <image:image>. */
images?: string[]
lastModified?: Date | string
priority?: number
url: string
@@ -41,6 +43,12 @@ type BuildSitemapArgs = {
* Read from System Pages when omitted.
*/
homeSlug?: Record<string, string> | string
/**
* Images of a document for the sitemap (Google Images). Default: the SEO
* share image (meta.image). Return any URLs your blocks hold — the plugin
* doesn't assume a block shape. Relative URLs are made absolute.
*/
images?: (doc: Record<string, unknown>) => (null | string | undefined)[]
/** Pages collection slug. Defaults to 'pages'. */
pagesSlug?: string
payload: BasePayload
@@ -49,6 +57,7 @@ type BuildSitemapArgs = {
}
type DocRow = {
[key: string]: unknown
_status?: string
id: number | string
meta?: { noindex?: boolean } | null
@@ -103,6 +112,7 @@ function entryFor(
homeSlug: Record<string, string> | string | undefined,
prefix: Record<string, string> | undefined,
changeFrequency: SitemapEntry['changeFrequency'],
images: string[],
): null | SitemapEntry {
const slugs =
doc.slug && typeof doc.slug === 'object'
@@ -120,9 +130,16 @@ function entryFor(
...(doc.updatedAt ? { lastModified: doc.updatedAt } : {}),
...(changeFrequency ? { changeFrequency } : {}),
...(Object.keys(languages).length ? { alternates: { languages } } : {}),
...(images.length ? { images } : {}),
}
}
/** Default image source: the SEO share image (plugin-seo meta.image, populated). */
function defaultImages(doc: Record<string, unknown>): (null | string | undefined)[] {
const image = (doc.meta as { image?: unknown } | null | undefined)?.image
return image && typeof image === 'object' ? [(image as { url?: string }).url] : []
}
/**
* Collects every public URL — pages and archive entries — as sitemap entries
* with per-URL hreflang and lastmod.
@@ -150,10 +167,14 @@ export async function buildSitemapEntries({
config,
content,
homeSlug,
images: imagesOf = defaultImages,
pagesSlug = 'pages',
payload,
settingsSlug = 'site-settings',
}: BuildSitemapArgs): Promise<SitemapEntry[]> {
const origin = baseUrl.replace(/\/$/, '')
const absolute = (u: null | string | undefined): string | undefined =>
!u ? undefined : /^https?:\/\//.test(u) ? u : `${origin}${u.startsWith('/') ? '' : '/'}${u}`
const locales = config.locales.map((l) => l.code)
const defaultLocale = config.defaultLocale
@@ -194,7 +215,7 @@ export async function buildSitemapEntries({
// alternates without re-querying per locale.
const result = await payload.find({
collection: collection.slug as never,
depth: 0,
depth: 1, // populate uploads so image URLs are available
limit: 0, // no pagination — sitemap wants everything
locale: 'all' as never,
pagination: false as never,
@@ -202,6 +223,7 @@ export async function buildSitemapEntries({
for (const raw of result.docs as DocRow[]) {
if (!isIndexable(raw)) {continue}
const images = [...new Set(imagesOf(raw).map(absolute).filter((u): u is string => Boolean(u)))]
// Emit a separate <url> for EACH locale. Google's sitemap spec for
// localized sites requires one <url> per language version (each with its
@@ -217,6 +239,7 @@ export async function buildSitemapEntries({
resolvedHomeSlug,
collection.prefixSlugs,
changeFrequency,
images,
)
if (entry) {entries.push(entry)}
}
+5 -1
View File
@@ -77,6 +77,9 @@ export function buildSitemapXml(
}
}
}
for (const img of e.images ?? []) {
parts.push(` <image:image><image:loc>${esc(img)}</image:loc></image:image>`)
}
return ` <url>\n${parts.join('\n')}\n </url>`
})
.join('\n')
@@ -87,7 +90,8 @@ export function buildSitemapXml(
`<?xml version="1.0" encoding="UTF-8"?>\n` +
stylesheet +
`<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" ` +
`xmlns:xhtml="http://www.w3.org/1999/xhtml">\n` +
`xmlns:xhtml="http://www.w3.org/1999/xhtml" ` +
`xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">\n` +
urls +
`\n</urlset>`
)
+45
View File
@@ -0,0 +1,45 @@
type WebPageJsonLdArgs = {
/** ISO date of the last change — a freshness signal for search and AI. */
dateModified?: string
description?: string
/** Absolute URL of a representative image. */
image?: string
/** BCP 47 language of the page, e.g. 'pl'. */
inLanguage?: string
name: string
/** 'WebPage' (default), 'CollectionPage' (archive listing), 'AboutPage', 'ContactPage', 'FAQPage'… */
type?: string
/** Absolute URL of the page (also its @id). */
url: string
/** Absolute URL of the site root — links the page to the WebSite node. */
websiteUrl?: string
}
/**
* schema.org WebPage node for one page: name, description, language, last
* modification and the site it belongs to. Gives search engines and AI
* assistants explicit facts (what, which language, how fresh) instead of
* inferring them from HTML. Render through <JsonLdGraph>; data from the panel.
*/
export function buildWebPageJsonLd({
name,
type = 'WebPage',
dateModified,
description,
image,
inLanguage,
url,
websiteUrl,
}: WebPageJsonLdArgs) {
return {
name,
'@id': url,
'@type': type,
url,
...(description ? { description } : {}),
...(inLanguage ? { inLanguage } : {}),
...(dateModified ? { dateModified } : {}),
...(image ? { primaryImageOfPage: { '@type': 'ImageObject', url: image } } : {}),
...(websiteUrl ? { isPartOf: { '@type': 'WebSite', url: websiteUrl } } : {}),
}
}
+23 -8
View File
@@ -2,7 +2,7 @@ import type { BasePayload } from 'payload'
import type { ContentOption, ResolvedRoute } from '../content/index.js'
import type { I18nConfig } from '../i18n/index.js'
import type { PageMetadata } from './buildMetadata.js'
import type { OgImage, PageMetadata } from './buildMetadata.js'
import type { SeoMeta } from './types.js'
import { resolveRoute } from '../content/index.js'
@@ -54,21 +54,33 @@ type PageMetadataContext = {
}
type DocShape = {
createdAt?: string
id: number | string
meta?: null | SeoMeta
/** Top-level noindex checkbox (buildNoindexField) — the field that persists. */
noindex?: boolean | null
publishedAt?: null | string
/** The document's own title (page name), used as the fallback page title. */
title?: null | string
updatedAt?: string
}
/** plugin-seo stores the OG image as an upload relationship. */
function resolveOgImage(doc: DocShape): null | string {
const image = (doc.meta as { image?: unknown } | null | undefined)?.image
if (image && typeof image === 'object' && 'url' in image) {
return (image as { url: string }).url ?? null
/** An upload relationship (populated) → OG image with its size and alt. */
function toOgImage(image: unknown): null | OgImage {
if (!image || typeof image !== 'object') {return null}
const m = image as { alt?: unknown; height?: unknown; url?: unknown; width?: unknown }
if (typeof m.url !== 'string' || !m.url) {return null}
return {
url: m.url,
...(typeof m.width === 'number' ? { width: m.width } : {}),
...(typeof m.height === 'number' ? { height: m.height } : {}),
...(typeof m.alt === 'string' && m.alt ? { alt: m.alt } : {}),
}
return null
}
/** plugin-seo stores the OG image on the meta group; Site Settings has the fallback. */
function resolveOgImage(doc: DocShape, fallback: unknown): null | OgImage {
return toOgImage((doc.meta as { image?: unknown } | null | undefined)?.image) ?? toOgImage(fallback)
}
/**
@@ -178,7 +190,10 @@ export function createPageMetadata(args: CreatePageMetadataArgs) {
return buildMetadata({
...base,
imageUrl: resolveOgImage(doc),
...(route.type === 'entry'
? { article: { modifiedTime: doc.updatedAt, publishedTime: doc.publishedAt ?? doc.createdAt } }
: {}),
image: resolveOgImage(doc, site.defaultShareImage),
meta: doc.meta,
noindex: doc.noindex,
pageTitle: doc.title,
+112
View File
@@ -0,0 +1,112 @@
/**
* Turns opening hours as an editor types them into schema.org `openingHours`
* strings, so the panel field can stay human text in the site's language:
*
* formatOpeningHours('Pn-Pt: 08:00 - 17:00, Sob: 8-14, Nd: nieczynne')
* // → ['Mo-Fr 08:00-17:00', 'Sa 08:00-14:00']
* formatOpeningHours('Mon, Wed, Fri 9:30–17') // → ['Mo,We,Fr 09:30-17:00']
* formatOpeningHours('Mo–Fr 8–16 Uhr; Sa 9–12') // → ['Mo-Fr 08:00-16:00', 'Sa 09:00-12:00']
* formatOpeningHours('całodobowo') // → ['Mo-Su 00:00-23:59']
*
* Understands Polish, English and German day names and abbreviations (with or
* without diacritics and dots), ranges (`-`, `–`, `do`, `to`, `bis`), lists,
* `8`, `8:00`, `8.00`, closed days (skipped) and "24/7". Strings already in
* schema.org form pass through. Accepts one string or an array of lines. Anything
* it can't read is dropped rather than emitted invalid — check the result.
*/
type Day = 'Fr' | 'Mo' | 'Sa' | 'Su' | 'Th' | 'Tu' | 'We'
// Normalized (lowercase, no diacritics, no dots) day words → schema.org day.
// "so" is German Sonntag; Polish Saturday is "sob"/"sb"/"sobota".
const DAYS: Record<string, Day> = {
// pl
cz: 'Th', czw: 'Th', czwartek: 'Th', nd: 'Su', ndz: 'Su', niedz: 'Su', niedziela: 'Su', piat: 'Fr', piatek: 'Fr',
pn: 'Mo', pon: 'Mo', poniedzialek: 'Mo', pt: 'Fr', sb: 'Sa', sob: 'Sa', sobota: 'Sa', sr: 'We', sro: 'We',
sroda: 'We', wt: 'Tu', wto: 'Tu', wtorek: 'Tu',
// en
fr: 'Fr', fri: 'Fr', friday: 'Fr', mo: 'Mo', mon: 'Mo', monday: 'Mo', sa: 'Sa', sat: 'Sa', saturday: 'Sa', su: 'Su',
sun: 'Su', sunday: 'Su', th: 'Th', thu: 'Th', thur: 'Th', thurs: 'Th', thursday: 'Th', tu: 'Tu',
tue: 'Tu', tues: 'Tu', tuesday: 'Tu', we: 'We', wed: 'We', wednesday: 'We',
// de
di: 'Tu', dienstag: 'Tu', do: 'Th', donnerstag: 'Th', freitag: 'Fr', mi: 'We', mittwoch: 'We', montag: 'Mo',
samstag: 'Sa', so: 'Su', sonntag: 'Su',
}
const CLOSED = /\b(?:nieczynne|nieczynny|zamkniete|zamkniety|closed|geschlossen|ruhetag)\b/g
const ALWAYS = /\b(?:calodobowo|cala doba|cala dobe|24\s*\/\s*7|24h|non-?stop|rund um die uhr|open 24 hours)\b/
const TIME = /(?<fromH>\d{1,2})(?:[:.](?<fromM>\d{2}))?\s*(?:-|do|to|bis)\s*(?<toH>\d{1,2})(?:[:.](?<toM>\d{2}))?/g
const SCHEMA = /^(?:Mo|Tu|We|Th|Fr|Sa|Su)(?:[-,](?:Mo|Tu|We|Th|Fr|Sa|Su))*(?:\s+\d{2}:\d{2}-\d{2}:\d{2})?$/
function normalize(text: string): string {
return text
.toLowerCase()
.normalize('NFD')
.replace(/\p{M}/gu, '') // drop combining accents (ą → a)
.replace(/ł/g, 'l')
.replace(/[–—−]/g, '-')
.replace(/\./g, (m, i: number, s: string) => (/\d/.test(s[i - 1] ?? '') && /\d/.test(s[i + 1] ?? '') ? m : ' '))
.replace(/\buhr\b/g, ' ')
}
function hhmm(h: string, m?: string): null | string {
const hour = Number(h)
const minute = m ? Number(m) : 0
if (hour > 24 || minute > 59) {return null}
return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`
}
/** Day words in a fragment → "Mo-Fr" (range) or "Mo,We,Fr" (list). */
function parseDays(fragment: string): null | string {
const days: Day[] = []
let range = false
for (const w of fragment.match(/[a-z]+|-/g) ?? []) {
// "do" is both Polish "to" and German Donnerstag: a range word only right after the first day.
const rangeWord = w === '-' || w === 'to' || w === 'bis' || (w === 'do' && days.length === 1)
if (rangeWord) {
if (days.length === 1) {range = true}
continue
}
const day = DAYS[w]
if (day) {days.push(day)}
}
if (days.length === 0) {return null}
if (range && days.length === 2) {return `${days[0]}-${days[1]}`}
return [...new Set(days)].join(',')
}
export function formatOpeningHours(input: null | readonly string[] | string | undefined): string[] {
if (!input) {return []}
const lines = (Array.isArray(input) ? input : [input as string]).map((l) => l.trim()).filter(Boolean)
if (lines.every((l) => SCHEMA.test(l))) {return [...lines]}
const out: string[] = []
for (const raw of lines) {
if (SCHEMA.test(raw)) {
out.push(raw)
continue
}
const text = normalize(raw)
if (ALWAYS.test(text)) {
out.push('Mo-Su 00:00-23:59')
continue
}
let last = 0
for (const m of text.matchAll(TIME)) {
// The day spec is what precedes this time range — after the previous
// range, the last line break / semicolon, and any "closed" day.
let spec = text.slice(last, m.index)
last = (m.index ?? 0) + m[0].length
spec = spec.split(/[;\n]/).pop() ?? ''
const closedAt = [...spec.matchAll(CLOSED)].pop()
if (closedAt) {spec = spec.slice((closedAt.index ?? 0) + closedAt[0].length)}
const days = parseDays(spec)
const g = m.groups ?? {}
const from = hhmm(g.fromH, g.fromM)
const to = hhmm(g.toH, g.toM)
if (!days || !from || !to) {continue}
out.push(`${days} ${from}-${to === '24:00' ? '23:59' : to}`)
}
}
return out
}
+14 -2
View File
@@ -10,22 +10,32 @@ export { createManifestHandler } from './buildManifest.js'
export { buildMetadata } from './buildMetadata.js'
export type { PageMetadata } from './buildMetadata.js'
export { buildNoindexField } from './buildNoindexField.js'
export { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js'
export { buildOrganizationJsonLd, sameAsUrls } from './buildOrganizationJsonLd.js'
export { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, buildRobots } from './buildRobots.js'
export type { RobotsOptions, RobotsRules } from './buildRobots.js'
export { buildServiceJsonLd } from './buildServiceJsonLd.js'
export { buildSitemapEntries } from './buildSitemapEntries.js'
export type { SitemapEntry } from './buildSitemapEntries.js'
export { buildSitemapXml } from './buildSitemapXml.js'
export { buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js'
export { buildNavigationJsonLd, buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js'
export { buildSpeakableJsonLd } from './buildSpeakableJsonLd.js'
export { buildSummaryField } from './buildSummaryField.js'
export { buildWebPageJsonLd } from './buildWebPageJsonLd.js'
export { buildWebSiteJsonLd } from './buildWebSiteJsonLd.js'
export { composeTitle } from './composeTitle.js'
export type { TitleOrder } from './composeTitle.js'
export { createMetadataGenerator } from './createMetadataGenerator.js'
export { createPageMetadata } from './createPageMetadata.js'
export { formatOpeningHours } from './formatOpeningHours.js'
export { buildHreflangAlternates } from './hreflang.js'
export {
buildIndexNowHook,
createIndexNowKeyRoute,
getIndexNowKey,
INDEXNOW_KEY_ENV,
INDEXNOW_KEY_PATH,
submitToIndexNow,
} from './indexNow.js'
export { injectAutoFillMeta } from './injectAutoFillMeta.js'
export { injectSeoTabs } from './injectSeoTabs.js'
export { JsonLdGraph } from './JsonLdGraph.js'
@@ -34,6 +44,8 @@ export type { SiteMetaConfig } from './readSiteMetaConfig.js'
export { createLlmsTxtRoute, createSitemapRouteHandler } from './routeHandlers.js'
export type { SitemapRouteOptions } from './routeHandlers.js'
export { buildSeoPlugin } from './seoPluginConfig.js'
export { collectSiteIndex } from './siteIndex.js'
export type { CollectSiteIndexArgs, SiteIndexEntry } from './siteIndex.js'
export { buildSitemapCss, DEFAULT_SITEMAP_CREDIT, SITEMAP_STYLE_PARAM } from './sitemapStyle.js'
export type { SitemapStyleOptions } from './sitemapStyle.js'
export { slugsAcrossLocales } from './slugsAcrossLocales.js'
+183
View File
@@ -0,0 +1,183 @@
import type { BasePayload, CollectionAfterChangeHook, Field } from 'payload'
import type { I18nConfig } from '../i18n/index.js'
import { archiveFieldName } from '../content/types.js'
import { buildLocalizedPath, getLocaleCodes, getLocalizedSlugs } from '../i18n/index.js'
/**
* IndexNow — tell search engines a URL changed the moment it's published
* (Bing, Yandex, Seznam, Naver… share submissions). Bing's index feeds ChatGPT
* Search and Copilot, so new content reaches AI answers in minutes instead of
* waiting for a crawl. Google doesn't use IndexNow (it reads the sitemap).
*
* Opt-in: `ipalKit({ indexNow: true })` adds the hook to the pages and content
* collections; or add `buildIndexNowHook(…)` yourself. Needs the key file route
* (createIndexNowKeyRoute) and a key: Site Integrations → IndexNow (generated on
* the first save) or the INDEXNOW_KEY env var. Sends only from production with
* a public NEXT_PUBLIC_SERVER_URL; never blocks or fails a save.
*/
export const INDEXNOW_KEY_ENV = 'INDEXNOW_KEY'
export const INDEXNOW_KEY_PATH = '/indexnow-key.txt'
const ENDPOINT = 'https://api.indexnow.org/indexnow'
const KEY_FIELD = 'indexNowKey'
const SITE_INTEGRATIONS = 'site-integrations'
/** Site Integrations field holding the key — generated when empty. */
export const indexNowFields: Field[] = [
{
name: KEY_FIELD,
type: 'text',
admin: {
description:
'Key that proves this site owns its URLs to IndexNow (Bing, ChatGPT Search). Generated automatically — change only to rotate it.',
},
hooks: {
beforeChange: [
({ value }) => (typeof value === 'string' && value.trim() ? value.trim() : randomKey()),
],
},
},
]
function randomKey(): string {
const bytes = new Uint8Array(16)
globalThis.crypto.getRandomValues(bytes)
return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')
}
/** The IndexNow key: env first, then Site Integrations. Empty string when none. */
export async function getIndexNowKey(payload: BasePayload): Promise<string> {
const fromEnv = process.env[INDEXNOW_KEY_ENV]?.trim()
if (fromEnv) {return fromEnv}
try {
const doc = (await payload.findGlobal({ slug: SITE_INTEGRATIONS as never, depth: 0 })) as Record<string, unknown>
return typeof doc[KEY_FIELD] === 'string' ? (doc[KEY_FIELD]).trim() : ''
} catch {
return ''
}
}
/**
* Route serving the key file IndexNow fetches to verify ownership:
*
* // src/app/indexnow-key.txt/route.ts
* import { createIndexNowKeyRoute } from '@intecion/ipal-kit'
* import { getCachedPayload } from '@/lib/content'
* export const dynamic = 'force-dynamic'
* export const GET = createIndexNowKeyRoute({ getCachedPayload })
*/
export function createIndexNowKeyRoute({ getCachedPayload }: { getCachedPayload: () => Promise<BasePayload> }) {
return async (): Promise<Response> => {
const key = await getIndexNowKey(await getCachedPayload())
if (!key) {return new Response('Not found', { status: 404 })}
return new Response(key, { headers: { 'cache-control': 'public, max-age=3600', 'content-type': 'text/plain; charset=utf-8' } })
}
}
/** True when submissions may leave this machine: production + a public https origin. */
function publicOrigin(baseUrl?: string): null | string {
const origin = (baseUrl ?? process.env.NEXT_PUBLIC_SERVER_URL ?? '').replace(/\/$/, '')
if (process.env.NODE_ENV !== 'production' || !/^https:\/\//i.test(origin)) {return null}
if (/localhost|127\.0\.0\.1|\.local\b|\.test\b/i.test(origin)) {return null}
return origin
}
/** POST a batch of URLs to IndexNow. Never throws; logs a warning on failure. */
export async function submitToIndexNow({
baseUrl,
payload,
urls,
}: {
baseUrl?: string
payload: BasePayload
urls: string[]
}): Promise<boolean> {
const origin = publicOrigin(baseUrl)
if (!origin || urls.length === 0) {return false}
const key = await getIndexNowKey(payload)
if (!key) {return false}
try {
const res = await fetch(ENDPOINT, {
body: JSON.stringify({ host: new URL(origin).host, key, keyLocation: `${origin}${INDEXNOW_KEY_PATH}`, urlList: urls.slice(0, 10_000) }),
headers: { 'content-type': 'application/json; charset=utf-8' },
method: 'POST',
signal: AbortSignal.timeout(8000),
})
// 200 = accepted, 202 = accepted, key validation pending.
if (res.status !== 200 && res.status !== 202) {
console.warn(`[ipal] IndexNow: ${res.status} for ${urls.length} URL(s) — check the key file at ${origin}${INDEXNOW_KEY_PATH}`)
return false
}
return true
} catch (err) {
console.warn('[ipal] IndexNow: request failed:', err instanceof Error ? err.message : err)
return false
}
}
type BuildIndexNowHookArgs = {
/** Absolute origin. Default NEXT_PUBLIC_SERVER_URL. */
baseUrl?: string
config: I18nConfig
/**
* Set for an archive-backed collection (blog…): its archive page in Site
* Settings gives the URL prefix. Omit for the pages collection.
*/
contentCollection?: string
/** SiteSettings global. Default 'site-settings'. */
settingsSlug?: string
}
/** Builds a locale→slug map from a populated relationship read with locale 'all'. */
function slugsOf(rel: unknown, config: I18nConfig): Record<string, string> | undefined {
if (!rel || typeof rel !== 'object') {return undefined}
const slug = (rel as { slug?: unknown }).slug
const map = getLocalizedSlugs({ config, slugField: slug && typeof slug === 'object' ? (slug as Record<string, unknown>) : undefined })
return Object.keys(map).length ? map : undefined
}
/**
* afterChange hook: when a document is published (or a published one changes),
* submits its URL in every language to IndexNow. Drafts, noindex documents and
* non-production environments send nothing. Runs in the background — the save
* never waits for or fails on IndexNow.
*/
export function buildIndexNowHook({
baseUrl,
config,
contentCollection,
settingsSlug = 'site-settings',
}: BuildIndexNowHookArgs): CollectionAfterChangeHook {
return ({ collection, context, doc, req }) => {
if (context?.ipalSkipIndexNow) {return doc}
const row = doc as { _status?: string; id: number | string; meta?: { noindex?: boolean } | null; noindex?: boolean | null }
if ((row._status && row._status !== 'published') || row.noindex || row.meta?.noindex) {return doc}
if (!publicOrigin(baseUrl)) {return doc}
const run = async () => {
const all = (await req.payload.findByID({ id: row.id, collection: collection.slug as never, depth: 0, locale: 'all' as never })) as {
slug?: Record<string, unknown> | string
}
const slugs =
typeof all.slug === 'string'
? Object.fromEntries(getLocaleCodes(config).map((l) => [l, all.slug as string]))
: getLocalizedSlugs({ config, slugField: all.slug })
const settings = (await req.payload.findGlobal({ slug: settingsSlug as never, depth: 1, locale: 'all' as never })) as Record<string, unknown>
const homeSlug = slugsOf(settings.homepage, config) ?? 'home'
const prefix = contentCollection ? slugsOf(settings[archiveFieldName(contentCollection)], config) : undefined
if (contentCollection && !prefix) {return}
const origin = publicOrigin(baseUrl)!
const urls = getLocaleCodes(config)
.map((locale) => buildLocalizedPath({ config, homeSlug, locale, prefix, slugs }))
.filter((p): p is string => Boolean(p))
.map((p) => `${origin}${p}`)
await submitToIndexNow({ baseUrl: origin, payload: req.payload, urls })
}
// Background: never block or fail the save.
void run().catch((err: unknown) => console.warn('[ipal] IndexNow hook failed:', err instanceof Error ? err.message : err))
return doc
}
}
+4
View File
@@ -10,6 +10,8 @@ type SettingsShape = {
}
export type SiteMetaConfig = {
/** Site Settings → defaultShareImage (populated upload), used when a page has no OG image. */
defaultShareImage?: null | Record<string, unknown>
/**
* Home slug per locale, e.g. { pl: 'strona-glowna', de: 'startseite' }. A map
* (not a single string) so multilingual homepages collapse to root in EVERY
@@ -99,7 +101,9 @@ export async function readSiteMetaConfig({
homeSlug = { [locale]: homepage.slug }
}
const share = settings.defaultShareImage
return {
defaultShareImage: share && typeof share === 'object' ? (share as Record<string, unknown>) : null,
siteDescription: (settings.siteDescription as string | undefined) ?? null,
siteName: (settings[siteNameField] as string | undefined) ?? null,
// The panel stores '|'; titles need it padded.
+7 -1
View File
@@ -1,5 +1,6 @@
import type { BasePayload } from 'payload'
import type { ContentOption } from '../content/index.js'
import type { I18nConfig } from '../i18n/index.js'
import type { SitemapEntry } from './buildSitemapEntries.js'
@@ -29,6 +30,8 @@ import { buildSitemapCss, SITEMAP_STYLE_PARAM, type SitemapStyleOptions } from '
export function createLlmsTxtRoute(opts: {
baseUrl: string
config: I18nConfig
/** Archive-backed collections (blog…) — listed too. Same value as the plugin option. */
content?: ContentOption
/** Inline every page's full Markdown (llms-full.txt). Default false. */
full?: boolean
getCachedPayload: () => Promise<BasePayload>
@@ -43,6 +46,7 @@ export function createLlmsTxtRoute(opts: {
const body = await buildLlmsTxt({
baseUrl: opts.baseUrl,
config: opts.config,
content: opts.content,
full: opts.full,
pagesSlug: opts.pagesSlug,
payload,
@@ -50,7 +54,9 @@ export function createLlmsTxtRoute(opts: {
summaryField: opts.summaryField,
})
return new Response(body, {
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
// For AI agents, not a search result: keep it (and the full-content
// copy, a duplicate of every page) out of search indexes.
headers: { 'Content-Type': 'text/plain; charset=utf-8', 'X-Robots-Tag': 'noindex' },
})
} catch (err) {
// DB unreachable at build (container) — return a minimal valid file so the
+167
View File
@@ -0,0 +1,167 @@
import type { BasePayload } from 'payload'
import type { ContentOption } from '../content/index.js'
import type { I18nConfig } from '../i18n/index.js'
import { archiveFieldName } from '../content/index.js'
import { buildLocalizedPath, getLocaleCodes, isValidLocale } from '../i18n/index.js'
import { resolveLocalized } from '../i18n/resolveLocalized.js'
/** One public, indexable document in one language. */
export type SiteIndexEntry = {
/** Collection slug, e.g. 'pages', 'posts'. */
collection: string
/** Plural label of the collection in this locale (from the project's config), e.g. 'Pages'. */
collectionLabel: string
createdAt?: string
/** Summary field (when configured and filled) or meta.description. */
description?: string
/** The raw document in this locale — for callers that render content (llms-full). */
doc: Record<string, unknown>
id: number | string
locale: string
/** Locale-aware path, e.g. /pl/blog/moj-wpis. */
path: string
/** publishedAt when the collection has it (setPublishedAt hook). */
publishedAt?: string
title: string
updatedAt?: string
/** Absolute URL (path prefixed with baseUrl). */
url: string
}
export type CollectSiteIndexArgs = {
/** Absolute origin; omit for relative URLs. */
baseUrl?: string
config: I18nConfig
/** Archive-backed collections, same value as the plugin option — their entries are included. */
content?: ContentOption
/** Population depth of `doc`. Default 0 (1 when you render blocks with images). */
depth?: number
/** Max documents per collection and locale. Default 1000. */
limit?: number
/** Only these locales. Default: every configured locale. */
locales?: string[]
/** Pages collection. Default 'pages'. */
pagesSlug?: string
payload: BasePayload
/** SiteSettings global. Default 'site-settings'. */
settingsSlug?: string
/** Field holding a richer AI summary (buildSummaryField) to prefer as description. */
summaryField?: string
}
type Row = {
[key: string]: unknown
_status?: string
createdAt?: string
id: number | string
meta?: { description?: unknown; noindex?: boolean } | null
noindex?: boolean | null
publishedAt?: unknown
slug?: unknown
title?: unknown
updatedAt?: string
}
/** Same exclusions as the sitemap: error/system pages that exist as documents. */
const EXCLUDED_SLUGS = new Set(['404', '500', 'error', 'not-found'])
function slugMap(rel: unknown, locales: string[]): Record<string, string> | undefined {
if (!rel || typeof rel !== 'object') {return undefined}
const slug = (rel as { slug?: unknown }).slug
if (typeof slug === 'string') {return Object.fromEntries(locales.map((l) => [l, slug]))}
if (!slug || typeof slug !== 'object') {return undefined}
const map: Record<string, string> = {}
for (const l of locales) {
const v = (slug as Record<string, unknown>)[l]
if (typeof v === 'string') {map[l] = v}
}
return Object.keys(map).length ? map : undefined
}
/**
* Every public page and archive entry, per language, with its URL, title,
* description and dates — ONE source for everything that lists the site to
* machines: llms.txt / llms-full.txt, the MCP server's list_pages, IndexNow.
* Uses the same rules as the sitemap (published only, no noindex, no 404/500
* pages, archive prefixes and homepage from System Pages), so all of them
* agree with what the site actually serves.
*
* Never throws for a missing field: a collection that can't be read is skipped.
*/
export async function collectSiteIndex({
baseUrl,
config,
content,
depth = 0,
limit = 1000,
locales,
pagesSlug = 'pages',
payload,
settingsSlug = 'site-settings',
summaryField,
}: CollectSiteIndexArgs): Promise<SiteIndexEntry[]> {
const all = getLocaleCodes(config)
const wanted = (locales ?? all).filter((l) => isValidLocale(l, config))
const origin = baseUrl?.replace(/\/$/, '') ?? ''
let settings: Record<string, unknown> = {}
try {
settings = (await payload.findGlobal({ slug: settingsSlug as never, depth: 1, locale: 'all' as never })) as Record<string, unknown>
} catch {
// no settings yet (fresh DB) — no homepage/archives, plain paths
}
const homeSlug = slugMap(settings.homepage, all) ?? 'home'
const collections: { prefix?: Record<string, string>; slug: string }[] = [{ slug: pagesSlug }]
for (const c of content?.collections ?? []) {
const prefix = slugMap(settings[archiveFieldName(c.slug)], all)
collections.push({ slug: c.slug, prefix })
}
const entries: SiteIndexEntry[] = []
for (const locale of wanted) {
for (const { slug: collection, prefix } of collections) {
// An archive collection without an archive page in this locale has no URLs there.
if (collection !== pagesSlug && !prefix?.[locale]) {continue}
let docs: Row[] = []
try {
const res = await payload.find({ collection: collection as never, depth, limit, locale: locale as never })
docs = (res?.docs ?? []) as Row[]
} catch {
continue
}
const labels = payload.collections?.[collection as never]?.config?.labels as { plural?: unknown } | undefined
const collectionLabel = resolveLocalized(labels?.plural, locale, collection)
for (const doc of docs) {
if (doc._status && doc._status !== 'published') {continue}
if (doc.noindex || doc.meta?.noindex) {continue}
const title = typeof doc.title === 'string' ? doc.title.trim() : ''
const slug = typeof doc.slug === 'string' ? doc.slug : ''
if (!title || !slug || EXCLUDED_SLUGS.has(slug)) {continue}
const path = buildLocalizedPath({ config, homeSlug, locale, prefix, slugs: { [locale]: slug } })
if (!path) {continue}
const summary = summaryField && typeof doc[summaryField] === 'string' ? (doc[summaryField]).trim() : ''
const metaDescription = typeof doc.meta?.description === 'string' ? doc.meta.description.trim() : ''
const description = summary || metaDescription
entries.push({
id: doc.id,
collection,
collectionLabel,
doc,
locale,
path,
title,
url: `${origin}${path}`,
...(description ? { description } : {}),
...(typeof doc.createdAt === 'string' ? { createdAt: doc.createdAt } : {}),
...(typeof doc.updatedAt === 'string' ? { updatedAt: doc.updatedAt } : {}),
...(typeof doc.publishedAt === 'string' ? { publishedAt: doc.publishedAt } : {}),
})
}
}
}
return entries
}
+14
View File
@@ -0,0 +1,14 @@
/**
* Whole-site noindex for staging, previews and test copies: set IPAL_NOINDEX=1
* in that environment's env. Then robots.txt disallows everything, every page
* gets `robots: noindex, nofollow`, and buildSecurityHeaders adds
* `X-Robots-Tag: noindex, nofollow` to every response (files and API too).
* Production never sets it — a forgotten staging copy indexed by Google is a
* duplicate of the real site.
*/
export const SITE_NOINDEX_ENV = 'IPAL_NOINDEX'
export function isSiteNoindex(): boolean {
const v = process.env[SITE_NOINDEX_ENV]?.trim().toLowerCase()
return v === '1' || v === 'true' || v === 'yes'
}
+55
View File
@@ -0,0 +1,55 @@
'use client'
import { useState } from 'react'
type YouTubeEmbedProps = {
/** Classes per element; nothing is styled by default (keep the aspect ratio in your CSS). */
classNames?: Partial<Record<'button' | 'frame' | 'note' | 'poster' | 'root', string>>
/** Short text under the play button, from the panel — e.g. that playing loads YouTube. */
note?: string
/** Accessible name of the play button, from the panel ("Play: <title>"). */
playLabel: string
/**
* Poster URL — your own upload (no request to Google until play) or omit to
* use YouTube's thumbnail (i.ytimg.com, no cookies).
*/
poster?: string
/** Video title, from the panel — iframe title for screen readers. */
title: string
/** YouTube video id (the part after watch?v=). */
videoId: string
}
/**
* Lightweight YouTube: a poster and a play button until the visitor clicks —
* no ~1 MB of player JavaScript and no YouTube cookies on page load (better
* LCP, no consent problem before interaction). On click it loads the
* privacy-enhanced youtube-nocookie.com player with autoplay. Unstyled.
*/
export function YouTubeEmbed({ classNames = {}, note, playLabel, poster, title, videoId }: YouTubeEmbedProps) {
const [playing, setPlaying] = useState(false)
const id = /^[\w-]{6,20}$/.test(videoId) ? videoId : ''
if (!id) {return null}
if (playing) {
return (
<iframe
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowFullScreen
className={classNames.frame}
// What the YouTube player needs, nothing more (no top navigation, no forms).
sandbox="allow-scripts allow-same-origin allow-presentation allow-popups allow-popups-to-escape-sandbox"
src={`https://www.youtube-nocookie.com/embed/${id}?autoplay=1`}
title={title}
/>
)
}
return (
<div className={classNames.root}>
<img alt="" className={classNames.poster} decoding="async" loading="lazy" src={poster ?? `https://i.ytimg.com/vi/${id}/hqdefault.jpg`} />
<button aria-label={playLabel} className={classNames.button} onClick={() => setPlaying(true)} type="button">
▶
</button>
{note ? <p className={classNames.note}>{note}</p> : null}
</div>
)
}
+35
View File
@@ -0,0 +1,35 @@
type RemotePattern = { hostname: string; pathname?: string; port?: string; protocol?: 'http' | 'https' }
export type ImagesConfig = {
formats: ('image/avif' | 'image/webp')[]
minimumCacheTTL: number
remotePatterns: RemotePattern[]
}
/**
* Defaults for `next.config.ts → images`, to merge or override:
* - AVIF first, WebP fallback — ~20–50 % smaller than JPEG at the same quality;
* - remotePatterns for the media domain (R2_PUBLIC_URL) so next/image may
* optimize R2 files — otherwise it refuses them;
* - optimized images cached for 31 days (uploads get new names when replaced).
*
* import { buildImagesConfig } from '@intecion/ipal-kit'
* export default withPayload({ images: { ...buildImagesConfig(), /* your overrides *\/ } })
*/
export function buildImagesConfig({
extraHosts = [],
publicUrl = process.env.R2_PUBLIC_URL,
}: { extraHosts?: string[]; publicUrl?: string } = {}): ImagesConfig {
const remotePatterns: RemotePattern[] = []
if (publicUrl && /^https?:\/\//i.test(publicUrl)) {
const u = new URL(publicUrl)
remotePatterns.push({
hostname: u.hostname,
protocol: u.protocol.replace(':', '') as 'http' | 'https',
...(u.port ? { port: u.port } : {}),
pathname: `${u.pathname.replace(/\/$/, '')}/**`,
})
}
for (const host of extraHosts) {remotePatterns.push({ hostname: host, protocol: 'https' })}
return { formats: ['image/avif', 'image/webp'], minimumCacheTTL: 60 * 60 * 24 * 31, remotePatterns }
}
+2
View File
@@ -1,2 +1,4 @@
export { buildImagesConfig } from './buildImagesConfig.js'
export type { ImagesConfig } from './buildImagesConfig.js'
export { buildR2Storage } from './buildR2Storage.js'
export type { BuildR2StorageDeps, S3StorageFactory } from './buildR2Storage.js'
+44
View File
@@ -7,12 +7,14 @@ import { buildNotifications } from './globals/Notifications/index.js'
import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js'
import { buildSiteSettings } from './globals/SiteSettings/index.js'
import { injectRoles } from './modules/access/index.js'
import { buildConsentLogCollection, buildConsentLogEndpoint } from './modules/consent/consentLog.js'
import { buildArchiveFields } from './modules/content/index.js'
import { testEmailEndpoint } from './modules/email/test/testEmailEndpoint.js'
import { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js'
import { buildSystemPagesFields } from './modules/pages/index.js'
import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo/index.js'
import { buildIndexNowHook } from './modules/seo/indexNow.js'
/**
* IPAL (Intecion Payload Advanced Library) plugin for Payload CMS 3.
@@ -49,6 +51,23 @@ export const ipalKit = (options: IpalOptions): Plugin => {
let config = { ...incomingConfig }
// --- auth collection: Payload adds its default `users` only AFTER plugins
// run (config sanitize), so roles and 2FA would have nothing to attach to,
// and a project without it crashes ("users is not a valid admin user
// collection"). Inject a plain auth collection when the project defines
// none — a project's own collection with that slug always wins.
const authSlug =
options.access?.authCollection ??
(options.twoFactor ? options.twoFactor.collectionSlug : undefined) ??
config.admin?.user ??
'users'
if (!(config.collections ?? []).some((c) => c.slug === authSlug)) {
config.collections = [
...(config.collections ?? []),
{ slug: authSlug, admin: { useAsTitle: 'email' }, auth: true, fields: [] },
]
}
// --- custom admin route (e.g. '/its' instead of '/admin') ---
// Sets config.routes.admin; the project must move its app/(payload)/<route>/
// folder to match (plugin can't create files in the project's app/).
@@ -202,6 +221,31 @@ export const ipalKit = (options: IpalOptions): Plugin => {
config.endpoints = [...(config.endpoints ?? []), testEmailEndpoint]
// --- consent log: proof of consent (opt-in) ---
if (options.consentLog) {
const logOptions = options.consentLog === true ? {} : options.consentLog
config.collections = [...(config.collections ?? []), buildConsentLogCollection()]
config.endpoints = [...(config.endpoints ?? []), buildConsentLogEndpoint(logOptions)]
}
// --- IndexNow: submit published URLs (opt-in) ---
if (options.indexNow) {
const pagesSlug = options.pages?.slug ?? 'pages'
const contentSlugs = new Set((options.content?.collections ?? []).map((c) => c.slug))
config.collections = (config.collections ?? []).map((collection) => {
const isPages = collection.slug === pagesSlug
if (!isPages && !contentSlugs.has(collection.slug)) {return collection}
const hook = buildIndexNowHook({
config: options.i18n,
...(isPages ? {} : { contentCollection: collection.slug }),
})
return {
...collection,
hooks: { ...collection.hooks, afterChange: [...(collection.hooks?.afterChange ?? []), hook] },
}
})
}
// --- integration alerts on the dashboard (Turnstile status, …) ---
// Renders nothing while everything works; never throws.
config.admin = {
+47
View File
@@ -0,0 +1,47 @@
/*
* @intecion/ipal-kit/fluid-wide.css — the fluid.css scale stretched over 360 → 1920px.
* Same variable names: import ONE of the two. With fluid.css everything stops
* growing at 1280px, so a 13" laptop and a 27" monitor look the same; here type
* and spacing keep scaling up to 1920px (at 1280px they're a little smaller than
* in fluid.css — check the design at 1280, 1440 and 1920).
*
* @import "tailwindcss";
* @import "@intecion/ipal-kit/fluid-wide.css";
* @theme inline { --text-h1: var(--ipal-fs-h1); --spacing-section: var(--ipal-space-section); … }
*
* rem-based (browser zoom and user font size still work, WCAG 1.4.4). Override
* any variable in the project's :root.
*/
:root {
--ipal-fs-sm: clamp(0.875rem, 0.8606rem + 0.0641vw, 0.9375rem); /* 0.875→0.9375rem · small print, captions */
--ipal-fs-base: clamp(1rem, 0.9712rem + 0.1282vw, 1.125rem); /* 1→1.125rem · body text */
--ipal-fs-lg: clamp(1.125rem, 1.0673rem + 0.2564vw, 1.375rem); /* 1.125→1.375rem · lead / intro */
--ipal-fs-h3: clamp(1.25rem, 1.1346rem + 0.5128vw, 1.75rem); /* 1.25→1.75rem · h3 */
--ipal-fs-h2: clamp(1.5rem, 1.2692rem + 1.0256vw, 2.5rem); /* 1.5→2.5rem · h2 — section headings */
--ipal-fs-h1: clamp(2rem, 1.6538rem + 1.5385vw, 3.5rem); /* 2→3.5rem · h1 — page heading */
--ipal-fs-display: clamp(2.5rem, 2.0385rem + 2.0513vw, 4.5rem); /* 2.5→4.5rem · hero / display */
--ipal-space-gap: clamp(1rem, 0.7692rem + 1.0256vw, 2rem); /* 1→2rem · gap between items in a section */
--ipal-space-gutter: clamp(1rem, 0.6538rem + 1.5385vw, 2.5rem); /* 1→2.5rem · container side padding */
--ipal-space-section: clamp(3rem, 1.9615rem + 4.6154vw, 7.5rem); /* 3→7.5rem · vertical padding of a section */
}
/*
* Layout & height-aware helpers (added in 1.9.1 — nothing uses them until the
* project does, so existing sites look exactly the same):
* max-w-[var(--ipal-measure)] comfortable line length for running text
* --ipal-container / -wide content widths for the section container
* min-h-[var(--ipal-hero-min-h)] hero that fills a laptop screen, not a 4K one
* text-[length:var(--ipal-fs-display-fit)], py-[var(--ipal-space-section-fit)]
* shrink on SHORT screens (1366×768, 1280×720,
* landscape phones) so the hero CTA stays above the fold
* svh = the small viewport height (mobile browser bars shown) — never 100vh.
*/
:root {
--ipal-measure: 68ch;
--ipal-container: 80rem;
--ipal-container-wide: 96rem;
--ipal-hero-min-h: min(100svh, 56rem);
--ipal-fs-display-fit: min(var(--ipal-fs-display), 7svh + 0.75rem);
--ipal-fs-h1-fit: min(var(--ipal-fs-h1), 6svh + 0.5rem);
--ipal-space-section-fit: min(var(--ipal-space-section), 10svh);
}
+24
View File
@@ -19,6 +19,9 @@
*
* The design (DESIGN.md) decides the numbers: override any variable in the project's
* :root — the plugin only removes the clamp() maths from every project.
*
* Wider screens should keep growing (13" laptop → 27" monitor)? Import
* @intecion/ipal-kit/fluid-wide.css instead: same variables, scaled 360 → 1920px.
*/
:root {
--ipal-fs-sm: clamp(0.875rem, 0.8505rem + 0.1087vw, 0.9375rem); /* 0.875→0.9375rem · small print, captions */
@@ -32,3 +35,24 @@
--ipal-space-gutter: clamp(1rem, 0.413rem + 2.6087vw, 2.5rem); /* 1→2.5rem · container side padding */
--ipal-space-section: clamp(3rem, 1.2391rem + 7.8261vw, 7.5rem); /* 3→7.5rem · vertical padding of a section */
}
/*
* Layout & height-aware helpers (added in 1.9.1 — nothing uses them until the
* project does, so existing sites look exactly the same):
* max-w-[var(--ipal-measure)] comfortable line length for running text
* --ipal-container / -wide content widths for the section container
* min-h-[var(--ipal-hero-min-h)] hero that fills a laptop screen, not a 4K one
* text-[length:var(--ipal-fs-display-fit)], py-[var(--ipal-space-section-fit)]
* shrink on SHORT screens (1366×768, 1280×720,
* landscape phones) so the hero CTA stays above the fold
* svh = the small viewport height (mobile browser bars shown) — never 100vh.
*/
:root {
--ipal-measure: 68ch;
--ipal-container: 80rem;
--ipal-container-wide: 96rem;
--ipal-hero-min-h: min(100svh, 56rem);
--ipal-fs-display-fit: min(var(--ipal-fs-display), 7svh + 0.75rem);
--ipal-fs-h1-fit: min(var(--ipal-fs-h1), 6svh + 0.5rem);
--ipal-space-section-fit: min(var(--ipal-space-section), 10svh);
}
+17 -1
View File
@@ -42,6 +42,15 @@ export type IpalOptions = {
*/
adminRoute?: string
/** Internationalization — locales, default locale, fallback behavior */
/**
* Consent log (proof of consent, GDPR Art. 7(1)): adds the `consent-records`
* collection and POST /api/ipal/consent. Pass `<ConsentProvider logEndpoint="/api/ipal/consent">`.
* Stores a random id, choices, policy version and time — no personal data.
* `true` or `{ retentionDays }` (default 1095). Default off.
*/
consentLog?: { retentionDays?: number } | boolean
/**
* Collections whose entries live under an archive page — blog posts, case
* studies, anything with a listing. Adds an "archive page" assignment per
@@ -59,9 +68,16 @@ export type IpalOptions = {
*/
forms?: FormsOption
/** Internationalization — locales, default locale, fallback behavior */
i18n: I18nConfig
/**
* IndexNow (seo/indexNow.ts): on publish, submit the page's URLs in every
* language to Bing & co. (feeds ChatGPT Search / Copilot). Adds the hook to the
* pages collection and every `content` collection. Production only. Needs the
* key file route createIndexNowKeyRoute. Default false.
*/
indexNow?: boolean
/** Additional fields injected into SiteIntegrations global */
integrationsFields?: Field[]
+89
View File
@@ -0,0 +1,89 @@
/** Unpublished drafts must never be served by the public routing helpers. */
import type { Payload } from 'payload'
import { sqliteAdapter } from '@payloadcms/db-sqlite'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'os'
import path from 'path'
import { buildConfig, getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test } from 'vitest'
import { resolveRoute } from '../src/modules/content/resolveRoute.js'
import { buildNoindexField } from '../src/modules/seo/buildNoindexField.js'
import { ipalKit } from '../src/plugin.js'
let payload: Payload
beforeAll(async () => {
const config = buildConfig({
collections: [
{
slug: 'pages',
fields: [
{ name: 'title', type: 'text' },
{ name: 'slug', type: 'text', localized: true },
buildNoindexField(),
],
versions: { drafts: true },
},
{ slug: 'posts', fields: [{ name: 'title', type: 'text' }, { name: 'slug', type: 'text', localized: true }], versions: { drafts: true } },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
],
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
editor: lexicalEditor(),
plugins: [
ipalKit({
access: { authCollection: 'users' },
content: { collections: [{ slug: 'posts' }] },
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
pages: { slug: 'pages' },
twoFactor: false,
}),
],
secret: 'drafts-test',
telemetry: false,
})
payload = await getPayload({ config })
}, 60_000)
afterAll(async () => {
await payload?.destroy()
})
describe('drafts', () => {
test('a never-published draft page is not resolvable', async () => {
await payload.create({ collection: 'pages' as never, data: { slug: 'tajne', _status: 'draft', title: 'Tajne' } as never, draft: true })
expect(await resolveRoute({ locale: 'pl', payload, segments: ['tajne'] })).toBeNull()
})
test('a published page is resolvable, and a later draft does not replace it', async () => {
const doc = await payload.create({ collection: 'pages' as never, data: { slug: 'oferta', _status: 'published', title: 'Oferta' } as never })
await payload.update({ id: doc.id, collection: 'pages' as never, data: { title: 'Oferta — szkic zmian' } as never, draft: true })
const route = await resolveRoute({ locale: 'pl', payload, segments: ['oferta'] })
expect((route?.doc as { title?: string })?.title).toBe('Oferta')
})
})
describe('archive listing', () => {
test('lists only published entries when the collection has drafts', async () => {
const { getArchiveEntries } = await import('../src/modules/content/getArchiveEntries.js')
await payload.create({ collection: 'posts' as never, data: { slug: 'jawny', _status: 'published', title: 'Jawny' } as never })
await payload.create({ collection: 'posts' as never, data: { slug: 'szkic', _status: 'draft', title: 'Szkic' } as never, draft: true })
const list = await getArchiveEntries({ collection: 'posts', locale: 'pl', payload })
expect(list.docs.map((d) => (d as { title: string }).title)).toEqual(['Jawny'])
expect(list.totalDocs).toBe(1)
const preview = await getArchiveEntries({ collection: 'posts', draft: true, locale: 'pl', payload })
expect(preview.totalDocs).toBe(2)
})
})
describe('noindex protection', () => {
test('the homepage cannot be set to noindex; an ordinary page can', async () => {
const home = await payload.create({ collection: 'pages' as never, data: { slug: 'start', _status: 'published', title: 'Start' } as never })
const other = await payload.create({ collection: 'pages' as never, data: { slug: 'dziekujemy', _status: 'published', title: 'Dziękujemy' } as never })
await payload.updateGlobal({ slug: 'site-settings' as never, data: { homepage: home.id, siteName: 'Acme' } as never })
await expect(payload.update({ id: home.id, collection: 'pages' as never, data: { noindex: true } as never })).rejects.toThrow(/Exclude from indexing/)
const updated = (await payload.update({ id: other.id, collection: 'pages' as never, data: { noindex: true } as never })) as { noindex?: boolean }
expect(updated.noindex).toBe(true)
})
})
+37
View File
@@ -0,0 +1,37 @@
import { existsSync, 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 pkg = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8')) as { exports: Record<string, unknown> }
function files(dir: string): string[] {
return readdirSync(dir).flatMap((name) => {
const p = path.join(dir, name)
return statSync(p).isDirectory() ? files(p) : /\.(?:md|ts|tsx|mjs)$/.test(name) ? [p] : []
})
}
describe('package exports', () => {
test('every @intecion/ipal-kit/<subpath> used in docs and src is exported', () => {
const used = new Map<string, string>()
for (const file of [...files(path.join(root, 'docs')), ...files(path.join(root, 'src'))]) {
for (const m of readFileSync(file, 'utf8').matchAll(/@intecion\/ipal-kit(?<sub>\/[a-z0-9./-]+)?(?=['"#\s`)])/g)) {
const sub = m.groups?.sub ? `.${m.groups.sub}` : '.'
// node_modules/@intecion/ipal-kit/dist|docs|package.json — filesystem paths in prose, not imports
if (/^\.\/(?:dist|docs|package\.json)(?:\/|$)/.test(sub)) {continue}
if (!used.has(sub)) {used.set(sub, path.relative(root, file))}
}
}
const missing = [...used].filter(([sub]) => !(sub in pkg.exports)).map(([sub, file]) => `${sub} (e.g. ${file})`)
expect(missing).toEqual([])
})
test('every export points at a file the build produces from src', () => {
for (const [sub, target] of Object.entries(pkg.exports)) {
const out = typeof target === 'string' ? target : (target as { import: string }).import
const src = out.replace('./dist/', 'src/').replace(/\.js$/, '.ts')
expect(existsSync(path.join(root, src)) || existsSync(path.join(root, src.replace(/\.ts$/, '.tsx'))), `${sub} → ${src}`).toBe(true)
}
})
})
+67
View File
@@ -0,0 +1,67 @@
import { describe, expect, test } from 'vitest'
import { validateSubmission } from '../src/modules/forms/validateSubmission.js'
import { fakePayload } from './helpers.js'
const forms = {
f: {
fields: [
{ name: 'name', blockType: 'text' },
{ name: 'email', blockType: 'email' },
{ name: 'topic', blockType: 'select', options: [{ value: 'offer' }, { value: 'support' }] },
{ name: 'count', blockType: 'number' },
{ name: 'message', blockType: 'textarea' },
{ name: 'agree', blockType: 'checkbox' },
],
},
}
const { payload } = fakePayload({ forms })
const check = (data: Record<string, unknown>) => validateSubmission(payload, 'f', data)
describe('form validation — injection and abuse', () => {
test.each([
['[email protected], [email protected]'],
['[email protected];[email protected]'],
['[email protected]\r\nBcc: [email protected]'],
['Name <[email protected]>'],
['not-an-email'],
[`${'a'.repeat(250)}@x.pl`],
])('email %j is rejected — no extra recipients or headers', async (email) => {
expect(await check({ email })).toMatchObject({ field: 'email', kind: 'invalid_format', ok: false })
})
test('a valid email is trimmed and kept', async () => {
expect(await check({ email: ' [email protected] ' })).toMatchObject({
cleaned: { email: '[email protected]' },
ok: true,
})
})
test('select accepts only values configured in the panel', async () => {
expect(await check({ topic: 'offer' })).toMatchObject({ ok: true })
expect(await check({ topic: '<script>alert(1)</script>' })).toMatchObject({ field: 'topic', kind: 'invalid_format' })
})
test('objects, arrays and wrong types are rejected', async () => {
expect(await check({ name: { $gt: '' } })).toMatchObject({ field: 'name', kind: 'invalid_format' })
expect(await check({ message: ['a', 'b'] })).toMatchObject({ field: 'message', kind: 'invalid_format' })
expect(await check({ count: '12abc' })).toMatchObject({ field: 'count', kind: 'invalid_format' })
expect(await check({ agree: 'true' })).toMatchObject({ field: 'agree', kind: 'invalid_format' })
})
test('control and bidi characters are stripped; single-line text loses line breaks', async () => {
const res = await check({ name: 'Jan\r\nKowalski\u0007', message: 'Dzień\u0000 dobry‮\nlinia 2' })
expect(res).toMatchObject({ cleaned: { name: 'Jan Kowalski', message: 'Dzień dobry\nlinia 2' }, ok: true })
})
test('HTML is stored as text (the renderer and e-mails escape it)', async () => {
expect(await check({ message: '<img src=x onerror=alert(1)>' })).toMatchObject({
cleaned: { message: '<img src=x onerror=alert(1)>' },
ok: true,
})
})
test('numbers are normalized', async () => {
expect(await check({ count: ' 42 ' })).toMatchObject({ cleaned: { count: 42 }, ok: true })
})
})
+95
View File
@@ -0,0 +1,95 @@
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { buildIndexNowHook, createIndexNowKeyRoute, indexNowFields } from '../src/modules/seo/indexNow.js'
const config: I18nConfig = {
defaultLocale: 'pl',
locales: [
{ code: 'pl', label: 'Polski' },
{ code: 'en', label: 'English' },
],
}
function fakeReq(doc: Record<string, unknown>, settings: Record<string, unknown>) {
return {
payload: {
findByID: vi.fn(async () => doc),
findGlobal: vi.fn(async ({ slug }: { slug: string }) => (slug === 'site-integrations' ? { indexNowKey: 'k123' } : settings)),
},
}
}
const flush = () => new Promise((r) => setTimeout(r, 0))
describe('IndexNow hook', () => {
let fetchSpy: ReturnType<typeof vi.spyOn>
beforeEach(() => {
fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, { status: 202 }))
vi.stubEnv('NODE_ENV', 'production')
vi.stubEnv('NEXT_PUBLIC_SERVER_URL', 'https://acme.pl')
})
afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllEnvs()
})
const run = async (row: Record<string, unknown>, opts = {}, settings: Record<string, unknown> = {}) => {
const req = fakeReq({ slug: { en: 'about', pl: 'o-nas' } }, settings)
const hook = buildIndexNowHook({ config, ...opts })
await hook({ collection: { slug: 'pages' }, context: {}, doc: { id: 1, ...row }, req } as never)
await flush()
await flush()
}
test('published page → every language submitted with key and keyLocation', async () => {
await run({ _status: 'published' })
expect(fetchSpy).toHaveBeenCalledOnce()
const body = JSON.parse((fetchSpy.mock.calls[0][1] as RequestInit).body as string)
expect(body).toEqual({
host: 'acme.pl',
key: 'k123',
keyLocation: 'https://acme.pl/indexnow-key.txt',
urlList: ['https://acme.pl/pl/o-nas', 'https://acme.pl/en/about'],
})
})
test('archive entry gets the archive prefix; no archive page → nothing sent', async () => {
await run({}, { contentCollection: 'posts' }, { postsArchive: { slug: { en: 'blog', pl: 'blog-pl' } } })
const body = JSON.parse((fetchSpy.mock.calls[0][1] as RequestInit).body as string)
expect(body.urlList).toEqual(['https://acme.pl/pl/blog-pl/o-nas', 'https://acme.pl/en/blog/about'])
fetchSpy.mockClear()
await run({}, { contentCollection: 'posts' }, {})
expect(fetchSpy).not.toHaveBeenCalled()
})
test('drafts, noindex, dev and localhost send nothing', async () => {
await run({ _status: 'draft' })
await run({ noindex: true })
vi.stubEnv('NODE_ENV', 'development')
await run({})
vi.stubEnv('NODE_ENV', 'production')
vi.stubEnv('NEXT_PUBLIC_SERVER_URL', 'http://localhost:3000')
await run({})
expect(fetchSpy).not.toHaveBeenCalled()
})
})
describe('IndexNow key', () => {
afterEach(() => vi.unstubAllEnvs())
test('field generates a 32-char key when empty and keeps an existing one', () => {
const hook = (indexNowFields[0] as { hooks: { beforeChange: ((a: { value: unknown }) => string)[] } }).hooks.beforeChange[0]
expect(hook({ value: '' })).toMatch(/^[0-9a-f]{32}$/)
expect(hook({ value: ' mine ' })).toBe('mine')
})
test('key route: env wins, 404 without a key', async () => {
const payload = { findGlobal: async () => ({}) } as never
expect((await createIndexNowKeyRoute({ getCachedPayload: async () => payload })()).status).toBe(404)
vi.stubEnv('INDEXNOW_KEY', 'fromenv')
const res = await createIndexNowKeyRoute({ getCachedPayload: async () => payload })()
expect(await res.text()).toBe('fromenv')
})
})
+86
View File
@@ -12,6 +12,8 @@ import path from 'path'
import { buildConfig, getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
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 { ipalKit } from '../src/plugin.js'
@@ -42,6 +44,7 @@ beforeAll(async () => {
plugins: [
ipalKit({
access: { authCollection: 'users' },
consentLog: true,
forms: {},
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
twoFactor: false,
@@ -156,3 +159,86 @@ describe('generatePageMetadata — markdownAlternate', () => {
expect((await off.generatePageMetadata('pl', ['o-nas'])).alternates?.types).toBeUndefined()
})
})
describe('getPageJsonLd', () => {
const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] } as const
test('WebPage + breadcrumbs from the real route, FAQ when mapped, no @context per node', async () => {
await payload.create({ collection: 'pages' as never, data: { slug: 'kontakt', title: 'Kontakt' } as never })
const h = createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n })
const nodes = await h.getPageJsonLd('pl', ['kontakt'], {
faq: () => [{ answer: 'Tak.', question: 'Czy dojeżdżacie?' }, { answer: '', question: 'puste' }],
pageType: () => 'ContactPage',
})
expect(nodes.map((n) => n['@type'])).toEqual(['ContactPage', 'BreadcrumbList', 'FAQPage'])
expect(nodes[0]).toMatchObject({ name: 'Kontakt', '@id': 'https://acme.pl/kontakt', inLanguage: 'pl' })
expect(nodes.every((n) => !('@context' in n))).toBe(true)
expect((nodes[2] as { mainEntity: unknown[] }).mainEntity).toHaveLength(1)
expect(await h.getPageJsonLd('pl', ['nie-ma'])).toEqual([])
})
})
describe('consent log', () => {
const post = (body: unknown, ip = '10.6.0.1') =>
buildConsentLogEndpoint().handler({
headers: new Headers({ 'x-real-ip': ip }),
json: async () => body,
payload,
} as never) as Promise<Response>
const state = { analytics: true, functional: false, marketing: false, necessary: true }
test('stores id, choices and version only', async () => {
const res = await post({ id: 'a1b2c3d4e5f6a7b8c9d0e1f2', state, version: 2 })
expect(res.status).toBe(201)
const { docs } = await payload.find({ collection: 'consent-records' as never, where: { consentId: { equals: 'a1b2c3d4e5f6a7b8c9d0e1f2' } } })
const rec = docs[0] as unknown as Record<string, unknown>
expect(rec).toMatchObject({ choices: state, version: 2 })
expect(Object.keys(rec).filter((k) => /ip|agent|email/i.test(k))).toEqual([])
})
test('rejects malformed records', async () => {
for (const bad of [{}, { id: 'x', state, version: 1 }, { id: 'a1b2c3d4e5f6a7b8', state: { analytics: 'yes' }, version: 1 }, { id: 'a1b2c3d4e5f6a7b8', state, version: 0 }]) {
expect((await post(bad, '10.6.0.2')).status).toBe(400)
}
})
test('the collection is not writable or readable anonymously', async () => {
await expect(payload.find({ collection: 'consent-records' as never, overrideAccess: false })).rejects.toThrow()
})
})
describe('cookie table', () => {
test('rows from Cookie Settings in the requested language', async () => {
await payload.updateGlobal({
slug: 'cookie-settings' as never,
data: { cookies: [{ name: '_ga', category: 'analytics', duration: '2 lata', provider: 'Google', purpose: 'Statystyki' }, { name: ' ' }] } as never,
locale: 'pl' as never,
})
expect(await getCookieTable({ locale: 'pl', payload })).toEqual([
{ name: '_ga', category: 'analytics', duration: '2 lata', provider: 'Google', purpose: 'Statystyki' },
])
})
})
describe('forms access', () => {
test('anonymous REST read of a form hides its e-mail recipients; submissions are staff-only', async () => {
await payload.update({
id: formId,
collection: 'forms' as never,
data: { emails: [{ emailTo: '[email protected]', subject: 'Nowe zgłoszenie' }] } as never,
})
const anon = (await payload.findByID({ id: formId, collection: 'forms' as never, overrideAccess: false })) as Record<string, unknown>
expect(anon.fields).toBeDefined()
expect(JSON.stringify(anon.emails ?? [])).not.toContain('[email protected]')
const user = (await payload.create({
collection: 'users',
data: { email: '[email protected]', password: 'Passw0rd!x' } as never,
})) as unknown as Record<string, unknown>
await expect(
payload.find({ collection: 'form-submissions' as never, overrideAccess: false, user: { ...user, collection: 'users' } as never }),
).rejects.toThrow()
const editor = { ...user, collection: 'users', roles: ['editor'] }
expect((await payload.find({ collection: 'form-submissions' as never, overrideAccess: false, user: editor as never })).totalDocs).toBeGreaterThan(0)
})
})
+84
View File
@@ -0,0 +1,84 @@
import sharp from 'sharp'
import { describe, expect, test, vi } from 'vitest'
import { MEDIA_SIZES, mediaImageProps, videoProps } from '../src/modules/media/mediaProps.js'
import { buildMediaPlaceholderHook } from '../src/modules/media/placeholder.js'
import { buildImagesConfig } from '../src/modules/storage/buildImagesConfig.js'
const image = { alt: 'Ekipa przy pracy', height: 800, mimeType: 'image/webp', url: '/media/a.webp', width: 1200 }
describe('mediaImageProps', () => {
test('lazy by default, dimensions from the document', () => {
expect(mediaImageProps(image, { sizes: MEDIA_SIZES.half })).toEqual({
alt: 'Ekipa przy pracy',
height: 800,
loading: 'lazy',
sizes: '(min-width: 768px) 50vw, 100vw',
src: '/media/a.webp',
width: 1200,
})
})
test('LCP image: preload + high priority + eager', () => {
expect(mediaImageProps(image, { priority: true })).toMatchObject({ fetchPriority: 'high', loading: 'eager', preload: true })
})
test('placeholder and focal point', () => {
const p = mediaImageProps({ ...image, focalX: 30, focalY: 70, placeholder: { blurDataURL: 'data:x', color: '#123456' } })
expect(p).toMatchObject({ blurDataURL: 'data:x', placeholder: 'blur', style: { backgroundColor: '#123456', objectPosition: '30% 70%' } })
expect(mediaImageProps({ ...image, focalX: 50, focalY: 50 })?.style).toBeUndefined()
})
test('video, PDF and bare ids give null; decorative alt override', () => {
expect(mediaImageProps({ ...image, mimeType: 'video/mp4' })).toBeNull()
expect(mediaImageProps({ mimeType: 'application/pdf', url: '/x.pdf' })).toBeNull()
expect(mediaImageProps(42)).toBeNull()
expect(mediaImageProps(image, { alt: '' })?.alt).toBe('')
})
})
describe('videoProps', () => {
const video = { mimeType: 'video/mp4', url: '/media/v.mp4' }
test('player: controls, nothing downloaded before play', () => {
expect(videoProps(video, { poster: { url: '/media/p.webp' } })).toEqual({
controls: true,
playsInline: true,
poster: '/media/p.webp',
preload: 'none',
src: '/media/v.mp4',
})
})
test('background: muted loop, no autoplay with reduced motion', () => {
expect(videoProps(video, { mode: 'background' })).toMatchObject({ autoPlay: true, loop: true, muted: true })
expect(videoProps(video, { mode: 'background', reducedMotion: true })?.autoPlay).toBe(false)
expect(videoProps(image)).toBeNull()
})
})
describe('buildImagesConfig', () => {
test('AVIF/WebP and the R2 domain', () => {
expect(buildImagesConfig({ publicUrl: 'https://media.acme.pl/' })).toEqual({
formats: ['image/avif', 'image/webp'],
minimumCacheTTL: 2678400,
remotePatterns: [{ hostname: 'media.acme.pl', pathname: '/**', protocol: 'https' }],
})
expect(buildImagesConfig({ publicUrl: '/media' }).remotePatterns).toEqual([])
})
})
describe('buildMediaPlaceholderHook', () => {
test('stores a tiny blur image and the dominant colour; skips non-raster files', async () => {
const png = await sharp({ create: { background: { b: 40, g: 120, r: 200 }, channels: 3, height: 300, width: 400 } }).png().toBuffer()
const data: Record<string, unknown> = {}
const req = { file: { data: png, mimetype: 'image/png' }, payload: { config: { sharp }, logger: { warn: vi.fn() } } }
await buildMediaPlaceholderHook()({ args: { data }, operation: 'create', req } as never)
const ph = data.placeholder as { blurDataURL: string; color: string }
expect(ph.blurDataURL).toMatch(/^data:image\/webp;base64,/)
expect(ph.blurDataURL.length).toBeLessThan(600)
expect(ph.color).toBe('#c87828')
const svgData: Record<string, unknown> = {}
await buildMediaPlaceholderHook()({ args: { data: svgData }, operation: 'create', req: { ...req, file: { data: png, mimetype: 'image/svg+xml' } } } as never)
expect(svgData.placeholder).toBeUndefined()
})
})
+30
View File
@@ -0,0 +1,30 @@
import { describe, expect, test } from 'vitest'
import { formatOpeningHours } from '../src/modules/seo/formatOpeningHours.js'
describe('formatOpeningHours', () => {
test.each([
['Pn-Pt: 08:00 - 17:00, Sob: 08:00 - 14:00', ['Mo-Fr 08:00-17:00', 'Sa 08:00-14:00']],
['Pn–Pt 8–17, Sob: 8-14, Nd: nieczynne', ['Mo-Fr 08:00-17:00', 'Sa 08:00-14:00']],
['Poniedziałek - Piątek: 9.30 - 17.30\nSobota: 10-14\nNiedziela: zamknięte', ['Mo-Fr 09:30-17:30', 'Sa 10:00-14:00']],
['Pn do Pt 8:00 do 16:00', ['Mo-Fr 08:00-16:00']],
['Sob: nieczynne, Nd 10-14', ['Su 10:00-14:00']],
['Pn, Śr, Pt 9-17', ['Mo,We,Fr 09:00-17:00']],
['Mon–Fri 9am... no: 9:00-18:00; Sat 10:00 to 15:00', ['Mo-Fr 09:00-18:00', 'Sa 10:00-15:00']],
['Mo–Fr 8–16 Uhr; Sa 9–12; So geschlossen', ['Mo-Fr 08:00-16:00', 'Sa 09:00-12:00']],
['Do 10-18', ['Th 10:00-18:00']],
['całodobowo', ['Mo-Su 00:00-23:59']],
['24/7', ['Mo-Su 00:00-23:59']],
['Pn-Pt 8-24', ['Mo-Fr 08:00-23:59']],
])('%s', (input, expected) => {
expect(formatOpeningHours(input)).toEqual(expected)
})
test('schema.org strings and arrays pass through; junk is dropped', () => {
expect(formatOpeningHours(['Mo-Fr 08:00-17:00', 'Sa 09:00-13:00'])).toEqual(['Mo-Fr 08:00-17:00', 'Sa 09:00-13:00'])
expect(formatOpeningHours(['Pn-Pt 8-16', 'Sa 09:00-13:00'])).toEqual(['Mo-Fr 08:00-16:00', 'Sa 09:00-13:00'])
expect(formatOpeningHours('zadzwoń, umówimy się')).toEqual([])
expect(formatOpeningHours('Pn-Pt 25-30')).toEqual([])
expect(formatOpeningHours(undefined)).toEqual([])
})
})
+23
View File
@@ -54,3 +54,26 @@ describe('ipalKit — config transform', () => {
expect(() => ipalKit({ i18n: { defaultLocale: 'de', locales: i18n.locales }, twoFactor: false })).toThrow()
})
})
describe('ipalKit — auth collection', () => {
test('injects a users auth collection when the project has none, with roles', async () => {
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })({
collections: [],
secret: 'x',
} as unknown as Config)
const users = config.collections?.find((c) => c.slug === 'users')
expect(users?.auth).toBe(true)
expect(users?.fields.some((f) => 'name' in f && f.name === 'roles')).toBe(true)
})
test("keeps the project's own users collection", async () => {
const own = { slug: 'users', auth: true, fields: [{ name: 'fullName', type: 'text' }] }
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })({
collections: [own],
secret: 'x',
} as unknown as Config)
const users = config.collections?.filter((c) => c.slug === 'users')
expect(users).toHaveLength(1)
expect(users?.[0].fields.some((f) => 'name' in f && f.name === 'fullName')).toBe(true)
})
})
+100
View File
@@ -159,3 +159,103 @@ describe('consent cookie', () => {
expect(parseConsent(undefined)).toBeNull()
})
})
describe('buildNavigationJsonLd', () => {
test('resolves page links per locale, keeps own-site links only, dedupes, walks submenus', async () => {
const { buildNavigationJsonLd } = await import('../src/modules/seo/buildSiteNavigationJsonLd.js')
const page = (slug: string) => ({ type: 'internal' as const, page: { slug } })
const nav = buildNavigationJsonLd({
baseUrl: 'https://acme.pl/',
config,
homeSlug: { en: 'home', pl: 'start' },
items: [
{ link: { ...page('start'), label: 'Start' } },
{ link: { ...page('uslugi'), label: 'Usługi' }, subItems: [{ link: { ...page('audyt'), label: 'Audyt' } }] },
{ link: { type: 'external', label: 'Blog firmy X', url: 'https://medium.com/x' } },
{ link: { ...page('uslugi'), label: 'Usługi (dup)' } },
{ link: { ...page('bez-etykiety') } },
],
locale: 'pl',
})
expect(nav?.itemListElement.map((i: { name: string; url: string }) => [i.name, i.url])).toEqual([
['Start', 'https://acme.pl/pl'],
['Usługi', 'https://acme.pl/pl/uslugi'],
['Audyt', 'https://acme.pl/pl/audyt'],
])
})
})
describe('buildCsp — googleMaps', () => {
test('covers Maps JS API domains in every needed directive, no duplicates', () => {
const { value } = buildCsp({ googleMaps: true })
const dir = (name: string) => value.split('; ').find((d) => d.startsWith(`${name} `)) ?? ''
for (const d of ['script-src', 'img-src', 'connect-src']) {
expect(dir(d)).toContain('https://*.googleapis.com')
expect(dir(d)).toContain('https://*.gstatic.com')
}
expect(dir('frame-src')).toContain('https://*.google.com')
expect(dir('worker-src')).toContain('blob:')
for (const d of value.split('; ')) {
const parts = d.split(' ').slice(1)
expect(new Set(parts).size).toBe(parts.length)
}
expect(buildCsp().value).toContain('https://fonts.gstatic.com')
})
})
describe('consent storage — version and id', () => {
test('a consent from another policy version is ignored; id round-trips', async () => {
const { readConsentRecord, serializeConsent } = await import('../src/modules/consent/storage.js')
const state = { analytics: true, functional: true, marketing: false, necessary: true }
const raw = serializeConsent(state, 2, 'abc123')
expect(readConsentRecord(raw, 2)).toMatchObject({ id: 'abc123', state, version: 2 })
expect(readConsentRecord(raw, 3)).toBeNull()
expect(readConsentRecord(raw)).toBeNull() // default version 1
})
})
describe('safeHref / resolveLinkHref', () => {
test('only safe schemes survive', async () => {
const { resolveLinkHref, safeHref } = await import('../src/modules/links/resolveLinkHref.js')
for (const ok of ['https://acme.pl', 'mailto:[email protected]', 'tel:+48123', '#kontakt', '/pl/o-nas']) {expect(safeHref(ok)).toBe(ok)}
for (const bad of ['javascript:alert(1)', ' JavaScript:alert(1)', 'java\tscript:alert(1)', 'data:text/html,x', '//evil.com', 'vbscript:x', '']) {
expect(safeHref(bad)).toBeNull()
}
expect(resolveLinkHref({ type: 'external', url: 'javascript:alert(1)' }, { config, locale: 'pl' })).toBeNull()
})
})
describe('buildUploadSecurityHeaders', () => {
test('sandboxes files served from upload routes', async () => {
const { buildUploadSecurityHeaders } = await import('../src/modules/security/buildSecurityHeaders.js')
const rules = buildUploadSecurityHeaders({ collections: ['media', 'documents'] })
expect(rules.map((r) => r.source)).toEqual(['/api/media/file/:path*', '/api/documents/file/:path*'])
const csp = rules[0].headers.find((h) => h.key === 'Content-Security-Policy')?.value ?? ''
expect(csp).toContain('sandbox')
expect(csp).toContain("default-src 'none'")
expect(csp).not.toContain('script-src')
})
})
describe('site-wide noindex (IPAL_NOINDEX) and Markdown headers', () => {
test('staging blocks crawling everywhere', async () => {
const { vi } = await import('vitest')
vi.stubEnv('IPAL_NOINDEX', '1')
try {
expect(buildRobots({ baseUrl: 'https://staging.acme.pl' })).toEqual({ rules: { disallow: ['/'], userAgent: '*' } })
expect(buildSecurityHeaders().find((h) => h.key === 'X-Robots-Tag')?.value).toBe('noindex, nofollow')
const { buildMetadata } = await import('../src/modules/seo/buildMetadata.js')
expect(buildMetadata({ config, locale: 'pl', slugs: { pl: 'x' } }).robots).toEqual({ follow: false, index: false })
} finally {
vi.unstubAllEnvs()
}
expect(buildSecurityHeaders().some((h) => h.key === 'X-Robots-Tag')).toBe(false)
})
test('Markdown mirrors are noindex with a canonical link to the HTML page', async () => {
const { markdownResponse } = await import('../src/modules/content/createMarkdownRenderer.js')
const res = markdownResponse('# x', { canonical: 'https://acme.pl/pl/o-nas' })
expect(res.headers.get('x-robots-tag')).toBe('noindex')
expect(res.headers.get('link')).toBe('<https://acme.pl/pl/o-nas>; rel="canonical"')
})
})
+40
View File
@@ -0,0 +1,40 @@
import { afterEach, describe, expect, test, vi } from 'vitest'
import { createSubmitAction } from '../src/modules/forms/createSubmitAction.js'
import { fakePayload } from './helpers.js'
vi.mock('server-only', () => ({}))
const forms = { contact: { fields: [{ name: 'name', blockType: 'text', required: true }] } }
describe('createSubmitAction', () => {
afterEach(() => vi.restoreAllMocks())
const make = (ip: string) => {
const { create, payload } = fakePayload({ forms })
;(payload as unknown as { findGlobal: unknown }).findGlobal = vi.fn(async ({ slug }: { slug: string }) =>
slug === 'notifications' ? { form: { success: 'Dzięki!', validation: 'Uzupełnij pola' } } : {},
)
const sendForm = createSubmitAction({ getCachedPayload: async () => payload, headers: () => new Headers({ 'x-real-ip': ip }) })
return { create, sendForm }
}
test('valid submission → stored, message from Notifications', async () => {
const { create, sendForm } = make('10.8.0.1')
expect(await sendForm('contact', 'pl', { name: 'Ala' })).toEqual({ message: 'Dzięki!', success: true })
expect(create).toHaveBeenCalledOnce()
})
test('honeypot → fake success, nothing stored; field is stripped otherwise', async () => {
const { create, sendForm } = make('10.8.0.2')
expect((await sendForm('contact', 'pl', { name: 'x', company_url: 'http://spam' })).success).toBe(true)
expect(create).not.toHaveBeenCalled()
expect((await sendForm('contact', 'pl', { name: 'Ala', company_url: '' })).success).toBe(true)
expect(create).toHaveBeenCalledOnce()
})
test('failure carries reason and field for the renderer', async () => {
const { sendForm } = make('10.8.0.3')
expect(await sendForm('contact', 'pl', {})).toMatchObject({ field: 'name', reason: 'validation', success: false })
})
})