Compare commits

...
10 Commits
Author SHA1 Message Date
radoslaw.smolinski c0d9911d90 1.7.12 2026-10-13 00:36:25 +02:00
radoslaw.smolinski 103c796e9d Instruction clarification 2026-10-13 00:36:11 +02:00
radoslaw.smolinski c6f177a37d 1.7.10 2026-10-12 22:31:50 +02:00
radoslaw.smolinski 1a9c51a1fd Add fix for branding 2026-10-12 22:31:40 +02:00
radoslaw.smolinski 7f5ed75f9e 1.7.9 2026-10-12 19:47:37 +02:00
radoslaw.smolinski 4eb2b627f0 Analytics fix 2026-10-12 19:47:31 +02:00
radoslaw.smolinski a92fc02cdf 1.7.8 2026-10-12 17:32:41 +02:00
radoslaw.smolinski 7aebe24236 Added not-found support for sitesettings 2026-10-12 17:32:31 +02:00
radoslaw.smolinski c852d7bdae 1.7.7 2026-10-12 14:47:59 +02:00
radoslaw.smolinski 24fa3fdcdf Security fix for MCP 2026-10-12 14:47:50 +02:00
92 changed files with 3753 additions and 2129 deletions
+5 -5
View File
@@ -71,7 +71,7 @@ pnpm add @payloadcms/[email protected] @payloadcms/[email protected] \
> If your project pulls a different major (e.g. `1.x`), you end up with two copies
> and confusing type errors. Pin your project to the same range.
From here, the guide takes over: **[docs/getting-started.md](./docs/getting-started.md)** —
From here, the guide takes over: **[docs/dev/PROGRAMISTA.md](./docs/dev/PROGRAMISTA.md)** —
from an empty project to a working site.
---
@@ -104,7 +104,7 @@ npm version patch # 1.0.0 → 1.0.1
npm publish
```
Full checklist and troubleshooting: **[docs/publishing.md](./docs/publishing.md)**.
Full checklist and troubleshooting: **[docs/dev/PROGRAMISTA.md §8](./docs/dev/PROGRAMISTA.md)**.
---
@@ -112,8 +112,8 @@ Full checklist and troubleshooting: **[docs/publishing.md](./docs/publishing.md)
Everything lives in the **[docs/](./docs)** directory. To get started:
- **[getting-started.md](./docs/getting-started.md)** — project setup, step by step
- **[publishing.md](./docs/publishing.md)** — releasing new plugin versions
- **[AGENT.md](./docs/agent/AGENT.md)** — rules for AI agents (Polish)
- **[PROGRAMISTA.md](./docs/dev/PROGRAMISTA.md)** — setup, deployment, upgrades, releasing (Polish)
- **[README.md](./docs/README.md)** — index of the plugin's modules
---
@@ -127,5 +127,5 @@ Everything lives in the **[docs/](./docs)** directory. To get started:
| two versions of `lucide-react` | your project pins a different major than the plugin's `^0.400.0` — align them |
| `missing secret key … to secure Payload` | `PAYLOAD_SECRET` isn't set in the runtime environment (not a plugin issue) |
If you get stuck, see **[docs/publishing.md](./docs/publishing.md)** or message the
If you get stuck, see **[docs/dev/PROGRAMISTA.md](./docs/dev/PROGRAMISTA.md)** or message the
team that maintains the plugin.
-260
View File
@@ -1,260 +0,0 @@
# Zasady i Standardy Projektowe — Payload CMS 3 + Next 16 + @intecion/ipal-kit
Niniejszy dokument stanowi bezwzględnie obowiązujące reguły pracy dla agenta (Antigravity) w niniejszym projekcie. Został sporządzony na podstawie dokumentacji w `/docs`. Każda zasada musi być ściśle przestrzegana, bez wyjątków i bez stosowania obejść/prowizorek.
---
## 1. ZASADA NADRZĘDNA: ipal-kit JEST OBOWIĄZKOWY
1. **Obowiązkowe użycie pluginu:**
- Każda funkcja dostarczana przez `@intecion/ipal-kit` (i18n, SEO, formularze, consent, email, slug, bezpieczeństwo, strony systemowe, storage R2, breadcrumbs, JSON-LD) **MUSI** być realizowana przez plugin.
- **NIGDY** nie twórz własnego kodu w projekcie dublującego możliwości pluginu.
2. **Sprawdzaj przed pisaniem:**
- Zanim napiszesz jakąkolwiek funkcję, helper czy komponent — sprawdź dokumentację w `node_modules/@intecion/ipal-kit/docs/` oraz definicje typów `.d.ts`. Jeśli funkcja istnieje w pluginie, **musisz** jej użyć.
3. **Gdy w pluginie czegoś brakuje:**
- **NIE** obchodź braku prowizorką ani własnym kodem w projekcie (to tworzy dług technologiczny i rozbieżności).
- **Zgłoś brak funkcji do rozbudowy pluginu**, zamiast łatać to lokalnie.
- Logika uniwersalna (przydatna w innych projektach) trafia do pluginu. W projekcie znajduje się **wyłącznie** specyfika danego klienta (jego bloki, wygląd, struktura danych).
4. **Gdy coś w pluginie nie działa:**
- **Zgłoś problem i błąd**, zamiast tworzyć ciche obejścia, prowizoryczne hooki czy hardkodowane patche.
---
## 2. KROK 0: INSTALACJA I DOSTĘP DO DOKUMENTACJI PLUGINU
1. **Utwórz `.npmrc` w katalogu projektu:**
```ini
legacy-peer-deps=true
@intecion:registry=https://git.intecion.net/api/packages/IntecionSoftware/npm/
```
*(Scoped override: tylko `@intecion/*` z Gitea, rejestr publiczny bez tokena).*
2. **Instalacja pluginu:**
```bash
pnpm add @intecion/ipal-kit
```
*(NIGDY nie instaluj z gita `git+https://...` — psuje React Client Manifest w Next).*
3. **Lokalizacja dokumentacji źródłowej:**
```bash
ls node_modules/@intecion/ipal-kit/docs/
```
Zawsze korzystaj z plików w `docs/` pluginu (`getting-started.md`, `seo.md`, `forms.md`, `email.md`, `storage.md`, `i18n.md`, `blocks.md`, `turnstile.md` itd.).
---
## 3. ABSOLUTNY ZAKAZ HARDKODOWANIA
### A. Treść i teksty:
- **ZAKAZ:** Tekst widoczny dla użytkownika wpisany w JSX, etykiety i komunikaty w kodzie, instrukcje `if (locale === 'pl')`, tablice z tekstami w kodzie.
- **WYMAGANE:** Każdy tekst pochodzi z pola `localized: true`, pobierany z panelu CMS.
- **Częsty błąd (ukryty hardkod w fallbacku):** `siteName || 'Nazwa Klienta'` lub `catch { return { name: 'Firma...' } }` to **niedopuszczalny hardkod**! Gdy brak danych z panelu/env: **pomiń pole** (np. `...(val ? { name: val } : {})`), nie wstawiaj danych klienta w fallbacku `||` ani w bloku `catch`.
### B. Obrazy i multimedia:
- **ZAKAZ:** `import logo from '@/assets/...'`, ścieżki `src="/images/..."`.
- **WYMAGANE:** Pole `type: 'upload', relationTo: 'media'`, renderowane z `media.url`. Do kolekcji `Media` obowiązkowo wepnij `normalizeFilenameHook`.
- **Preconnect:** Użyj `<MediaPreconnect />` z pluginu (czyta `R2_PUBLIC_URL` z env), nigdy sztywnego tagu `<link>` z domeną.
- **Favicon:** Użyj `buildIconsMetadata(settings.favicon)` z panelu (format PNG, nie ręczny SVG).
### C. Linki i routing:
- **ZAKAZ:** `href="/pl/kontakt"`, menu jako statyczna tablica w kodzie, oraz **sztywna mapa zlokalizowanych ścieżek** (`const localizedRoutes = {...}` — kardynalny antywzorzec).
- **WYMAGANE:** `getLocalizedSlugs` / `switchLocalePath` z bazy danych, `getSystemPagePath`, relacje `relationship -> pages` w panelu CMS.
### D. Konfiguracja i dane firmy:
- **ZAKAZ:** `locale as 'pl' | 'en'`, zaszyty slug kolekcji, dane firmy, NIP, adres, telefon w kodzie.
- **WYMAGANE:** Jedno źródło prawdy `i18n.config.ts`, `locale as never`, dane firmy z globala (np. `siteSettings` / `CompanyInfo`), infrastruktura wyłącznie w `.env`.
### E. Renderer bloków, kolekcje, formularze (częste błędy):
- **Renderer rich text:** ZAWSZE `RenderRichText` z pluginu (`@intecion/ipal-kit/rsc`, wrapper nad oficjalnym konwerterem Lexical). NIGDY własny parser Lexical (switch po node.type, flagi node.format, dangerouslySetInnerHTML, hardkod `.pl`). Styl przez `converters`. Patrz richtext.md.
- **Renderer bloków:** ZAWSZE `RenderBlocks` z pluginu + mapa `registry`. NIGDY własny `switch (block.blockType)` — to gadatliwe, bez enhanceProps, rośnie liniowo. Mapa deklaratywna, silnik z pluginu.
- **MINIMUM kolekcji, nie maksimum:** Domyślnie tylko rdzeń (pages, media, settings, navigation, footer + globale). Kolekcję treści (blog/produkty) TYLKO gdy klient JAWNIE wymaga. NIGDY nie twórz: `users` (WBUDOWANE w Payload — nie duplikuj!), `daneFirmy`/`settings` jako kolekcje (to GLOBALE), FAQ/hero/features jako kolekcje (to BLOKI). Test przed stworzeniem: lista rekordów + własny URL + jawna potrzeba + Payload nie ma wbudowanego. Patrz `kolekcje-katalog.md`.
- **Formularze z buildera:** ZAWSZE pola/etykiety/komunikaty z buildera w panelu (kolekcja Forms) + `submitForm`. NIGDY nie hardkoduj pól ani tekstów w JSX. Turnstile: `TurnstileProvider` (siteKey raz w layoutcie) + `useTurnstile()`.
- **Logika formularza z pluginu:** stan/walidacja/Turnstile/submit przez `useForm` (dowolne pola) lub `useContactForm` (preset) z `@intecion/ipal-kit/client` — hooki NIE renderują markupu, wygląd zostaje w projekcie. NIGDY nie kopiuj ręcznej hydrauliki (useState na pola, regex e-maila, obsługa tokenu, try/catch submitu) do projektu — to antywzorzec, który hook eliminuje. Walidacja przez `buildValidator` + reguły (`required`, `email`, `minLength`, `pattern`…). Patrz `forms.md`.
- **Wartości lokalizowane:** ZAWSZE `resolveLocalized(value, locale)` z pluginu. NIGDY własny `getSafeString`/`(v as any)[locale]` kopiowany do JSON-LD, rich text czy topiców formularza.
- **ZAKAZ:** `locale as 'pl' | 'en'`, zaszyty slug kolekcji, dane firmy, NIP, adres, telefon w kodzie.
- **WYMAGANE:** Jedno źródło prawdy `i18n.config.ts`, `locale as never`, dane firmy z globala (np. `siteSettings` / `CompanyInfo`), infrastruktura wyłącznie w `.env`.
---
## 4. ARCHITEKTURA I STRUKTURA PROJEKTU
### A. Next 16 + Payload 3:
- **NIGDY nie twórz `middleware.ts`.** W Next 16 stosuje się **WYŁĄCZNIE `proxy.ts`** (funkcja `proxy`). Jeśli plik `middleware.ts` istnieje — usuń go natychmiast.
- **Struktura katalogów:**
```
src/
app/
(frontend)/
styles.css # Tailwind + @source na plugin
[locale]/
layout.tsx # root layout bez sztywnego <head>
not-found.tsx # 404 (treść z panelu)
[[...slug]]/
page.tsx # render stron z bloków (podwójne nawiasy!)
(payload)/ # panel admina
manifest.ts # PWA z panelu — WYMAGANE export const dynamic = 'force-dynamic'
sitemap.ts # z lib/content + export const dynamic = 'force-dynamic'
robots.ts # z lib/content
instrumentation.ts # assertEnv(ipalEnvRules(...)) — walidacja ENV na starcie
blocks/
<NazwaBloku>/
config.ts # schemat pól bloku
Component.tsx # render komponentu
registry.ts # mapa blockType -> komponent
collections/
Pages.ts # layout typu blocks
Media.ts # upload + normalizeFilenameHook
globals/ # siteSettings, siteIntegrations, navigation, footer
lib/
content.ts # createContentHelpers — JEDNO źródło
payload.ts # helpery projektu (getSettings...)
i18n.config.ts # locale — jedno źródło
payload.config.ts
proxy.ts # routing locale (NIE middleware.ts)
```
### B. Przepływ danych i zależności:
- **Brak cykli importów:** Warstwa niższa (bloki) **NIE** może importować warstwy wyższej (`lib/*`). Dane zewnętrzne (np. klucze Turnstile) przekazuj przez `enhanceProps` w `page.tsx`.
- **Dostęp do Payloada:** Jedno źródło `getCachedPayload` w `lib/content.ts`.
- **Server Components (RSC) domyślnie:** Pobieranie danych po stronie serwera; `'use client'` stosuj wyłącznie dla komponentów z lokalnym stanem/interakcją. Chroń wrażliwe moduły przez `import 'server-only'`.
### C. Kluczowe wymagania SEO i Renderingu:
1. **Brak jawnego `<head>` w layoutcie:** Sztywny `<head>` wypycha metatagi Next.js do `<body>`. Pozwól Next.js zarządzać nagłówkiem. `<MediaPreconnect />` umieszczaj w `<body>` (React 19 automatycznie hoistuje tag link do head).
2. **Wymagane ISR:** `export const revalidate = 3600` w `page.tsx` stron (zapobiega race condition streamingu metadanych i zapewnia TTFB ~20ms).
3. **Wymagane `generateStaticParams`:** W `[[...slug]]/page.tsx` eksportuj `generateStaticParams` z `lib/content` (`export { generateStaticParams } from '@/lib/content'`). Gwarantuje synchroniczne generowanie metadanych w `<head>` dla robotów.
4. **`htmlLimitedBots`:** Skonfiguruj w `next.config.ts` zgodnie z `seo.md`.
5. **`export const dynamic = 'force-dynamic'` na route'ach odpytujących bazę:** `manifest.ts`, `llms.txt/route.ts`, `sitemap.xml/route.ts`. Bez tego Next próbuje prerenderować je podczas `docker build` (baza offline → crash). Handlery pluginu mają try/catch jako drugą warstwę, ale `dynamic` to eksport modułowy — MUSI być w pliku route'a, handler nie ustawi go za Ciebie.
6. **Walidacja ENV na starcie:** `instrumentation.ts` z `assertEnv(ipalEnvRules({ ... }))` — fail fast przy brakującej konfiguracji, zamiast kryptograficznego crashu w buildzie. Patrz `env.md`.
---
## 5. STANDARDY KODU I TYPOWANIA (POZIOM SENIOR)
1. **Zero `any` i zero `@ts-ignore`:**
- Zawsze typuj precyzyjnie. Jeśli kształt danych z zewnątrz jest nieznany, użyj `unknown` + zawężenie (type guard).
- Wyjątek: wąskie rzutowanie `as unknown as Record<string, unknown>` przy udokumentowanych rozbieżnościach generatora Payload (np. pole zlokalizowane przy `locale: 'all'`).
2. **Typy generowane:** Importuj typy z `@/payload-types` (`pnpm generate:types`), nie twórz ręcznych duplikatów interfejsów.
3. **Generyki przy wywołaniu:** Stosuj np. `getSiteSettings<SiteSetting>(payload)`, a nie rzutowanie `as SiteSetting` na wyniku.
4. **`satisfies` dla konfiguracji:** Używaj `as const satisfies I18nConfig`.
5. **Obsługa błędów:** Nigdy nie połykaj błędów (`catch {}`). Loguj konkretny komunikat i zwracaj kontrolowany błąd. Stosuj guard clauses (płaski kod).
6. **Transakcje i hooki:** W hookach Payload zawsze przekazuj `req` do kolejnych operacji bazodanowych. Chroń hooki przed nieskończonymi pętlami za pomocą flagi w `context` (np. `context.skip`). Przy `payload.find` pamiętaj o `overrideAccess: false`, jeśli operacja ma respektować uprawnienia usera.
---
## 6. NAZEWNICTWO I KONWENCJE
- **Foldery bloków i pliki kolekcji:** PascalCase (`blocks/HeroSection/`, `collections/Pages.ts`).
- **Pliki bloku:** `config.ts` + `Component.tsx` w jednym folderze.
- **Slugi kolekcji:** camelCase, liczba mnoga (`pages`, `blogPosts`, `products`).
- **Slugi bloków:** camelCase (`hero`, `textSection`). Klucz w `registry.ts` musi być identyczny ze slugiem bloku.
- **Wspólne nazwy pól (obowiązkowe w każdym projekcie):**
- Nagłówek: `heading`
- Podtytuł: `subheading`
- Treść: `body` (textarea) lub `content` (richText)
- Obraz: `image` (upload -> media)
- Przycisk CTA: `ctaLabel` (text, localized)
- Cel CTA: `ctaTarget` (relationship -> pages)
- Link zewn.: `url` (text)
- Zgoda prawna: `consent` (checkbox)
---
**Globale Company/Header/Footer → PROJEKT, nie plugin.** Model danych firmy różni się per kraj (NIP/PL, ABN/AU, EIN/US) i branżę. NIE szukaj buildCompanyGlobal w pluginie — zdefiniuj własny src/globals/Company.ts. Schema.org: klocki pluginu (buildOrganizationJsonLd...) + JsonLdGraph, zmapuj SWOJE dane na @type (LegalService/PL, HVACBusiness/AU). Patrz seo.md.
## 6b. WYMAGANIA PRAWNE (COMPLIANCE)
Każda strona (PL/EU) MUSI mieć: polityka prywatności, polityka cookies, baner
zgody cookies, zgoda RODO w formularzach. Plugin dostarcza MECHANIZM:
- **Strony polityk** → System Pages (role: privacyPolicy, cookiePolicy, termsOfService), linkowane przez `getSystemPagePath`.
- **Baner cookies** → CookieBanner + CookieButton + ConsentProvider (analytics/marketing gated — NIE ładują się przed zgodą).
- **Zgoda RODO** → checkbox `consent` w formularzu (enforcement server-side w submitForm).
- **Strony noindex** → polityki/regulamin zaznacz `noindex` w panelu SEO (kanibalizacja fraz).
- **Ochrona:** hook `buildPreventDeleteSystemPage` blokuje usunięcie strony systemowej.
Granica: MY dostarczamy mechanizm, TREŚĆ prawną (tekst polityk) tworzy klient/prawnik.
**Widget dostępności (a11y)** — OPCJONALNY, NIE dodawaj domyślnie. Wymagany tylko
dla podmiotów publicznych / części e-commerce (European Accessibility Act). Dla
zwykłych stron komercyjnych to opcja — dodawaj GDY klient wymaga (AccessibilityProvider
+ AccessibilityWidget + CSS projektu). Patrz `accessibility.md`.
Patrz `wymagania-prawne.md`.
## 6c. HOOKI PLUGINU (automatyzacja)
Wpinaj w kolekcje gdzie dotyczy (patrz `hooks.md`):
- **buildRevalidateHook** (afterChange/afterDelete) — ISR odświeżany po zapisie (redaktor od razu widzi zmianę). `revalidatePath` wstrzykiwany z projektu.
- **trackSlugHistoryHook** (beforeChange) — zmiana slug → zapis starego slug. Odczyt robi **resolveRedirect** (patrz niżej) — NIE pisz własnego lookupu.
- **resolveRedirect** (moduł content) — w catch-all, gdy `resolveRoute` nic nie znajdzie: czyta slugHistory i zwraca cel 301/308; projekt woła `permanentRedirect` (plugin nie importuje `next/navigation`). Domyka trackSlugHistoryHook.
- **buildCrossLocaleFieldSync** (afterChange) — kopiuje pola wspólne dla języków (obrazki) wewnątrz lokalizowanego `blocks` między locale. Lista języków z `config` (NIGDY hardkod `['pl','en',…]`). Zastępuje ręczny hook z zahardkodowaną listą.
- **buildNoindexField** (pole, nie hook) — sidebarowy checkbox `noindex` zgrany z `meta.noindex`, bez `any`. Zamiast ręcznego checkboxa + hooka glue.
- **setPublishedAtHook** — auto-data publikacji (blog).
- **normalizeFilenameHook** — czyste nazwy plików (Media, obowiązkowo).
- **buildPreventDeleteSystemPage** / **buildValidateUniqueRole** — ochrona stron systemowych.
## 6d. BEZPIECZEŃSTWO (nagłówki)
- **buildSecurityHeaders** w next.config — HSTS, COOP, nosniff, Referrer-Policy (z automatu, uniwersalne).
- **buildCsp** — generator CSP z twardymi regułami (base-uri, object-src, frame-ancestors). Flagi: turnstile, analytics, youtube, r2Url. Wdrażaj przez `report-only` → sprawdź konsolę → `enforce`.
- **2FA WYMUSZONE** — `pnpm add @clocklimited/payload-2fa@3.0.0-beta.7`, potem WSTRZYKNIJ: `import { payloadTotp } from '@clocklimited/payload-2fa'` + `ipalKit({ twoFactor: { issuer: 'Nazwa Firmy', plugin: payloadTotp } })`. Wstrzyknięcie obowiązkowe — bez niego plugin robi dynamiczny import, którego Next nie wbundluje → „Cannot find module" na froncie. (Ewentualnie zamiast wstrzyknięcia: `serverExternalPackages: ['@clocklimited/payload-2fa']` w next.config.) Wymuszone dla WSZYSTKICH (forceSetup), bez opcji per user. NIE `twoFactor: false` (chyba że klient wprost odmawia). Patrz security.md.
- **Ścieżka panelu** — `ipalKit({ adminRoute: '/its' })` ukrywa panel. WYMAGA przeniesienia folderu `app/(payload)/admin/` → `app/(payload)/its/`. To obscurity, nie security (2FA to prawdziwa ochrona).
- CSP zostaje w projekcie (domeny), ale skeleton z pluginu. NIE Trusted Types (psuje Turnstile/GA).
## 7. PODZIAŁ PRACY I RÓL
- **Antigravity (Agent):** Buduje architekturę, logikę, kolekcje, bloki, routing, edytowalność przez panel, integracje oraz dba o brak hardkodów.
- **Impeccable (osobne narzędzie):** Dopracowuje wygląd, system wizualny na bazie `PRODUCT.md` i `DESIGN.md`. Antigravity nie „dopieszcza" styli ad-hoc kosztem logiki i edytowalności.
- **Klient / Redaktor:** Samodzielnie zarządza każdą treścią z poziomu panelu CMS.
---
## 8. PROCEDURA RAPORTOWANIA DO PLUGINU
Jeśli w trakcie pracy:
1. Funkcja okaże się brakująca w `@intecion/ipal-kit`,
2. Wystąpi błąd wewnętrzny w bibliotece pluginu,
3. Pojawi się powtarzalna potrzeba biznesowa przydatna w wielu projektach,
**Należy natychmiast przygotować raport proponowanej zmiany/rozbudowy pluginu:**
- Dokładny opis problemu / brakującej funkcjonalności,
- Proponowany interfejs API / sygnatura funkcji lub konfiguracji,
- Uzasadnienie uniwersalności dla innych projektów.
**Nie wolno tworzyć cichej łaty w kodzie projektu.**
---
## 9. MAPA DOKUMENTACJI — gdzie szukać szczegółów
Ten plik to skondensowane reguły. Szczegóły w `node_modules/@intecion/ipal-kit/docs/`:
| Chcę... | Plik |
|---|---|
| Zbudować projekt od zera | `getting-started.md` |
| Strukturę, nazewnictwo, konwencje | `fundamenty-projektu.md` |
| Jakie kolekcje budować (minimum!) | `kolekcje-katalog.md` |
| SEO, metadane, sitemap, favicon, structured data, llms.txt | `seo.md` |
| Hooki (revalidate, slug history, cross-locale sync, ochrona) | `hooks.md` |
| Redirecty 301/308 (resolveRedirect) | `content.md` |
| Walidacja ENV na starcie (assertEnv) | `env.md` |
| Czytelność dla AI: Markdown per strona, llms-full, boty AI w robots | `content.md`, `seo.md` |
| Serwer MCP strony (Claude podłącza się do treści) | `mcp.md` |
| GTM + Meta Pixel — konfiguracja krok po kroku | `gtm-meta-pixel.md` |
| White-label panelu admina (logo/nazwa z SiteSettings) | `white-label.md` |
| Bezpieczeństwo, CSP, COOP | `security.md` |
| Formularze, Turnstile, submitForm, useForm/useContactForm | `forms.md`, `turnstile.md` |
| i18n, strona jednojęzyczna, ścieżki | `i18n.md` |
| Strony systemowe, routing | `pages.md` |
| Bloki, RenderBlocks | `blocks.md` |
| Media, R2, MediaPreconnect | `storage.md` |
| Email (SMTP/Graph) | `email.md` |
| Consent, cookies | `consent.md` |
| Deployment, ISR/SSG, Coolify | `deployment.md` |
| Wymagania prawne, compliance | `wymagania-prawne.md` |
| Filozofia CMS, edytowalność, Impeccable | `architektura-tresci.md` |
| Standardy kodu, antywzorce | `standardy-kodu.md` |
---
## 10. ZAPISZ REGUŁY PROJEKTU
Kluczowe ustalenia projektu (stack, decyzje, tryby stron) zapisz we własnym pliku
kontekstu (`agents.md` / `.agents/context/`), żeby nie gubić ich między sesjami.
Nie polegaj tylko na pamięci sesji.
+2
View File
@@ -3,7 +3,9 @@ export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmai
export { AccessibilityProvider, AccessibilityWidget, useAccessibility, } from '../modules/accessibility/client.js';
export type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js';
export { Analytics } from '../modules/analytics/client.js';
export type { AnalyticsProps } from '../modules/analytics/client.js';
export { pushDataLayer } from '../modules/analytics/client.js';
export { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok, } from '../modules/analytics/client.js';
/**
* Entry point: ipal-kit/client
*
+1
View File
@@ -4,6 +4,7 @@ export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmai
export { AccessibilityProvider, AccessibilityWidget, useAccessibility } from '../modules/accessibility/client.js';
export { Analytics } from '../modules/analytics/client.js';
export { pushDataLayer } from '../modules/analytics/client.js';
export { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from '../modules/analytics/client.js';
/**
* Entry point: ipal-kit/client
*
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["'use client'\nexport { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js'\nexport { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js'\nexport {\n AccessibilityProvider,\n AccessibilityWidget,\n useAccessibility,\n} from '../modules/accessibility/client.js'\nexport type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js'\nexport { Analytics } from '../modules/analytics/client.js'\nexport { pushDataLayer } from '../modules/analytics/client.js'\n\n/**\n * Entry point: ipal-kit/client\n *\n * Client-side ('use client') exports — React hooks, providers, and UI\n * components. Kept separate from the main entry so server bundles don't pull in\n * client-only code.\n */\nexport {\n ConsentProvider,\n ConsentScript,\n CookieBanner,\n CookieButton,\n useConsent,\n useConsentContext,\n} from '../modules/consent/client.js'\nexport type { CookieBannerClassNames } from '../modules/consent/client.js'\nexport { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js'\nexport type { FormAnalyticsConfig } from '../modules/forms/formAnalytics.js'\nexport { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js'\nexport { useContactForm } from '../modules/forms/useContactForm.js'\nexport type {\n ContactFormErrors,\n ContactFormValues,\n SubmitAction,\n} from '../modules/forms/useContactForm.js'\nexport { useForm } from '../modules/forms/useForm.js'\nexport type { FormErrors, FormSubmitAction, Validator } from '../modules/forms/useForm.js'\nexport {\n buildValidator,\n checked,\n custom,\n email,\n isEmail,\n maxLength,\n minLength,\n pattern,\n required,\n} from '../modules/forms/validators.js'\nexport type { Rule } from '../modules/forms/validators.js'\n// Pure i18n path helpers — no server/RSC deps, safe to import in client\n// components (e.g. a LanguageSwitcher that computes locale URLs on the client).\nexport {\n buildLocalizedPath,\n getLocaleCodes,\n getLocalizedSlugs,\n switchLocalePath,\n} from '../modules/i18n/index.js'\nexport type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js'\nexport {\n AlternateLinksProvider,\n AlternateLinksUpdater,\n LanguageSwitcher,\n useAlternateLinks,\n useSetAlternateLinks,\n} from '../modules/i18n/index.js'\nexport type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js'\nexport { Turnstile } from '../modules/turnstile/client.js'\nexport { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js'\nexport type { TurnstileProps } from '../modules/turnstile/client.js'\n"],"names":["MaskedField","TestEmailButton","AccessibilityProvider","AccessibilityWidget","useAccessibility","Analytics","pushDataLayer","ConsentProvider","ConsentScript","CookieBanner","CookieButton","useConsent","useConsentContext","formAnalyticsOnSuccess","HONEYPOT_FIELD","honeypotInputProps","isHoneypotTripped","useContactForm","useForm","buildValidator","checked","custom","email","isEmail","maxLength","minLength","pattern","required","buildLocalizedPath","getLocaleCodes","getLocalizedSlugs","switchLocalePath","AlternateLinksProvider","AlternateLinksUpdater","LanguageSwitcher","useAlternateLinks","useSetAlternateLinks","Turnstile","TurnstileProvider","useTurnstile"],"mappings":"AAAA;AACA,SAASA,WAAW,QAAQ,wDAAuD;AACnF,SAASC,eAAe,QAAQ,4DAA2D;AAC3F,SACEC,qBAAqB,EACrBC,mBAAmB,EACnBC,gBAAgB,QACX,qCAAoC;AAE3C,SAASC,SAAS,QAAQ,iCAAgC;AAC1D,SAASC,aAAa,QAAQ,iCAAgC;AAE9D;;;;;;CAMC,GACD,SACEC,eAAe,EACfC,aAAa,EACbC,YAAY,EACZC,YAAY,EACZC,UAAU,EACVC,iBAAiB,QACZ,+BAA8B;AAErC,SAASC,sBAAsB,QAAQ,oCAAmC;AAE1E,SAASC,cAAc,EAAEC,kBAAkB,EAAEC,iBAAiB,QAAQ,+BAA8B;AACpG,SAASC,cAAc,QAAQ,qCAAoC;AAMnE,SAASC,OAAO,QAAQ,8BAA6B;AAErD,SACEC,cAAc,EACdC,OAAO,EACPC,MAAM,EACNC,KAAK,EACLC,OAAO,EACPC,SAAS,EACTC,SAAS,EACTC,OAAO,EACPC,QAAQ,QACH,iCAAgC;AAEvC,wEAAwE;AACxE,gFAAgF;AAChF,SACEC,kBAAkB,EAClBC,cAAc,EACdC,iBAAiB,EACjBC,gBAAgB,QACX,2BAA0B;AAEjC,SACEC,sBAAsB,EACtBC,qBAAqB,EACrBC,gBAAgB,EAChBC,iBAAiB,EACjBC,oBAAoB,QACf,2BAA0B;AAEjC,SAASC,SAAS,QAAQ,iCAAgC;AAC1D,SAASC,iBAAiB,EAAEC,YAAY,QAAQ,iCAAgC"}
{"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["'use client'\nexport { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js'\nexport { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js'\nexport {\n AccessibilityProvider,\n AccessibilityWidget,\n useAccessibility,\n} from '../modules/accessibility/client.js'\nexport type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js'\nexport { Analytics } from '../modules/analytics/client.js'\nexport type { AnalyticsProps } from '../modules/analytics/client.js'\n\nexport { pushDataLayer } from '../modules/analytics/client.js'\nexport {\n loadClarity,\n loadLinkedIn,\n loadMetaPixel,\n loadTikTok,\n} from '../modules/analytics/client.js'\n/**\n * Entry point: ipal-kit/client\n *\n * Client-side ('use client') exports — React hooks, providers, and UI\n * components. Kept separate from the main entry so server bundles don't pull in\n * client-only code.\n */\nexport {\n ConsentProvider,\n ConsentScript,\n CookieBanner,\n CookieButton,\n useConsent,\n useConsentContext,\n} from '../modules/consent/client.js'\nexport type { CookieBannerClassNames } from '../modules/consent/client.js'\nexport { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js'\nexport type { FormAnalyticsConfig } from '../modules/forms/formAnalytics.js'\nexport { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js'\nexport { useContactForm } from '../modules/forms/useContactForm.js'\nexport type {\n ContactFormErrors,\n ContactFormValues,\n SubmitAction,\n} from '../modules/forms/useContactForm.js'\nexport { useForm } from '../modules/forms/useForm.js'\nexport type { FormErrors, FormSubmitAction, Validator } from '../modules/forms/useForm.js'\nexport {\n buildValidator,\n checked,\n custom,\n email,\n isEmail,\n maxLength,\n minLength,\n pattern,\n required,\n} from '../modules/forms/validators.js'\nexport type { Rule } from '../modules/forms/validators.js'\n// Pure i18n path helpers — no server/RSC deps, safe to import in client\n// components (e.g. a LanguageSwitcher that computes locale URLs on the client).\nexport {\n buildLocalizedPath,\n getLocaleCodes,\n getLocalizedSlugs,\n switchLocalePath,\n} from '../modules/i18n/index.js'\nexport type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js'\nexport {\n AlternateLinksProvider,\n AlternateLinksUpdater,\n LanguageSwitcher,\n useAlternateLinks,\n useSetAlternateLinks,\n} from '../modules/i18n/index.js'\nexport type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js'\nexport { Turnstile } from '../modules/turnstile/client.js'\nexport { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js'\nexport type { TurnstileProps } from '../modules/turnstile/client.js'\n"],"names":["MaskedField","TestEmailButton","AccessibilityProvider","AccessibilityWidget","useAccessibility","Analytics","pushDataLayer","loadClarity","loadLinkedIn","loadMetaPixel","loadTikTok","ConsentProvider","ConsentScript","CookieBanner","CookieButton","useConsent","useConsentContext","formAnalyticsOnSuccess","HONEYPOT_FIELD","honeypotInputProps","isHoneypotTripped","useContactForm","useForm","buildValidator","checked","custom","email","isEmail","maxLength","minLength","pattern","required","buildLocalizedPath","getLocaleCodes","getLocalizedSlugs","switchLocalePath","AlternateLinksProvider","AlternateLinksUpdater","LanguageSwitcher","useAlternateLinks","useSetAlternateLinks","Turnstile","TurnstileProvider","useTurnstile"],"mappings":"AAAA;AACA,SAASA,WAAW,QAAQ,wDAAuD;AACnF,SAASC,eAAe,QAAQ,4DAA2D;AAC3F,SACEC,qBAAqB,EACrBC,mBAAmB,EACnBC,gBAAgB,QACX,qCAAoC;AAE3C,SAASC,SAAS,QAAQ,iCAAgC;AAG1D,SAASC,aAAa,QAAQ,iCAAgC;AAC9D,SACEC,WAAW,EACXC,YAAY,EACZC,aAAa,EACbC,UAAU,QACL,iCAAgC;AACvC;;;;;;CAMC,GACD,SACEC,eAAe,EACfC,aAAa,EACbC,YAAY,EACZC,YAAY,EACZC,UAAU,EACVC,iBAAiB,QACZ,+BAA8B;AAErC,SAASC,sBAAsB,QAAQ,oCAAmC;AAE1E,SAASC,cAAc,EAAEC,kBAAkB,EAAEC,iBAAiB,QAAQ,+BAA8B;AACpG,SAASC,cAAc,QAAQ,qCAAoC;AAMnE,SAASC,OAAO,QAAQ,8BAA6B;AAErD,SACEC,cAAc,EACdC,OAAO,EACPC,MAAM,EACNC,KAAK,EACLC,OAAO,EACPC,SAAS,EACTC,SAAS,EACTC,OAAO,EACPC,QAAQ,QACH,iCAAgC;AAEvC,wEAAwE;AACxE,gFAAgF;AAChF,SACEC,kBAAkB,EAClBC,cAAc,EACdC,iBAAiB,EACjBC,gBAAgB,QACX,2BAA0B;AAEjC,SACEC,sBAAsB,EACtBC,qBAAqB,EACrBC,gBAAgB,EAChBC,iBAAiB,EACjBC,oBAAoB,QACf,2BAA0B;AAEjC,SAASC,SAAS,QAAQ,iCAAgC;AAC1D,SAASC,iBAAiB,EAAEC,YAAY,QAAQ,iCAAgC"}
+3 -2
View File
@@ -1,7 +1,8 @@
import type { Field } from 'payload';
/**
* Fields for the CookieSettings global — GDPR consent banner copy, editable
* per locale. The privacy-policy link is NOT stored here: it comes from the
* pages module (system page role 'privacyPolicy'), keeping one source of truth.
* per locale. The privacy-policy link TARGET is NOT stored here: it comes from
* the pages module (system page role 'privacyPolicy'), keeping one source of
* truth. Only the link's visible text lives here (privacyLinkLabel).
*/
export declare const cookieSettingsFields: Field[];
+12 -3
View File
@@ -1,8 +1,9 @@
import { CONSENT_CATEGORIES } from '../../modules/consent/index.js';
import { CONSENT_CATEGORIES } from '../../modules/consent/categories.js';
/**
* Fields for the CookieSettings global — GDPR consent banner copy, editable
* per locale. The privacy-policy link is NOT stored here: it comes from the
* pages module (system page role 'privacyPolicy'), keeping one source of truth.
* per locale. The privacy-policy link TARGET is NOT stored here: it comes from
* the pages module (system page role 'privacyPolicy'), keeping one source of
* truth. Only the link's visible text lives here (privacyLinkLabel).
*/ export const cookieSettingsFields = [
{
name: 'message',
@@ -20,6 +21,14 @@ import { CONSENT_CATEGORIES } from '../../modules/consent/index.js';
},
localized: true
},
{
name: 'privacyLinkLabel',
type: 'text',
admin: {
description: 'Text of the privacy-policy link in the banner, e.g. "Privacy policy". The link target is the page assigned as Privacy Policy in Site Settings → System Pages. Empty → the page title is used.'
},
localized: true
},
{
name: 'buttons',
type: 'group',
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/globals/CookieSettings/fields.ts"],"sourcesContent":["import type { Field } from 'payload'\n\nimport { CONSENT_CATEGORIES } from '../../modules/consent/index.js'\n\n/**\n * Fields for the CookieSettings global — GDPR consent banner copy, editable\n * per locale. The privacy-policy link is NOT stored here: it comes from the\n * pages module (system page role 'privacyPolicy'), keeping one source of truth.\n */\nexport const cookieSettingsFields: Field[] = [\n {\n name: 'message',\n type: 'textarea',\n admin: {\n description: 'Main consent message shown in the banner.',\n },\n localized: true,\n },\n {\n name: 'settingsTitle',\n type: 'text',\n admin: {\n description: 'Heading for the detailed settings panel.',\n },\n localized: true,\n },\n {\n name: 'buttons',\n type: 'group',\n admin: {\n description: 'Button labels.',\n },\n fields: [\n { name: 'acceptAll', type: 'text', localized: true },\n { name: 'reject', type: 'text', localized: true },\n { name: 'settings', type: 'text', localized: true },\n { name: 'save', type: 'text', localized: true },\n { name: 'back', type: 'text', localized: true },\n ],\n },\n {\n name: 'categories',\n type: 'array',\n admin: {\n description: 'Per-category titles and descriptions.',\n },\n fields: [\n {\n name: 'key',\n type: 'select',\n options: CONSENT_CATEGORIES.map((c) => ({ label: c, value: c })),\n required: true,\n },\n { name: 'title', type: 'text', localized: true },\n { name: 'description', type: 'textarea', localized: true },\n ],\n },\n]\n"],"names":["CONSENT_CATEGORIES","cookieSettingsFields","name","type","admin","description","localized","fields","options","map","c","label","value","required"],"mappings":"AAEA,SAASA,kBAAkB,QAAQ,iCAAgC;AAEnE;;;;CAIC,GACD,OAAO,MAAMC,uBAAgC;IAC3C;QACEC,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;QACAC,WAAW;IACb;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;QACAC,WAAW;IACb;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;QACAE,QAAQ;YACN;gBAAEL,MAAM;gBAAaC,MAAM;gBAAQG,WAAW;YAAK;YACnD;gBAAEJ,MAAM;gBAAUC,MAAM;gBAAQG,WAAW;YAAK;YAChD;gBAAEJ,MAAM;gBAAYC,MAAM;gBAAQG,WAAW;YAAK;YAClD;gBAAEJ,MAAM;gBAAQC,MAAM;gBAAQG,WAAW;YAAK;YAC9C;gBAAEJ,MAAM;gBAAQC,MAAM;gBAAQG,WAAW;YAAK;SAC/C;IACH;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;QACAE,QAAQ;YACN;gBACEL,MAAM;gBACNC,MAAM;gBACNK,SAASR,mBAAmBS,GAAG,CAAC,CAACC,IAAO,CAAA;wBAAEC,OAAOD;wBAAGE,OAAOF;oBAAE,CAAA;gBAC7DG,UAAU;YACZ;YACA;gBAAEX,MAAM;gBAASC,MAAM;gBAAQG,WAAW;YAAK;YAC/C;gBAAEJ,MAAM;gBAAeC,MAAM;gBAAYG,WAAW;YAAK;SAC1D;IACH;CACD,CAAA"}
{"version":3,"sources":["../../../src/globals/CookieSettings/fields.ts"],"sourcesContent":["import type { Field } from 'payload'\n\nimport { CONSENT_CATEGORIES } from '../../modules/consent/categories.js'\n\n/**\n * Fields for the CookieSettings global — GDPR consent banner copy, editable\n * per locale. The privacy-policy link TARGET is NOT stored here: it comes from\n * the pages module (system page role 'privacyPolicy'), keeping one source of\n * truth. Only the link's visible text lives here (privacyLinkLabel).\n */\nexport const cookieSettingsFields: Field[] = [\n {\n name: 'message',\n type: 'textarea',\n admin: {\n description: 'Main consent message shown in the banner.',\n },\n localized: true,\n },\n {\n name: 'settingsTitle',\n type: 'text',\n admin: {\n description: 'Heading for the detailed settings panel.',\n },\n localized: true,\n },\n {\n name: 'privacyLinkLabel',\n type: 'text',\n admin: {\n description:\n 'Text of the privacy-policy link in the banner, e.g. \"Privacy policy\". The link target is the page assigned as Privacy Policy in Site Settings → System Pages. Empty → the page title is used.',\n },\n localized: true,\n },\n {\n name: 'buttons',\n type: 'group',\n admin: {\n description: 'Button labels.',\n },\n fields: [\n { name: 'acceptAll', type: 'text', localized: true },\n { name: 'reject', type: 'text', localized: true },\n { name: 'settings', type: 'text', localized: true },\n { name: 'save', type: 'text', localized: true },\n { name: 'back', type: 'text', localized: true },\n ],\n },\n {\n name: 'categories',\n type: 'array',\n admin: {\n description: 'Per-category titles and descriptions.',\n },\n fields: [\n {\n name: 'key',\n type: 'select',\n options: CONSENT_CATEGORIES.map((c) => ({ label: c, value: c })),\n required: true,\n },\n { name: 'title', type: 'text', localized: true },\n { name: 'description', type: 'textarea', localized: true },\n ],\n },\n]\n"],"names":["CONSENT_CATEGORIES","cookieSettingsFields","name","type","admin","description","localized","fields","options","map","c","label","value","required"],"mappings":"AAEA,SAASA,kBAAkB,QAAQ,sCAAqC;AAExE;;;;;CAKC,GACD,OAAO,MAAMC,uBAAgC;IAC3C;QACEC,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;QACAC,WAAW;IACb;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;QACAC,WAAW;IACb;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aACE;QACJ;QACAC,WAAW;IACb;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;QACAE,QAAQ;YACN;gBAAEL,MAAM;gBAAaC,MAAM;gBAAQG,WAAW;YAAK;YACnD;gBAAEJ,MAAM;gBAAUC,MAAM;gBAAQG,WAAW;YAAK;YAChD;gBAAEJ,MAAM;gBAAYC,MAAM;gBAAQG,WAAW;YAAK;YAClD;gBAAEJ,MAAM;gBAAQC,MAAM;gBAAQG,WAAW;YAAK;YAC9C;gBAAEJ,MAAM;gBAAQC,MAAM;gBAAQG,WAAW;YAAK;SAC/C;IACH;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;QACAE,QAAQ;YACN;gBACEL,MAAM;gBACNC,MAAM;gBACNK,SAASR,mBAAmBS,GAAG,CAAC,CAACC,IAAO,CAAA;wBAAEC,OAAOD;wBAAGE,OAAOF;oBAAE,CAAA;gBAC7DG,UAAU;YACZ;YACA;gBAAEX,MAAM;gBAASC,MAAM;gBAAQG,WAAW;YAAK;YAC/C;gBAAEJ,MAAM;gBAAeC,MAAM;gBAAYG,WAAW;YAAK;SAC1D;IACH;CACD,CAAA"}
+3 -2
View File
@@ -1,6 +1,7 @@
import type { Field } from 'payload';
/**
* Analytics configuration — GA4 measurement ID and GTM container ID.
* IDs are public (exposed client-side), so no read restriction needed.
* 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
* after the matching consent category is granted (see modules/analytics).
*/
export declare const analyticsFields: Field[];
+37 -4
View File
@@ -1,12 +1,13 @@
/**
* Analytics configuration — GA4 measurement ID and GTM container ID.
* IDs are public (exposed client-side), so no read restriction needed.
* 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
* after the matching consent category is granted (see modules/analytics).
*/ export const analyticsFields = [
{
name: 'ga4MeasurementId',
type: 'text',
admin: {
description: 'Google Analytics 4 Measurement ID.',
description: 'Google Analytics 4 Measurement ID. (Google — Consent Mode)',
placeholder: 'G-XXXXXXXXXX'
}
},
@@ -14,9 +15,41 @@
name: 'gtmContainerId',
type: 'text',
admin: {
description: 'Google Tag Manager container ID.',
description: 'Google Tag Manager container ID. (Google — Consent Mode)',
placeholder: 'GTM-XXXXXXX'
}
},
{
name: 'metaPixelId',
type: 'text',
admin: {
description: 'Meta (Facebook) Pixel ID. Loads only after MARKETING consent.',
placeholder: '1234567890123456'
}
},
{
name: 'clarityProjectId',
type: 'text',
admin: {
description: 'Microsoft Clarity project ID (heatmaps). Loads only after ANALYTICS consent.',
placeholder: 'abcdefghij'
}
},
{
name: 'linkedInPartnerId',
type: 'text',
admin: {
description: 'LinkedIn Insight Tag partner ID. Loads only after MARKETING consent.',
placeholder: '1234567'
}
},
{
name: 'tiktokPixelId',
type: 'text',
admin: {
description: 'TikTok Pixel ID. Loads only after MARKETING consent.',
placeholder: 'CXXXXXXXXXXXXXXXXXXX'
}
}
];
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../../src/globals/SiteIntegrations/fields/analytics.ts"],"sourcesContent":["import type { Field } from 'payload'\n\n/**\n * Analytics configuration — GA4 measurement ID and GTM container ID.\n * IDs are public (exposed client-side), so no read restriction needed.\n */\nexport const analyticsFields: Field[] = [\n {\n name: 'ga4MeasurementId',\n type: 'text',\n admin: {\n description: 'Google Analytics 4 Measurement ID.',\n placeholder: 'G-XXXXXXXXXX',\n },\n },\n {\n name: 'gtmContainerId',\n type: 'text',\n admin: {\n description: 'Google Tag Manager container ID.',\n placeholder: 'GTM-XXXXXXX',\n },\n },\n]\n"],"names":["analyticsFields","name","type","admin","description","placeholder"],"mappings":"AAEA;;;CAGC,GACD,OAAO,MAAMA,kBAA2B;IACtC;QACEC,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACbC,aAAa;QACf;IACF;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACbC,aAAa;QACf;IACF;CACD,CAAA"}
{"version":3,"sources":["../../../../src/globals/SiteIntegrations/fields/analytics.ts"],"sourcesContent":["import type { Field } from 'payload'\n\n/**\n * Analytics / marketing tag IDs. All are PUBLIC (exposed client-side), so no\n * read restriction. Google tags (GA4/GTM) use Consent Mode; the rest load only\n * after the matching consent category is granted (see modules/analytics).\n */\nexport const analyticsFields: Field[] = [\n {\n name: 'ga4MeasurementId',\n type: 'text',\n admin: {\n description: 'Google Analytics 4 Measurement ID. (Google — Consent Mode)',\n placeholder: 'G-XXXXXXXXXX',\n },\n },\n {\n name: 'gtmContainerId',\n type: 'text',\n admin: {\n description: 'Google Tag Manager container ID. (Google — Consent Mode)',\n placeholder: 'GTM-XXXXXXX',\n },\n },\n {\n name: 'metaPixelId',\n type: 'text',\n admin: {\n description: 'Meta (Facebook) Pixel ID. Loads only after MARKETING consent.',\n placeholder: '1234567890123456',\n },\n },\n {\n name: 'clarityProjectId',\n type: 'text',\n admin: {\n description: 'Microsoft Clarity project ID (heatmaps). Loads only after ANALYTICS consent.',\n placeholder: 'abcdefghij',\n },\n },\n {\n name: 'linkedInPartnerId',\n type: 'text',\n admin: {\n description: 'LinkedIn Insight Tag partner ID. Loads only after MARKETING consent.',\n placeholder: '1234567',\n },\n },\n {\n name: 'tiktokPixelId',\n type: 'text',\n admin: {\n description: 'TikTok Pixel ID. Loads only after MARKETING consent.',\n placeholder: 'CXXXXXXXXXXXXXXXXXXX',\n },\n },\n]\n"],"names":["analyticsFields","name","type","admin","description","placeholder"],"mappings":"AAEA;;;;CAIC,GACD,OAAO,MAAMA,kBAA2B;IACtC;QACEC,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACbC,aAAa;QACf;IACF;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACbC,aAAa;QACf;IACF;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACbC,aAAa;QACf;IACF;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACbC,aAAa;QACf;IACF;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACbC,aAAa;QACf;IACF;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACbC,aAAa;QACf;IACF;CACD,CAAA"}
+1 -1
View File
@@ -7,7 +7,7 @@ export { getAnalyticsConfig } from './modules/analytics/index.js';
export { ACCEPT_ALL_CONSENT, CONSENT_CATEGORIES, CONSENT_COOKIE, CONSENT_MAX_AGE, CONSENT_VERSION, DEFAULT_CONSENT, getConsentTexts, parseConsent, REJECT_ALL_CONSENT, serializeConsent, setDefaultConsent, updateConsent, } from './modules/consent/index.js';
export type { ConsentCategory, ConsentState, ConsentTexts } from './modules/consent/index.js';
export type { ContentCollectionOption, ContentOption, ResolvedRoute, } from './modules/content/index.js';
export { archiveFieldName, blocksToMarkdown, buildArchivePath, buildEntryPath, createMarkdownRenderer, createSearchRoute, getArchiveEntries, MARKDOWN_PREFIX, markdownHref, markdownResponse, parsePageParam, prefersMarkdown, resolveRedirect, resolveRoute, searchContent, } from './modules/content/index.js';
export { archiveFieldName, blocksToMarkdown, buildArchivePath, buildEntryPath, createMarkdownRenderer, createSearchRoute, getArchiveEntries, MARKDOWN_PREFIX, markdownHref, markdownResponse, parsePageParam, prefersMarkdown, resolveNotFoundPage, resolveRedirect, resolveRoute, searchContent, } from './modules/content/index.js';
export type { ArchiveEntries } from './modules/content/index.js';
export type { SearchResult } from './modules/content/index.js';
export { graphAdapter } from './modules/email/graphAdapter.js';
+1 -1
View File
@@ -2,7 +2,7 @@ export { adminOnly, adminOnlyField, adminOrEditor, adminOrEditorField, adminOrSe
export { A11Y_COOKIE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y } from './modules/accessibility/index.js';
export { getAnalyticsConfig } from './modules/analytics/index.js';
export { ACCEPT_ALL_CONSENT, CONSENT_CATEGORIES, CONSENT_COOKIE, CONSENT_MAX_AGE, CONSENT_VERSION, DEFAULT_CONSENT, getConsentTexts, parseConsent, REJECT_ALL_CONSENT, serializeConsent, setDefaultConsent, updateConsent } from './modules/consent/index.js';
export { archiveFieldName, blocksToMarkdown, buildArchivePath, buildEntryPath, createMarkdownRenderer, createSearchRoute, getArchiveEntries, MARKDOWN_PREFIX, markdownHref, markdownResponse, parsePageParam, prefersMarkdown, resolveRedirect, resolveRoute, searchContent } from './modules/content/index.js';
export { archiveFieldName, blocksToMarkdown, buildArchivePath, buildEntryPath, createMarkdownRenderer, createSearchRoute, getArchiveEntries, MARKDOWN_PREFIX, markdownHref, markdownResponse, parsePageParam, prefersMarkdown, resolveNotFoundPage, resolveRedirect, resolveRoute, searchContent } from './modules/content/index.js';
export { graphAdapter } from './modules/email/graphAdapter.js';
export { mailAdapter } from './modules/email/mailAdapter.js';
// Imported straight from the file, NOT from ./modules/email/index.js — that
+1 -1
View File
File diff suppressed because one or more lines are too long
+32 -9
View File
@@ -4,16 +4,39 @@ declare global {
dataLayer?: unknown[];
}
}
export type AnalyticsProps = {
/**
* Core Web Vitals mode: hold back every tag's NETWORK load until the first
* user interaction (scroll, pointer, touch, key) or `deferTimeoutMs` after the
* window `load` event — whichever comes first. Keeps ~100+ KiB of third-party
* JS out of the FCP/LCP window.
*
* Consent is unaffected: the Consent Mode default is still pushed immediately
* (a synchronous dataLayer push, no network), and non-Google pixels still
* require their consent category. Defer changes WHEN a tag loads, never WHETHER.
*
* Trade-off: visitors who leave before interacting and before the timeout are
* not counted (slightly fewer sessions in GA). Default false.
*/
defer?: boolean;
/** Fallback delay after window `load`, in ms. Default 3500. */
deferTimeoutMs?: number;
} & AnalyticsConfig;
/**
* Loads Google Analytics — GTM if a container ID is set, otherwise GA4 gtag.
* Loads every configured analytics / marketing tag, each respecting consent:
*
* Consent Mode is initialised to the visitor's stored consent BEFORE the tag
* loads (via setDefaultConsent from the consent module), so tags respect the
* choice from the first hit; useConsent sends an update the moment the visitor
* decides. IDs are public and come from SiteIntegrations, passed in as props
* (the client project reads them server-side).
* - **Google (GA4 / GTM)** — Consent Mode: the visitor's stored choice is set as
* the default BEFORE the tag loads (always immediately, even with `defer`),
* and useConsent pushes an update the moment they decide. GTM wins if both
* IDs are set.
* - **Non-Google (Meta Pixel, Clarity, LinkedIn, TikTok)** — no Consent Mode, so
* each loads ONLY after its category is granted (marketing for
* Pixel/LinkedIn/TikTok, analytics for Clarity). Reacts live to the banner.
* - **`defer`** (opt-in) — additionally waits for first interaction / idle
* after load, for better LCP/INP. See AnalyticsProps.defer.
*
* Renders nothing — it only injects the scripts. Mount once, high in the tree
* (e.g. root layout), inside ConsentProvider.
* All IDs are public and come from SiteIntegrations (getAnalyticsConfig), passed
* in as props. Renders nothing. Mount once, high in the tree, INSIDE
* <ConsentProvider> (required — it reads live consent state).
*/
export declare function Analytics({ ga4MeasurementId, gtmContainerId }: AnalyticsConfig): null;
export declare function Analytics(props: AnalyticsProps): null;
+129 -17
View File
@@ -1,7 +1,9 @@
'use client';
import { useEffect } from 'react';
import { useEffect, useRef, useState } from 'react';
import { useConsentContext } from '../consent/client.js';
import { gtag } from '../consent/googleConsent.js';
import { CONSENT_COOKIE, DEFAULT_CONSENT, parseConsent, setDefaultConsent } from '../consent/index.js';
import { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from './pixels.js';
const GTM_SCRIPT = (id)=>`https://www.googletagmanager.com/gtm.js?id=${id}`;
const GA4_SCRIPT = (id)=>`https://www.googletagmanager.com/gtag/js?id=${id}`;
/** Reads the current consent state from cookie, or defaults if none. */ function readConsent() {
@@ -20,25 +22,106 @@ function injectScript(src) {
s.async = true;
document.head.appendChild(s);
}
/**
* Loads Google Analytics — GTM if a container ID is set, otherwise GA4 gtag.
*
* Consent Mode is initialised to the visitor's stored consent BEFORE the tag
* loads (via setDefaultConsent from the consent module), so tags respect the
* choice from the first hit; useConsent sends an update the moment the visitor
* decides. IDs are public and come from SiteIntegrations, passed in as props
* (the client project reads them server-side).
*
* Renders nothing — it only injects the scripts. Mount once, high in the tree
* (e.g. root layout), inside ConsentProvider.
*/ export function Analytics({ ga4MeasurementId, gtmContainerId }) {
const INTERACTION_EVENTS = [
'scroll',
'pointerdown',
'touchstart',
'keydown'
];
/** True once third-party tags may load (immediately, or per `defer` rules). */ function useDeferredReady(defer, timeoutMs) {
const [ready, setReady] = useState(!defer);
useEffect(()=>{
if (!defer || ready) {
return;
}
let timer;
const fire = ()=>setReady(true);
const onLoad = ()=>{
timer = setTimeout(()=>{
if ('requestIdleCallback' in window) {
window.requestIdleCallback(fire, {
timeout: 1000
});
} else {
fire();
}
}, timeoutMs);
};
for (const e of INTERACTION_EVENTS){
window.addEventListener(e, fire, {
once: true,
passive: true
});
}
if (document.readyState === 'complete') {
onLoad();
} else {
window.addEventListener('load', onLoad, {
once: true
});
}
return ()=>{
for (const e of INTERACTION_EVENTS){
window.removeEventListener(e, fire);
}
window.removeEventListener('load', onLoad);
if (timer) {
clearTimeout(timer);
}
};
}, [
defer,
ready,
timeoutMs
]);
return ready;
}
/**
* Loads every configured analytics / marketing tag, each respecting consent:
*
* - **Google (GA4 / GTM)** — Consent Mode: the visitor's stored choice is set as
* the default BEFORE the tag loads (always immediately, even with `defer`),
* and useConsent pushes an update the moment they decide. GTM wins if both
* IDs are set.
* - **Non-Google (Meta Pixel, Clarity, LinkedIn, TikTok)** — no Consent Mode, so
* each loads ONLY after its category is granted (marketing for
* Pixel/LinkedIn/TikTok, analytics for Clarity). Reacts live to the banner.
* - **`defer`** (opt-in) — additionally waits for first interaction / idle
* after load, for better LCP/INP. See AnalyticsProps.defer.
*
* All IDs are public and come from SiteIntegrations (getAnalyticsConfig), passed
* in as props. Renders nothing. Mount once, high in the tree, INSIDE
* <ConsentProvider> (required — it reads live consent state).
*/ export function Analytics(props) {
const { clarityProjectId, defer = false, deferTimeoutMs = 3500, ga4MeasurementId, gtmContainerId, linkedInPartnerId, metaPixelId, tiktokPixelId } = props;
// Live consent state — drives the non-Google pixels.
const { state } = useConsentContext();
const ready = useDeferredReady(defer, deferTimeoutMs);
const defaultConsentSet = useRef(false);
// --- Consent Mode default: immediately, once — never deferred ---
// No network cost, and it must precede any gtag('config') / GTM start, or
// Google assumes "granted".
useEffect(()=>{
if (defaultConsentSet.current) {
return;
}
if (!ga4MeasurementId && !gtmContainerId) {
return;
}
// 1. Consent Mode default = the visitor's stored choice, before tags load.
setDefaultConsent(readConsent());
// 2. Load the tag.
defaultConsentSet.current = true;
}, [
ga4MeasurementId,
gtmContainerId
]);
// --- Google: load once `ready`; Consent Mode handles gating ---
useEffect(()=>{
if (!ready) {
return;
}
if (!ga4MeasurementId && !gtmContainerId) {
return;
}
if (gtmContainerId) {
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
@@ -48,15 +131,44 @@ function injectScript(src) {
injectScript(GTM_SCRIPT(gtmContainerId));
} else if (ga4MeasurementId) {
injectScript(GA4_SCRIPT(ga4MeasurementId));
// Uses the shared gtag (pushes `arguments`, as Google's tags expect);
// real gtag.js wires itself up once the script loads.
gtag('js', new Date());
gtag('config', ga4MeasurementId);
}
}, [
ready,
ga4MeasurementId,
gtmContainerId
]);
// --- Non-Google: each when `ready` AND its consent category is granted ---
// Loaders are idempotent, so re-running on state changes is safe; a tag loads
// the first time both conditions hold and never doubles up.
useEffect(()=>{
if (!ready) {
return;
}
if (state.marketing) {
if (metaPixelId) {
loadMetaPixel(metaPixelId);
}
if (linkedInPartnerId) {
loadLinkedIn(linkedInPartnerId);
}
if (tiktokPixelId) {
loadTikTok(tiktokPixelId);
}
}
if (state.analytics && clarityProjectId) {
loadClarity(clarityProjectId);
}
}, [
ready,
state.marketing,
state.analytics,
metaPixelId,
linkedInPartnerId,
tiktokPixelId,
clarityProjectId
]);
return null;
}
File diff suppressed because one or more lines are too long
+2
View File
@@ -1,2 +1,4 @@
export { Analytics } from './Analytics.js';
export type { AnalyticsProps } from './Analytics.js';
export { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from './pixels.js';
export { pushDataLayer } from './pushDataLayer.js';
+3
View File
@@ -1,5 +1,8 @@
'use client';
export { Analytics } from './Analytics.js';
// Low-level pixel loaders — exported for manual conversion events if a project
// needs them (Analytics loads them automatically, consent-gated).
export { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from './pixels.js';
export { pushDataLayer } from './pushDataLayer.js';
//# sourceMappingURL=client.js.map
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/analytics/client.ts"],"sourcesContent":["'use client'\nexport { Analytics } from './Analytics.js'\nexport { pushDataLayer } from './pushDataLayer.js'\n"],"names":["Analytics","pushDataLayer"],"mappings":"AAAA;AACA,SAASA,SAAS,QAAQ,iBAAgB;AAC1C,SAASC,aAAa,QAAQ,qBAAoB"}
{"version":3,"sources":["../../../src/modules/analytics/client.ts"],"sourcesContent":["'use client'\nexport { Analytics } from './Analytics.js'\nexport type { AnalyticsProps } from './Analytics.js'\n// Low-level pixel loaders — exported for manual conversion events if a project\n// needs them (Analytics loads them automatically, consent-gated).\nexport { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from './pixels.js'\nexport { pushDataLayer } from './pushDataLayer.js'\n"],"names":["Analytics","loadClarity","loadLinkedIn","loadMetaPixel","loadTikTok","pushDataLayer"],"mappings":"AAAA;AACA,SAASA,SAAS,QAAQ,iBAAgB;AAE1C,+EAA+E;AAC/E,kEAAkE;AAClE,SAASC,WAAW,EAAEC,YAAY,EAAEC,aAAa,EAAEC,UAAU,QAAQ,cAAa;AAClF,SAASC,aAAa,QAAQ,qBAAoB"}
+2 -3
View File
@@ -1,9 +1,8 @@
import type { BasePayload } from 'payload';
import type { AnalyticsConfig } from './types.js';
/**
* Reads the public analytics IDs from SiteIntegrations, server-side.
*
* Returns only the two public IDs (GA4 / GTM) — safe to pass to the client
* Reads the public analytics / marketing tag IDs from SiteIntegrations,
* server-side. All are public (exposed client-side), so safe to pass to the
* <Analytics> component. Does NOT expose any secret from SiteIntegrations.
*/
export declare function getAnalyticsConfig(payload: BasePayload): Promise<AnalyticsConfig>;
+7 -4
View File
@@ -1,14 +1,17 @@
import { getSiteIntegrations } from '../payload/index.js';
/**
* Reads the public analytics IDs from SiteIntegrations, server-side.
*
* Returns only the two public IDs (GA4 / GTM) — safe to pass to the client
* Reads the public analytics / marketing tag IDs from SiteIntegrations,
* server-side. All are public (exposed client-side), so safe to pass to the
* <Analytics> component. Does NOT expose any secret from SiteIntegrations.
*/ export async function getAnalyticsConfig(payload) {
const integrations = await getSiteIntegrations(payload);
return {
clarityProjectId: integrations.clarityProjectId ?? null,
ga4MeasurementId: integrations.ga4MeasurementId ?? null,
gtmContainerId: integrations.gtmContainerId ?? null
gtmContainerId: integrations.gtmContainerId ?? null,
linkedInPartnerId: integrations.linkedInPartnerId ?? null,
metaPixelId: integrations.metaPixelId ?? null,
tiktokPixelId: integrations.tiktokPixelId ?? null
};
}
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/analytics/getAnalyticsConfig.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\nimport type { AnalyticsConfig } from './types.js'\n\nimport { getSiteIntegrations } from '../payload/index.js'\n\n/**\n * Reads the public analytics IDs from SiteIntegrations, server-side.\n *\n * Returns only the two public IDs (GA4 / GTM) — safe to pass to the client\n * <Analytics> component. Does NOT expose any secret from SiteIntegrations.\n */\nexport async function getAnalyticsConfig(payload: BasePayload): Promise<AnalyticsConfig> {\n const integrations = await getSiteIntegrations<AnalyticsConfig>(payload)\n return {\n ga4MeasurementId: integrations.ga4MeasurementId ?? null,\n gtmContainerId: integrations.gtmContainerId ?? null,\n }\n}\n"],"names":["getSiteIntegrations","getAnalyticsConfig","payload","integrations","ga4MeasurementId","gtmContainerId"],"mappings":"AAIA,SAASA,mBAAmB,QAAQ,sBAAqB;AAEzD;;;;;CAKC,GACD,OAAO,eAAeC,mBAAmBC,OAAoB;IAC3D,MAAMC,eAAe,MAAMH,oBAAqCE;IAChE,OAAO;QACLE,kBAAkBD,aAAaC,gBAAgB,IAAI;QACnDC,gBAAgBF,aAAaE,cAAc,IAAI;IACjD;AACF"}
{"version":3,"sources":["../../../src/modules/analytics/getAnalyticsConfig.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\nimport type { AnalyticsConfig } from './types.js'\n\nimport { getSiteIntegrations } from '../payload/index.js'\n\n/**\n * Reads the public analytics / marketing tag IDs from SiteIntegrations,\n * server-side. All are public (exposed client-side), so safe to pass to the\n * <Analytics> component. Does NOT expose any secret from SiteIntegrations.\n */\nexport async function getAnalyticsConfig(payload: BasePayload): Promise<AnalyticsConfig> {\n const integrations = await getSiteIntegrations<AnalyticsConfig>(payload)\n return {\n clarityProjectId: integrations.clarityProjectId ?? null,\n ga4MeasurementId: integrations.ga4MeasurementId ?? null,\n gtmContainerId: integrations.gtmContainerId ?? null,\n linkedInPartnerId: integrations.linkedInPartnerId ?? null,\n metaPixelId: integrations.metaPixelId ?? null,\n tiktokPixelId: integrations.tiktokPixelId ?? null,\n }\n}\n"],"names":["getSiteIntegrations","getAnalyticsConfig","payload","integrations","clarityProjectId","ga4MeasurementId","gtmContainerId","linkedInPartnerId","metaPixelId","tiktokPixelId"],"mappings":"AAIA,SAASA,mBAAmB,QAAQ,sBAAqB;AAEzD;;;;CAIC,GACD,OAAO,eAAeC,mBAAmBC,OAAoB;IAC3D,MAAMC,eAAe,MAAMH,oBAAqCE;IAChE,OAAO;QACLE,kBAAkBD,aAAaC,gBAAgB,IAAI;QACnDC,kBAAkBF,aAAaE,gBAAgB,IAAI;QACnDC,gBAAgBH,aAAaG,cAAc,IAAI;QAC/CC,mBAAmBJ,aAAaI,iBAAiB,IAAI;QACrDC,aAAaL,aAAaK,WAAW,IAAI;QACzCC,eAAeN,aAAaM,aAAa,IAAI;IAC/C;AACF"}
+21
View File
@@ -0,0 +1,21 @@
/**
* Loaders for non-Google marketing/analytics pixels. Each is idempotent (guards
* against double-init) and loads the vendor's own script + bootstrap.
*
* These are the one place `any` is unavoidable: vendor SDK bootstraps attach
* untyped globals (fbq, clarity, lintrk, ttq) to `window`. Casts are contained
* here; nothing else in the kit uses `any`.
*
* CONSENT: these vendors have no Google Consent Mode — the caller (Analytics)
* loads each ONLY after the matching consent category is granted:
* Meta Pixel / LinkedIn / TikTok → marketing
* Microsoft Clarity → analytics
*/
/** Meta (Facebook) Pixel — fires PageView on load. */
export declare function loadMetaPixel(id: string): void;
/** Microsoft Clarity — heatmaps / session recordings (analytics category). */
export declare function loadClarity(id: string): void;
/** LinkedIn Insight Tag (marketing). */
export declare function loadLinkedIn(partnerId: string): void;
/** TikTok Pixel (marketing) — fires page view on load. */
export declare function loadTikTok(id: string): void;
+134
View File
@@ -0,0 +1,134 @@
/* eslint-disable @typescript-eslint/no-explicit-any */ /**
* Loaders for non-Google marketing/analytics pixels. Each is idempotent (guards
* against double-init) and loads the vendor's own script + bootstrap.
*
* These are the one place `any` is unavoidable: vendor SDK bootstraps attach
* untyped globals (fbq, clarity, lintrk, ttq) to `window`. Casts are contained
* here; nothing else in the kit uses `any`.
*
* CONSENT: these vendors have no Google Consent Mode — the caller (Analytics)
* loads each ONLY after the matching consent category is granted:
* Meta Pixel / LinkedIn / TikTok → marketing
* Microsoft Clarity → analytics
*/ /** Meta (Facebook) Pixel — fires PageView on load. */ export function loadMetaPixel(id) {
if (typeof window === 'undefined') {
return;
}
const w = window;
if (w.fbq) {
return;
}
const n = w.fbq = function(...args) {
if (n.callMethod) {
n.callMethod.apply(n, args);
} else {
n.queue.push(args);
}
};
if (!w._fbq) {
w._fbq = n;
}
n.push = n;
n.loaded = true;
n.version = '2.0';
n.queue = [];
const s = document.createElement('script');
s.async = true;
s.src = 'https://connect.facebook.net/en_US/fbevents.js';
document.head.appendChild(s);
w.fbq('init', id);
w.fbq('track', 'PageView');
}
/** Microsoft Clarity — heatmaps / session recordings (analytics category). */ export function loadClarity(id) {
if (typeof window === 'undefined') {
return;
}
const w = window;
if (w.clarity) {
return;
}
w.clarity = function(...a) {
;
(w.clarity.q = w.clarity.q || []).push(a);
};
const s = document.createElement('script');
s.async = true;
s.src = `https://www.clarity.ms/tag/${id}`;
document.head.appendChild(s);
}
/** LinkedIn Insight Tag (marketing). */ export function loadLinkedIn(partnerId) {
if (typeof window === 'undefined') {
return;
}
const w = window;
w._linkedin_partner_id = partnerId;
w._linkedin_data_partner_ids = w._linkedin_data_partner_ids || [];
if (w._linkedin_data_partner_ids.includes(partnerId)) {
if (document.getElementById('ipal-linkedin-insight')) {
return;
}
} else {
w._linkedin_data_partner_ids.push(partnerId);
}
if (document.getElementById('ipal-linkedin-insight')) {
return;
}
const s = document.createElement('script');
s.async = true;
s.id = 'ipal-linkedin-insight';
s.src = 'https://snap.licdn.com/li.lms-analytics/insight.min.js';
document.head.appendChild(s);
}
/** TikTok Pixel (marketing) — fires page view on load. */ export function loadTikTok(id) {
if (typeof window === 'undefined') {
return;
}
const w = window;
if (w.ttq) {
return;
}
w.TiktokAnalyticsObject = 'ttq';
const ttq = w.ttq = [];
ttq.methods = [
'page',
'track',
'identify',
'instances',
'debug',
'on',
'off',
'once',
'ready',
'alias',
'group',
'enableCookie',
'disableCookie'
];
ttq.setAndDefer = function(t, e) {
t[e] = function(...args) {
t.push([
e,
...args
]);
};
};
for (const m of ttq.methods){
ttq.setAndDefer(ttq, m);
}
ttq.load = function(e) {
const url = 'https://analytics.tiktok.com/i18n/pixel/events.js';
ttq._i = ttq._i || {};
ttq._i[e] = [];
ttq._i[e]._u = url;
ttq._t = ttq._t || {};
ttq._t[e] = Number(new Date());
const s = document.createElement('script');
s.async = true;
s.src = `${url}?sdkid=${e}&lib=ttq`;
document.head.appendChild(s);
};
ttq.load(id);
ttq.page();
}
//# sourceMappingURL=pixels.js.map
File diff suppressed because one or more lines are too long
+13 -3
View File
@@ -1,9 +1,19 @@
/**
* Analytics IDs, read from SiteIntegrations (public — safe on the client).
* Analytics / marketing tag IDs, read from SiteIntegrations (all public — safe
* on the client). Google tags (GA4/GTM) use Consent Mode; the rest load only
* after the matching consent category is granted (see Analytics).
*/
export type AnalyticsConfig = {
/** GA4 Measurement ID, e.g. 'G-XXXXXXXXXX'. */
/** Microsoft Clarity project ID. (analytics consent) */
clarityProjectId?: null | string;
/** GA4 Measurement ID, e.g. 'G-XXXXXXXXXX'. (Google — Consent Mode) */
ga4MeasurementId?: null | string;
/** GTM Container ID, e.g. 'GTM-XXXXXXX'. */
/** GTM Container ID, e.g. 'GTM-XXXXXXX'. (Google — Consent Mode) */
gtmContainerId?: null | string;
/** LinkedIn Insight Tag partner ID. (marketing consent) */
linkedInPartnerId?: null | string;
/** Meta (Facebook) Pixel ID, ~15–16 digits. (marketing consent) */
metaPixelId?: null | string;
/** TikTok Pixel ID. (marketing consent) */
tiktokPixelId?: null | string;
};
+3 -1
View File
@@ -1,5 +1,7 @@
/**
* Analytics IDs, read from SiteIntegrations (public — safe on the client).
* Analytics / marketing tag IDs, read from SiteIntegrations (all public — safe
* on the client). Google tags (GA4/GTM) use Consent Mode; the rest load only
* after the matching consent category is granted (see Analytics).
*/ export { };
//# sourceMappingURL=types.js.map
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/analytics/types.ts"],"sourcesContent":["/**\n * Analytics IDs, read from SiteIntegrations (public — safe on the client).\n */\nexport type AnalyticsConfig = {\n /** GA4 Measurement ID, e.g. 'G-XXXXXXXXXX'. */\n ga4MeasurementId?: null | string\n /** GTM Container ID, e.g. 'GTM-XXXXXXX'. */\n gtmContainerId?: null | string\n}\n"],"names":[],"mappings":"AAAA;;CAEC,GACD,WAKC"}
{"version":3,"sources":["../../../src/modules/analytics/types.ts"],"sourcesContent":["/**\n * Analytics / marketing tag IDs, read from SiteIntegrations (all public — safe\n * on the client). Google tags (GA4/GTM) use Consent Mode; the rest load only\n * after the matching consent category is granted (see Analytics).\n */\nexport type AnalyticsConfig = {\n /** Microsoft Clarity project ID. (analytics consent) */\n clarityProjectId?: null | string\n /** GA4 Measurement ID, e.g. 'G-XXXXXXXXXX'. (Google — Consent Mode) */\n ga4MeasurementId?: null | string\n /** GTM Container ID, e.g. 'GTM-XXXXXXX'. (Google — Consent Mode) */\n gtmContainerId?: null | string\n /** LinkedIn Insight Tag partner ID. (marketing consent) */\n linkedInPartnerId?: null | string\n /** Meta (Facebook) Pixel ID, ~15–16 digits. (marketing consent) */\n metaPixelId?: null | string\n /** TikTok Pixel ID. (marketing consent) */\n tiktokPixelId?: null | string\n}\n"],"names":[],"mappings":"AAAA;;;;CAIC,GACD,WAaC"}
+14 -7
View File
@@ -1,3 +1,4 @@
import type { Payload } from 'payload';
/**
* White-label admin branding: the Payload admin panel's logo (login + nav) and
* icon, pulled from the project's SiteSettings so each client sees THEIR brand,
@@ -5,13 +6,13 @@
* automatically by `ipalKit({ whiteLabel: true })` (it injects
* admin.components.graphics.Logo/Icon pointing here).
*
* Server Components — they read the SiteSettings global at render. Data access
* uses the project's `@payload-config` alias (universal in Payload 3 Next apps),
* loaded via a variable specifier so the PLUGIN's own typecheck doesn't try to
* resolve it (same pattern as the optional 2FA import). Everything is wrapped in
* try/catch: on the login screen before the DB is ready, or a build with no DB,
* the component falls back to the site name text, then to null (Payload's own
* default) — never throws, never blocks the panel.
* Server Components — they read the SiteSettings global at render, using the
* `payload` instance Payload itself passes to admin server components. NO
* `import('@payload-config')`: a variable-specifier import isn't traced by the
* Next bundler ("Cannot find module '@payload-config'") — same bug class as the
* old 2FA import. Everything is wrapped in try/catch: no payload prop, DB not
* ready, etc. → site name text, then null (Payload's own default) — never
* throws, never blocks the panel.
*
* A0: no client brand in code. The logo/name come from the panel; if nothing is
* set, nothing is forced.
@@ -19,8 +20,14 @@
type BrandingProps = {
/** Upload field to render as the image. Default 'logo' (Logo) / 'favicon' (Icon). */
imageField?: string;
/** Injected by Payload — current admin locale (object or code). */
locale?: {
code?: string;
} | string;
/** Field holding the site name. Default 'siteName'. */
nameField?: string;
/** Injected by Payload into admin server components. */
payload?: Payload;
/** SiteSettings global slug. Default 'site-settings'. */
settingsSlug?: string;
};
+33 -13
View File
@@ -1,25 +1,45 @@
import { jsx as _jsx } from "react/jsx-runtime";
import { getPayload } from 'payload';
async function loadBranding(settingsSlug, nameField, imageField) {
/** A localized text field may arrive as a string or a { locale: value } map. */ function pickText(value, locale) {
if (typeof value === 'string') {
return value;
}
if (value && typeof value === 'object') {
const map = value;
const preferred = locale ? map[locale] : undefined;
if (typeof preferred === 'string') {
return preferred;
}
const first = Object.values(map).find((v)=>typeof v === 'string');
return first ?? null;
}
return null;
}
async function loadBranding(props, settingsSlug, nameField, imageField) {
const { payload } = props;
if (!payload) {
return {
name: null,
url: null
};
}
try {
// Consumer alias — resolved in the project's build, hidden from plugin tsc.
const spec = '@payload-config';
const mod = await import(spec);
const payload = await getPayload({
config: mod.default
});
const locale = typeof props.locale === 'string' ? props.locale : props.locale?.code;
const settings = await payload.findGlobal({
slug: settingsSlug,
depth: 1
depth: 1,
...locale ? {
locale: locale
} : {}
});
const name = typeof settings[nameField] === 'string' ? settings[nameField] : null;
const name = pickText(settings[nameField], locale);
const image = settings[imageField];
const url = image && typeof image === 'object' && typeof image.url === 'string' ? image.url : null;
return {
name,
url
};
} catch {
} catch (error) {
console.warn('[ipal] admin branding: falling back to Payload default:', error);
return {
name: null,
url: null
@@ -32,7 +52,7 @@ async function loadBranding(settingsSlug, nameField, imageField) {
* falls back to `siteName` text. Sized generously for the login screen.
*/ export async function AdminLogo(props = {}) {
const { imageField = 'logo', nameField = 'siteName', settingsSlug = 'site-settings' } = props;
const { name, url } = await loadBranding(settingsSlug, nameField, imageField);
const { name, url } = await loadBranding(props, settingsSlug, nameField, imageField);
if (url) {
return /*#__PURE__*/ _jsx("img", {
alt: name ?? '',
@@ -59,7 +79,7 @@ async function loadBranding(settingsSlug, nameField, imageField) {
}
/** Admin panel icon (small nav glyph). SiteSettings `favicon`, falls back to initials. */ export async function AdminIcon(props = {}) {
const { imageField = 'favicon', nameField = 'siteName', settingsSlug = 'site-settings' } = props;
const { name, url } = await loadBranding(settingsSlug, nameField, imageField);
const { name, url } = await loadBranding(props, settingsSlug, nameField, imageField);
if (url) {
return /*#__PURE__*/ _jsx("img", {
alt: name ?? '',
File diff suppressed because one or more lines are too long
+21 -10
View File
@@ -1,25 +1,36 @@
import type { BasePayload } from 'payload';
import type { I18nConfig } from '../i18n/index.js';
import type { ConsentTexts } from './texts.js';
type PrivacyPage = {
slug?: null | Record<string, unknown>;
title?: unknown;
} | null;
type GetConsentTextsArgs = {
config: I18nConfig;
locale?: string;
payload: BasePayload;
/**
* Privacy-policy label + the system page (from SiteSettings.privacyPolicy,
* read with locale:'all') to link to. Optional — omit for no link.
* Privacy-policy link. Omit it — the page is read automatically from
* SiteSettings → System Pages → Privacy Policy, and the link text from
* CookieSettings → privacyLinkLabel (per locale, editable in the panel).
*
* - `false` → no link.
* - `{ page }` → use this page (SiteSettings.privacyPolicy read with locale:'all').
* - `label` → DEPRECATED (hardcoded text); used only when the panel field is empty.
*/
privacyPolicy?: {
label: string;
page: {
slug?: null | Record<string, unknown>;
} | null;
};
/** @deprecated Set CookieSettings → privacyLinkLabel in the panel instead. */
label?: string;
page?: PrivacyPage;
} | false;
/** SiteSettings global slug for the automatic privacy page lookup. Default 'site-settings'. */
settingsSlug?: string;
};
/**
* Resolves consent banner texts from the CookieSettings global, falling back to
* English defaults per field. The privacy-policy link is built from the pages
* module (system page role), not stored in CookieSettings — one source of truth.
* English defaults per field. The privacy-policy link target comes from the
* pages module (system page role, read automatically); its text from
* CookieSettings.privacyLinkLabel — both editable in the panel, per locale.
*/
export declare function getConsentTexts({ config, locale, payload, privacyPolicy, }: GetConsentTextsArgs): Promise<ConsentTexts>;
export declare function getConsentTexts({ config, locale, payload, privacyPolicy, settingsSlug, }: GetConsentTextsArgs): Promise<ConsentTexts>;
export {};
+30 -9
View File
@@ -1,3 +1,4 @@
import { resolveLocalized } from '../i18n/resolveLocalized.js';
import { getSystemPagePath } from '../pages/index.js';
import { getGlobal } from '../payload/index.js';
import { CONSENT_CATEGORIES } from './categories.js';
@@ -31,11 +32,28 @@ import { CONSENT_CATEGORIES } from './categories.js';
privacyLink: null,
settingsTitle: 'Cookie settings'
};
/** Last-resort link text — only when neither the panel nor the page has one. */ const FALLBACK_PRIVACY_LABEL = 'Privacy policy';
/** Reads SiteSettings.privacyPolicy with all locales (slug + title as maps). */ async function readPrivacyPage(payload, settingsSlug) {
try {
const settings = await payload.findGlobal({
slug: settingsSlug,
depth: 1,
locale: 'all'
});
const page = settings.privacyPolicy;
return page && typeof page === 'object' ? page : null;
} catch (error) {
// No pages option / no privacyPolicy field / DB unreachable at build → no link.
console.warn('[ipal] getConsentTexts: privacy page lookup failed, banner without link:', error);
return null;
}
}
/**
* Resolves consent banner texts from the CookieSettings global, falling back to
* English defaults per field. The privacy-policy link is built from the pages
* module (system page role), not stored in CookieSettings — one source of truth.
*/ export async function getConsentTexts({ config, locale, payload, privacyPolicy }) {
* English defaults per field. The privacy-policy link target comes from the
* pages module (system page role, read automatically); its text from
* CookieSettings.privacyLinkLabel — both editable in the panel, per locale.
*/ export async function getConsentTexts({ config, locale, payload, privacyPolicy, settingsSlug = 'site-settings' }) {
const g = await getGlobal(payload, 'cookie-settings', {
locale
});
@@ -48,16 +66,19 @@ import { CONSENT_CATEGORIES } from './categories.js';
};
}
let privacyLink = null;
if (privacyPolicy?.page && locale) {
const href = getSystemPagePath({
if (privacyPolicy !== false && locale) {
const page = privacyPolicy?.page !== undefined ? privacyPolicy.page : await readPrivacyPage(payload, settingsSlug);
const href = page ? getSystemPagePath({
config,
locale,
page: privacyPolicy.page
});
if (href) {
page
}) : undefined;
if (page && href) {
// Panel first, then the deprecated code label, then the page's own title.
const label = g.privacyLinkLabel?.trim() || privacyPolicy?.label?.trim() || resolveLocalized(page.title, locale).trim() || FALLBACK_PRIVACY_LABEL;
privacyLink = {
href,
label: privacyPolicy.label
label
};
}
}
File diff suppressed because one or more lines are too long
+1
View File
@@ -6,6 +6,7 @@ export { getArchiveEntries } from './getArchiveEntries.js';
export type { ArchiveEntries } from './getArchiveEntries.js';
export { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegotiation.js';
export { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js';
export { resolveNotFoundPage } from './resolveNotFoundPage.js';
export { resolveRedirect } from './resolveRedirect.js';
export { resolveRoute } from './resolveRoute.js';
export type { ResolvedRoute } from './resolveRoute.js';
+1
View File
@@ -5,6 +5,7 @@ export { createSearchRoute } from './createSearchRoute.js';
export { getArchiveEntries } from './getArchiveEntries.js';
export { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegotiation.js';
export { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js';
export { resolveNotFoundPage } from './resolveNotFoundPage.js';
export { resolveRedirect } from './resolveRedirect.js';
export { resolveRoute } from './resolveRoute.js';
export { searchContent } from './searchContent.js';
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/content/index.ts"],"sourcesContent":["export { buildArchiveFields } from './archiveFields.js'\nexport { blocksToMarkdown } from './blocksToMarkdown.js'\nexport { createMarkdownRenderer, markdownResponse } from './createMarkdownRenderer.js'\nexport { createSearchRoute } from './createSearchRoute.js'\nexport { getArchiveEntries } from './getArchiveEntries.js'\nexport type { ArchiveEntries } from './getArchiveEntries.js'\nexport { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegotiation.js'\nexport { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js'\nexport { resolveRedirect } from './resolveRedirect.js'\nexport { resolveRoute } from './resolveRoute.js'\nexport type { ResolvedRoute } from './resolveRoute.js'\nexport { searchContent } from './searchContent.js'\nexport type { SearchResult } from './searchContent.js'\nexport type { ContentCollectionOption, ContentOption } from './types.js'\nexport { archiveFieldName } from './types.js'\n"],"names":["buildArchiveFields","blocksToMarkdown","createMarkdownRenderer","markdownResponse","createSearchRoute","getArchiveEntries","MARKDOWN_PREFIX","markdownHref","prefersMarkdown","buildArchivePath","buildEntryPath","parsePageParam","resolveRedirect","resolveRoute","searchContent","archiveFieldName"],"mappings":"AAAA,SAASA,kBAAkB,QAAQ,qBAAoB;AACvD,SAASC,gBAAgB,QAAQ,wBAAuB;AACxD,SAASC,sBAAsB,EAAEC,gBAAgB,QAAQ,8BAA6B;AACtF,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,iBAAiB,QAAQ,yBAAwB;AAE1D,SAASC,eAAe,EAAEC,YAAY,EAAEC,eAAe,QAAQ,2BAA0B;AACzF,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,cAAc,QAAQ,aAAY;AAC7E,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,YAAY,QAAQ,oBAAmB;AAEhD,SAASC,aAAa,QAAQ,qBAAoB;AAGlD,SAASC,gBAAgB,QAAQ,aAAY"}
{"version":3,"sources":["../../../src/modules/content/index.ts"],"sourcesContent":["export { buildArchiveFields } from './archiveFields.js'\nexport { blocksToMarkdown } from './blocksToMarkdown.js'\nexport { createMarkdownRenderer, markdownResponse } from './createMarkdownRenderer.js'\nexport { createSearchRoute } from './createSearchRoute.js'\nexport { getArchiveEntries } from './getArchiveEntries.js'\nexport type { ArchiveEntries } from './getArchiveEntries.js'\nexport { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegotiation.js'\nexport { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js'\nexport { resolveNotFoundPage } from './resolveNotFoundPage.js'\nexport { resolveRedirect } from './resolveRedirect.js'\nexport { resolveRoute } from './resolveRoute.js'\nexport type { ResolvedRoute } from './resolveRoute.js'\nexport { searchContent } from './searchContent.js'\nexport type { SearchResult } from './searchContent.js'\nexport type { ContentCollectionOption, ContentOption } from './types.js'\nexport { archiveFieldName } from './types.js'\n"],"names":["buildArchiveFields","blocksToMarkdown","createMarkdownRenderer","markdownResponse","createSearchRoute","getArchiveEntries","MARKDOWN_PREFIX","markdownHref","prefersMarkdown","buildArchivePath","buildEntryPath","parsePageParam","resolveNotFoundPage","resolveRedirect","resolveRoute","searchContent","archiveFieldName"],"mappings":"AAAA,SAASA,kBAAkB,QAAQ,qBAAoB;AACvD,SAASC,gBAAgB,QAAQ,wBAAuB;AACxD,SAASC,sBAAsB,EAAEC,gBAAgB,QAAQ,8BAA6B;AACtF,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,iBAAiB,QAAQ,yBAAwB;AAE1D,SAASC,eAAe,EAAEC,YAAY,EAAEC,eAAe,QAAQ,2BAA0B;AACzF,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,cAAc,QAAQ,aAAY;AAC7E,SAASC,mBAAmB,QAAQ,2BAA0B;AAC9D,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,YAAY,QAAQ,oBAAmB;AAEhD,SAASC,aAAa,QAAQ,qBAAoB;AAGlD,SAASC,gBAAgB,QAAQ,aAAY"}
+23
View File
@@ -0,0 +1,23 @@
import type { BasePayload } from 'payload';
type ResolveNotFoundPageArgs = {
locale: string;
/** Client's Pages collection slug. Defaults to 'pages'. */
pagesSlug?: string;
payload: BasePayload;
/** SiteSettings global slug. Defaults to 'site-settings'. */
settingsSlug?: string;
};
/**
* Returns the page the editor assigned as **404 (Not Found)** in System Pages,
* fully populated (depth 2, same shape as resolveRoute's pages), or null when
* the role is unassigned.
*
* Used by the project's `not-found.tsx`. The editor decides what a 404 looks
* like: a dedicated "Not found" page, or simply the homepage. Null means
* "render the project's built-in fallback view".
*
* Never throws — a missing DB (container build prerendering not-found) or a
* deleted page just yields null, so the 404 view can't crash the build.
*/
export declare function resolveNotFoundPage({ locale, pagesSlug, payload, settingsSlug, }: ResolveNotFoundPageArgs): Promise<null | Record<string, unknown>>;
export {};
+37
View File
@@ -0,0 +1,37 @@
/**
* Returns the page the editor assigned as **404 (Not Found)** in System Pages,
* fully populated (depth 2, same shape as resolveRoute's pages), or null when
* the role is unassigned.
*
* Used by the project's `not-found.tsx`. The editor decides what a 404 looks
* like: a dedicated "Not found" page, or simply the homepage. Null means
* "render the project's built-in fallback view".
*
* Never throws — a missing DB (container build prerendering not-found) or a
* deleted page just yields null, so the 404 view can't crash the build.
*/ export async function resolveNotFoundPage({ locale, pagesSlug = 'pages', payload, settingsSlug = 'site-settings' }) {
try {
const settings = await payload.findGlobal({
slug: settingsSlug,
depth: 0,
locale: locale
});
const rel = settings.notFound;
const id = typeof rel === 'string' || typeof rel === 'number' ? rel : rel && typeof rel === 'object' ? rel.id : undefined;
if (id === undefined) {
return null;
}
const doc = await payload.findByID({
id,
collection: pagesSlug,
depth: 2,
locale: locale
});
return doc ?? null;
} catch (error) {
console.warn('[ipal] resolveNotFoundPage: falling back to built-in 404 view:', error);
return null;
}
}
//# sourceMappingURL=resolveNotFoundPage.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/modules/content/resolveNotFoundPage.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\ntype ResolveNotFoundPageArgs = {\n locale: string\n /** Client's Pages collection slug. Defaults to 'pages'. */\n pagesSlug?: string\n payload: BasePayload\n /** SiteSettings global slug. Defaults to 'site-settings'. */\n settingsSlug?: string\n}\n\n/**\n * Returns the page the editor assigned as **404 (Not Found)** in System Pages,\n * fully populated (depth 2, same shape as resolveRoute's pages), or null when\n * the role is unassigned.\n *\n * Used by the project's `not-found.tsx`. The editor decides what a 404 looks\n * like: a dedicated \"Not found\" page, or simply the homepage. Null means\n * \"render the project's built-in fallback view\".\n *\n * Never throws — a missing DB (container build prerendering not-found) or a\n * deleted page just yields null, so the 404 view can't crash the build.\n */\nexport async function resolveNotFoundPage({\n locale,\n pagesSlug = 'pages',\n payload,\n settingsSlug = 'site-settings',\n}: ResolveNotFoundPageArgs): Promise<null | Record<string, unknown>> {\n try {\n const settings = (await payload.findGlobal({\n slug: settingsSlug as never,\n depth: 0,\n locale: locale as never,\n })) as Record<string, unknown>\n\n const rel = settings.notFound\n const id =\n typeof rel === 'string' || typeof rel === 'number'\n ? rel\n : rel && typeof rel === 'object'\n ? (rel as { id?: number | string }).id\n : undefined\n if (id === undefined) {return null}\n\n const doc = await payload.findByID({\n id,\n collection: pagesSlug as never,\n depth: 2,\n locale: locale as never,\n })\n return (doc as null | Record<string, unknown>) ?? null\n } catch (error) {\n console.warn('[ipal] resolveNotFoundPage: falling back to built-in 404 view:', error)\n return null\n }\n}\n"],"names":["resolveNotFoundPage","locale","pagesSlug","payload","settingsSlug","settings","findGlobal","slug","depth","rel","notFound","id","undefined","doc","findByID","collection","error","console","warn"],"mappings":"AAWA;;;;;;;;;;;CAWC,GACD,OAAO,eAAeA,oBAAoB,EACxCC,MAAM,EACNC,YAAY,OAAO,EACnBC,OAAO,EACPC,eAAe,eAAe,EACN;IACxB,IAAI;QACF,MAAMC,WAAY,MAAMF,QAAQG,UAAU,CAAC;YACzCC,MAAMH;YACNI,OAAO;YACPP,QAAQA;QACV;QAEA,MAAMQ,MAAMJ,SAASK,QAAQ;QAC7B,MAAMC,KACJ,OAAOF,QAAQ,YAAY,OAAOA,QAAQ,WACtCA,MACAA,OAAO,OAAOA,QAAQ,WACpB,AAACA,IAAiCE,EAAE,GACpCC;QACR,IAAID,OAAOC,WAAW;YAAC,OAAO;QAAI;QAElC,MAAMC,MAAM,MAAMV,QAAQW,QAAQ,CAAC;YACjCH;YACAI,YAAYb;YACZM,OAAO;YACPP,QAAQA;QACV;QACA,OAAO,AAACY,OAA0C;IACpD,EAAE,OAAOG,OAAO;QACdC,QAAQC,IAAI,CAAC,kEAAkEF;QAC/E,OAAO;IACT;AACF"}
+14
View File
@@ -114,6 +114,20 @@ import { archiveFieldName } from './types.js';
if (!doc) {
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
// it as not found, so the route calls notFound() and not-found.tsx renders
// that same page with a real 404 status. (If 404 = homepage, the homepage is
// served from the root branch above and never reaches here by its own slug
// in a way that matters — but guard anyway so we never hide the homepage.)
const notFound = settings.notFound;
const homepage = settings.homepage;
const notFoundId = notFound && typeof notFound === 'object' ? notFound.id : notFound;
const homepageId = homepage && typeof homepage === 'object' ? homepage.id : homepage;
const docId = doc.id;
if (notFoundId != null && notFoundId === docId && notFoundId !== homepageId) {
return null;
}
return {
type: 'page',
doc: doc
File diff suppressed because one or more lines are too long
+1
View File
@@ -62,6 +62,7 @@ export declare function createContentHelpers({ baseUrl, config, content, i18n, p
getCachedPayload: () => Promise<BasePayload>;
getConfiguredLocales: () => Promise<string[]>;
getEntries: (collection: string, locale: string, page: number, perPage: number) => Promise<ArchiveEntries>;
getNotFoundPage: (locale: string) => Promise<Record<string, unknown> | null>;
getSettings: (locale: string) => Promise<import("payload").JsonObject>;
resolveRoute: (locale: string, segments: string[] | undefined, page: number) => Promise<null | ResolvedRoute>;
robots: () => RobotsRules;
+25 -1
View File
@@ -1,6 +1,6 @@
import { getPayload } from 'payload';
import { cache } from 'react';
import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js';
import { getArchiveEntries, resolveNotFoundPage, resolveRoute as resolveRouteRaw } from '../content/index.js';
import { buildRobots, buildSitemapEntries } from '../seo/index.js';
/**
* Bundles the per-request data helpers a frontend needs — the same cached
@@ -56,6 +56,24 @@ import { buildRobots, buildSitemapEntries } from '../seo/index.js';
settingsSlug
});
});
/**
* The page assigned as 404 in System Pages (or null → built-in fallback).
* For app/not-found.tsx; never throws. Locale comes from the x-locale header
* set by createProxy (not-found.tsx receives no params).
*/ const getNotFoundPage = cache(async (locale)=>{
try {
const payload = await getCachedPayload();
return await resolveNotFoundPage({
locale,
pagesSlug,
payload,
settingsSlug
});
} catch {
return null // DB unreachable (container build) — fallback view
;
}
});
/** One page of a collection's entries, for an archive listing. */ const getEntries = cache(async (collection, locale, page, perPage)=>{
const payload = await getCachedPayload();
return getArchiveEntries({
@@ -154,6 +172,8 @@ import { buildRobots, buildSitemapEntries } from '../seo/index.js';
locale: 'all'
}).catch(()=>null);
const homeId = settings?.homepage?.id;
// The assigned 404 page renders via not-found.tsx, never as its own URL.
const notFoundId = settings?.notFound?.id !== undefined && settings.notFound.id !== homeId ? settings.notFound.id : undefined;
const EXCLUDED = new Set([
'404',
'500',
@@ -177,6 +197,9 @@ import { buildRobots, buildSitemapEntries } from '../seo/index.js';
if (raw._status && raw._status !== 'published') {
continue;
}
if (notFoundId !== undefined && raw.id === notFoundId) {
continue;
}
// NOTE: unlike the sitemap, we do NOT skip meta.noindex here. A noindex
// page (privacy, cookies, terms) still needs to render — users reach it
// from the footer and crawlers read its <meta robots=noindex>. Pre-render
@@ -230,6 +253,7 @@ import { buildRobots, buildSitemapEntries } from '../seo/index.js';
getCachedPayload,
getConfiguredLocales,
getEntries,
getNotFoundPage,
getSettings,
resolveRoute,
robots,
File diff suppressed because one or more lines are too long
+4 -1
View File
@@ -41,9 +41,12 @@
status: 200
});
} catch (err) {
// Log the real error for ops; keep the PUBLIC body generic — a 503 with
// `db: 'down'` is all an orchestrator needs, and raw DB error text (host,
// credentials-in-URL, driver internals) must not leak on a public route.
console.warn('[ipal] createHealthRoute: database unreachable:', err);
const body = {
db: 'down',
error: err instanceof Error ? err.message : 'unknown',
status: 'error',
timestamp: new Date().toISOString(),
tookMs: Date.now() - startedAt
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/health/createHealthRoute.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\ntype CreateHealthRouteArgs = {\n /**\n * Collection to ping for a real DB round-trip. Default 'pages'. Pick any\n * collection that always exists in the project.\n */\n collection?: string\n /**\n * Optional extra checks merged into the body (e.g. a cache or queue ping).\n * Throwing marks the whole healthcheck unhealthy.\n */\n extra?: () => Promise<Record<string, unknown>>\n /** Same cached accessor the rest of the app uses. */\n getCachedPayload: () => Promise<BasePayload>\n}\n\n/**\n * A liveness/readiness route for Coolify/Docker healthchecks and uptime\n * monitors. Does a real DB round-trip (not just \"process is up\") and returns\n * 200 when reachable, 503 when not — so an orchestrator can restart or hold\n * traffic off a container whose database is down.\n *\n * // app/api/health/route.ts\n * import { createHealthRoute } from '@intecion/ipal-kit'\n * import { getCachedPayload } from '@/lib/content'\n * export const dynamic = 'force-dynamic' // never prerender/cache a healthcheck\n * export const GET = createHealthRoute({ getCachedPayload })\n *\n * Point Coolify's healthcheck at /api/health. Uses the global `Response`\n * (standard in Next route handlers) — no next/server import, peer-dep clean.\n */\nexport function createHealthRoute(args: CreateHealthRouteArgs): () => Promise<Response> {\n const { collection = 'pages', extra, getCachedPayload } = args\n\n return async () => {\n const startedAt = Date.now()\n try {\n const payload = await getCachedPayload()\n // Cheapest real round-trip: ask for at most one row, no population.\n await payload.find({\n collection: collection as never,\n depth: 0,\n limit: 1,\n pagination: false,\n })\n\n const extraData = extra ? await extra() : {}\n const body = {\n db: 'up',\n status: 'ok',\n timestamp: new Date().toISOString(),\n tookMs: Date.now() - startedAt,\n ...extraData,\n }\n return new Response(JSON.stringify(body), {\n headers: { 'cache-control': 'no-store', 'content-type': 'application/json' },\n status: 200,\n })\n } catch (err) {\n const body = {\n db: 'down',\n error: err instanceof Error ? err.message : 'unknown',\n status: 'error',\n timestamp: new Date().toISOString(),\n tookMs: Date.now() - startedAt,\n }\n return new Response(JSON.stringify(body), {\n headers: { 'cache-control': 'no-store', 'content-type': 'application/json' },\n status: 503,\n })\n }\n }\n}\n"],"names":["createHealthRoute","args","collection","extra","getCachedPayload","startedAt","Date","now","payload","find","depth","limit","pagination","extraData","body","db","status","timestamp","toISOString","tookMs","Response","JSON","stringify","headers","err","error","Error","message"],"mappings":"AAiBA;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASA,kBAAkBC,IAA2B;IAC3D,MAAM,EAAEC,aAAa,OAAO,EAAEC,KAAK,EAAEC,gBAAgB,EAAE,GAAGH;IAE1D,OAAO;QACL,MAAMI,YAAYC,KAAKC,GAAG;QAC1B,IAAI;YACF,MAAMC,UAAU,MAAMJ;YACtB,oEAAoE;YACpE,MAAMI,QAAQC,IAAI,CAAC;gBACjBP,YAAYA;gBACZQ,OAAO;gBACPC,OAAO;gBACPC,YAAY;YACd;YAEA,MAAMC,YAAYV,QAAQ,MAAMA,UAAU,CAAC;YAC3C,MAAMW,OAAO;gBACXC,IAAI;gBACJC,QAAQ;gBACRC,WAAW,IAAIX,OAAOY,WAAW;gBACjCC,QAAQb,KAAKC,GAAG,KAAKF;gBACrB,GAAGQ,SAAS;YACd;YACA,OAAO,IAAIO,SAASC,KAAKC,SAAS,CAACR,OAAO;gBACxCS,SAAS;oBAAE,iBAAiB;oBAAY,gBAAgB;gBAAmB;gBAC3EP,QAAQ;YACV;QACF,EAAE,OAAOQ,KAAK;YACZ,MAAMV,OAAO;gBACXC,IAAI;gBACJU,OAAOD,eAAeE,QAAQF,IAAIG,OAAO,GAAG;gBAC5CX,QAAQ;gBACRC,WAAW,IAAIX,OAAOY,WAAW;gBACjCC,QAAQb,KAAKC,GAAG,KAAKF;YACvB;YACA,OAAO,IAAIe,SAASC,KAAKC,SAAS,CAACR,OAAO;gBACxCS,SAAS;oBAAE,iBAAiB;oBAAY,gBAAgB;gBAAmB;gBAC3EP,QAAQ;YACV;QACF;IACF;AACF"}
{"version":3,"sources":["../../../src/modules/health/createHealthRoute.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\ntype CreateHealthRouteArgs = {\n /**\n * Collection to ping for a real DB round-trip. Default 'pages'. Pick any\n * collection that always exists in the project.\n */\n collection?: string\n /**\n * Optional extra checks merged into the body (e.g. a cache or queue ping).\n * Throwing marks the whole healthcheck unhealthy.\n */\n extra?: () => Promise<Record<string, unknown>>\n /** Same cached accessor the rest of the app uses. */\n getCachedPayload: () => Promise<BasePayload>\n}\n\n/**\n * A liveness/readiness route for Coolify/Docker healthchecks and uptime\n * monitors. Does a real DB round-trip (not just \"process is up\") and returns\n * 200 when reachable, 503 when not — so an orchestrator can restart or hold\n * traffic off a container whose database is down.\n *\n * // app/api/health/route.ts\n * import { createHealthRoute } from '@intecion/ipal-kit'\n * import { getCachedPayload } from '@/lib/content'\n * export const dynamic = 'force-dynamic' // never prerender/cache a healthcheck\n * export const GET = createHealthRoute({ getCachedPayload })\n *\n * Point Coolify's healthcheck at /api/health. Uses the global `Response`\n * (standard in Next route handlers) — no next/server import, peer-dep clean.\n */\nexport function createHealthRoute(args: CreateHealthRouteArgs): () => Promise<Response> {\n const { collection = 'pages', extra, getCachedPayload } = args\n\n return async () => {\n const startedAt = Date.now()\n try {\n const payload = await getCachedPayload()\n // Cheapest real round-trip: ask for at most one row, no population.\n await payload.find({\n collection: collection as never,\n depth: 0,\n limit: 1,\n pagination: false,\n })\n\n const extraData = extra ? await extra() : {}\n const body = {\n db: 'up',\n status: 'ok',\n timestamp: new Date().toISOString(),\n tookMs: Date.now() - startedAt,\n ...extraData,\n }\n return new Response(JSON.stringify(body), {\n headers: { 'cache-control': 'no-store', 'content-type': 'application/json' },\n status: 200,\n })\n } catch (err) {\n // Log the real error for ops; keep the PUBLIC body generic — a 503 with\n // `db: 'down'` is all an orchestrator needs, and raw DB error text (host,\n // credentials-in-URL, driver internals) must not leak on a public route.\n console.warn('[ipal] createHealthRoute: database unreachable:', err)\n const body = {\n db: 'down',\n status: 'error',\n timestamp: new Date().toISOString(),\n tookMs: Date.now() - startedAt,\n }\n return new Response(JSON.stringify(body), {\n headers: { 'cache-control': 'no-store', 'content-type': 'application/json' },\n status: 503,\n })\n }\n }\n}\n"],"names":["createHealthRoute","args","collection","extra","getCachedPayload","startedAt","Date","now","payload","find","depth","limit","pagination","extraData","body","db","status","timestamp","toISOString","tookMs","Response","JSON","stringify","headers","err","console","warn"],"mappings":"AAiBA;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASA,kBAAkBC,IAA2B;IAC3D,MAAM,EAAEC,aAAa,OAAO,EAAEC,KAAK,EAAEC,gBAAgB,EAAE,GAAGH;IAE1D,OAAO;QACL,MAAMI,YAAYC,KAAKC,GAAG;QAC1B,IAAI;YACF,MAAMC,UAAU,MAAMJ;YACtB,oEAAoE;YACpE,MAAMI,QAAQC,IAAI,CAAC;gBACjBP,YAAYA;gBACZQ,OAAO;gBACPC,OAAO;gBACPC,YAAY;YACd;YAEA,MAAMC,YAAYV,QAAQ,MAAMA,UAAU,CAAC;YAC3C,MAAMW,OAAO;gBACXC,IAAI;gBACJC,QAAQ;gBACRC,WAAW,IAAIX,OAAOY,WAAW;gBACjCC,QAAQb,KAAKC,GAAG,KAAKF;gBACrB,GAAGQ,SAAS;YACd;YACA,OAAO,IAAIO,SAASC,KAAKC,SAAS,CAACR,OAAO;gBACxCS,SAAS;oBAAE,iBAAiB;oBAAY,gBAAgB;gBAAmB;gBAC3EP,QAAQ;YACV;QACF,EAAE,OAAOQ,KAAK;YACZ,wEAAwE;YACxE,0EAA0E;YAC1E,yEAAyE;YACzEC,QAAQC,IAAI,CAAC,mDAAmDF;YAChE,MAAMV,OAAO;gBACXC,IAAI;gBACJC,QAAQ;gBACRC,WAAW,IAAIX,OAAOY,WAAW;gBACjCC,QAAQb,KAAKC,GAAG,KAAKF;YACvB;YACA,OAAO,IAAIe,SAASC,KAAKC,SAAS,CAACR,OAAO;gBACxCS,SAAS;oBAAE,iBAAiB;oBAAY,gBAAgB;gBAAmB;gBAC3EP,QAAQ;YACV;QACF;IACF;AACF"}
+5 -1
View File
@@ -190,7 +190,11 @@ export function createMcpRoute(args) {
}
return rpcResult(id, toolText(`Unknown tool: ${p.name}`, true));
} catch (err) {
return rpcResult(id, toolText(err instanceof Error ? err.message : 'Tool error', true));
// Log the real error server-side; return a GENERIC message to the
// (anonymous) caller so internal details — DB schema, host, stack —
// never leak over a public endpoint.
console.warn('[ipal] createMcpRoute: tool execution failed:', err);
return rpcResult(id, toolText('Tool execution failed.', true));
}
}
case 'tools/list':
File diff suppressed because one or more lines are too long
+2
View File
@@ -2,12 +2,14 @@ import { ALL_SYSTEM_PAGE_ROLES } from './types.js';
/** Admin-facing labels per role. */ const ROLE_LABELS = {
cookiePolicy: 'Cookie Policy',
homepage: 'Homepage',
notFound: '404 (Not Found)',
privacyPolicy: 'Privacy Policy',
termsOfService: 'Terms of Service'
};
/** Admin descriptions per role. */ const ROLE_DESCRIPTIONS = {
cookiePolicy: 'Page linked from the cookie consent banner.',
homepage: 'Page served at the locale root (e.g. /pl, /en).',
notFound: 'Page shown for unknown URLs (404). Pick a dedicated "Not found" page, or reuse the homepage. If left empty, the project falls back to its built-in not-found view.',
privacyPolicy: 'Page linked as the privacy policy.',
termsOfService: 'Page linked as the terms of service / site regulations.'
};
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/pages/systemPagesFields.ts"],"sourcesContent":["import type { Field, RelationshipField } from 'payload'\n\nimport type { PagesOption, SystemPageRole } from './types.js'\n\nimport { ALL_SYSTEM_PAGE_ROLES } from './types.js'\n\n/** Admin-facing labels per role. */\nconst ROLE_LABELS: Record<SystemPageRole, string> = {\n cookiePolicy: 'Cookie Policy',\n homepage: 'Homepage',\n privacyPolicy: 'Privacy Policy',\n termsOfService: 'Terms of Service',\n}\n\n/** Admin descriptions per role. */\nconst ROLE_DESCRIPTIONS: Record<SystemPageRole, string> = {\n cookiePolicy: 'Page linked from the cookie consent banner.',\n homepage: 'Page served at the locale root (e.g. /pl, /en).',\n privacyPolicy: 'Page linked as the privacy policy.',\n termsOfService: 'Page linked as the terms of service / site regulations.',\n}\n\n/**\n * Builds one relationship field per configured system-page role.\n *\n * Each field points at the client's Pages collection (via the provided slug)\n * and holds a single document reference. The referenced document's slug is\n * localized, so the same assignment resolves to /pl/strona-glowna and\n * /en/home at runtime — role assignment is locale-agnostic, path resolution\n * is locale-aware (see getSystemPagePath).\n */\nexport function buildSystemPagesFields(pages: PagesOption): Field[] {\n const roles = pages.roles?.length ? pages.roles : [...ALL_SYSTEM_PAGE_ROLES]\n\n return roles.map((role): RelationshipField => ({\n name: role,\n type: 'relationship',\n admin: {\n description: ROLE_DESCRIPTIONS[role],\n },\n label: ROLE_LABELS[role],\n maxDepth: 1,\n relationTo: pages.slug,\n }))\n}\n"],"names":["ALL_SYSTEM_PAGE_ROLES","ROLE_LABELS","cookiePolicy","homepage","privacyPolicy","termsOfService","ROLE_DESCRIPTIONS","buildSystemPagesFields","pages","roles","length","map","role","name","type","admin","description","label","maxDepth","relationTo","slug"],"mappings":"AAIA,SAASA,qBAAqB,QAAQ,aAAY;AAElD,kCAAkC,GAClC,MAAMC,cAA8C;IAClDC,cAAc;IACdC,UAAU;IACVC,eAAe;IACfC,gBAAgB;AAClB;AAEA,iCAAiC,GACjC,MAAMC,oBAAoD;IACxDJ,cAAc;IACdC,UAAU;IACVC,eAAe;IACfC,gBAAgB;AAClB;AAEA;;;;;;;;CAQC,GACD,OAAO,SAASE,uBAAuBC,KAAkB;IACvD,MAAMC,QAAQD,MAAMC,KAAK,EAAEC,SAASF,MAAMC,KAAK,GAAG;WAAIT;KAAsB;IAE5E,OAAOS,MAAME,GAAG,CAAC,CAACC,OAA6B,CAAA;YAC7CC,MAAMD;YACNE,MAAM;YACNC,OAAO;gBACLC,aAAaV,iBAAiB,CAACM,KAAK;YACtC;YACAK,OAAOhB,WAAW,CAACW,KAAK;YACxBM,UAAU;YACVC,YAAYX,MAAMY,IAAI;QACxB,CAAA;AACF"}
{"version":3,"sources":["../../../src/modules/pages/systemPagesFields.ts"],"sourcesContent":["import type { Field, RelationshipField } from 'payload'\n\nimport type { PagesOption, SystemPageRole } from './types.js'\n\nimport { ALL_SYSTEM_PAGE_ROLES } from './types.js'\n\n/** Admin-facing labels per role. */\nconst ROLE_LABELS: Record<SystemPageRole, string> = {\n cookiePolicy: 'Cookie Policy',\n homepage: 'Homepage',\n notFound: '404 (Not Found)',\n privacyPolicy: 'Privacy Policy',\n termsOfService: 'Terms of Service',\n}\n\n/** Admin descriptions per role. */\nconst ROLE_DESCRIPTIONS: Record<SystemPageRole, string> = {\n cookiePolicy: 'Page linked from the cookie consent banner.',\n homepage: 'Page served at the locale root (e.g. /pl, /en).',\n notFound:\n 'Page shown for unknown URLs (404). Pick a dedicated \"Not found\" page, or reuse the homepage. If left empty, the project falls back to its built-in not-found view.',\n privacyPolicy: 'Page linked as the privacy policy.',\n termsOfService: 'Page linked as the terms of service / site regulations.',\n}\n\n/**\n * Builds one relationship field per configured system-page role.\n *\n * Each field points at the client's Pages collection (via the provided slug)\n * and holds a single document reference. The referenced document's slug is\n * localized, so the same assignment resolves to /pl/strona-glowna and\n * /en/home at runtime — role assignment is locale-agnostic, path resolution\n * is locale-aware (see getSystemPagePath).\n */\nexport function buildSystemPagesFields(pages: PagesOption): Field[] {\n const roles = pages.roles?.length ? pages.roles : [...ALL_SYSTEM_PAGE_ROLES]\n\n return roles.map((role): RelationshipField => ({\n name: role,\n type: 'relationship',\n admin: {\n description: ROLE_DESCRIPTIONS[role],\n },\n label: ROLE_LABELS[role],\n maxDepth: 1,\n relationTo: pages.slug,\n }))\n}\n"],"names":["ALL_SYSTEM_PAGE_ROLES","ROLE_LABELS","cookiePolicy","homepage","notFound","privacyPolicy","termsOfService","ROLE_DESCRIPTIONS","buildSystemPagesFields","pages","roles","length","map","role","name","type","admin","description","label","maxDepth","relationTo","slug"],"mappings":"AAIA,SAASA,qBAAqB,QAAQ,aAAY;AAElD,kCAAkC,GAClC,MAAMC,cAA8C;IAClDC,cAAc;IACdC,UAAU;IACVC,UAAU;IACVC,eAAe;IACfC,gBAAgB;AAClB;AAEA,iCAAiC,GACjC,MAAMC,oBAAoD;IACxDL,cAAc;IACdC,UAAU;IACVC,UACE;IACFC,eAAe;IACfC,gBAAgB;AAClB;AAEA;;;;;;;;CAQC,GACD,OAAO,SAASE,uBAAuBC,KAAkB;IACvD,MAAMC,QAAQD,MAAMC,KAAK,EAAEC,SAASF,MAAMC,KAAK,GAAG;WAAIV;KAAsB;IAE5E,OAAOU,MAAME,GAAG,CAAC,CAACC,OAA6B,CAAA;YAC7CC,MAAMD;YACNE,MAAM;YACNC,OAAO;gBACLC,aAAaV,iBAAiB,CAACM,KAAK;YACtC;YACAK,OAAOjB,WAAW,CAACY,KAAK;YACxBM,UAAU;YACVC,YAAYX,MAAMY,IAAI;QACxB,CAAA;AACF"}
+1 -1
View File
@@ -2,7 +2,7 @@
* Built-in "system page" roles — documents from the client's Pages
* collection that the site references by function rather than by slug.
*/
export type SystemPageRole = 'cookiePolicy' | 'homepage' | 'privacyPolicy' | 'termsOfService';
export type SystemPageRole = 'cookiePolicy' | 'homepage' | 'notFound' | 'privacyPolicy' | 'termsOfService';
/**
* All system roles in a stable order (used when no subset is configured).
*/
+1
View File
@@ -5,6 +5,7 @@
* All system roles in a stable order (used when no subset is configured).
*/ export const ALL_SYSTEM_PAGE_ROLES = [
'homepage',
'notFound',
'privacyPolicy',
'cookiePolicy',
'termsOfService'
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/pages/types.ts"],"sourcesContent":["/**\n * Built-in \"system page\" roles — documents from the client's Pages\n * collection that the site references by function rather than by slug.\n */\nexport type SystemPageRole = 'cookiePolicy' | 'homepage' | 'privacyPolicy' | 'termsOfService'\n\n/**\n * All system roles in a stable order (used when no subset is configured).\n */\nexport const ALL_SYSTEM_PAGE_ROLES: readonly SystemPageRole[] = [\n 'homepage',\n 'privacyPolicy',\n 'cookiePolicy',\n 'termsOfService',\n]\n\n/**\n * Plugin option enabling system-page assignments in SiteSettings.\n *\n * The plugin doesn't own the Pages collection — the client creates it in\n * their own project. This option hands the plugin the collection's slug so\n * it can build relationship fields pointing at it. No hardcoding: the slug\n * always comes from the client.\n */\nexport type PagesOption = {\n /**\n * Which system roles to expose as assignable fields.\n * Defaults to all roles when omitted.\n */\n roles?: SystemPageRole[]\n /** Slug of the client's Pages collection, e.g. 'pages'. */\n slug: string\n}\n"],"names":["ALL_SYSTEM_PAGE_ROLES"],"mappings":"AAAA;;;CAGC,GAGD;;CAEC,GACD,OAAO,MAAMA,wBAAmD;IAC9D;IACA;IACA;IACA;CACD,CAAA"}
{"version":3,"sources":["../../../src/modules/pages/types.ts"],"sourcesContent":["/**\n * Built-in \"system page\" roles — documents from the client's Pages\n * collection that the site references by function rather than by slug.\n */\nexport type SystemPageRole =\n 'cookiePolicy' | 'homepage' | 'notFound' | 'privacyPolicy' | 'termsOfService'\n\n/**\n * All system roles in a stable order (used when no subset is configured).\n */\nexport const ALL_SYSTEM_PAGE_ROLES: readonly SystemPageRole[] = [\n 'homepage',\n 'notFound',\n 'privacyPolicy',\n 'cookiePolicy',\n 'termsOfService',\n]\n\n/**\n * Plugin option enabling system-page assignments in SiteSettings.\n *\n * The plugin doesn't own the Pages collection — the client creates it in\n * their own project. This option hands the plugin the collection's slug so\n * it can build relationship fields pointing at it. No hardcoding: the slug\n * always comes from the client.\n */\nexport type PagesOption = {\n /**\n * Which system roles to expose as assignable fields.\n * Defaults to all roles when omitted.\n */\n roles?: SystemPageRole[]\n /** Slug of the client's Pages collection, e.g. 'pages'. */\n slug: string\n}\n"],"names":["ALL_SYSTEM_PAGE_ROLES"],"mappings":"AAAA;;;CAGC,GAID;;CAEC,GACD,OAAO,MAAMA,wBAAmD;IAC9D;IACA;IACA;IACA;IACA;CACD,CAAA"}
-264
View File
@@ -1,264 +0,0 @@
# Playbook wdrożenia — ipal-kit
Sztywna procedura dla pracownika albo AI (Antigravity). Mówi CO robić, W JAKIEJ
KOLEJNOŚCI, i CZYM SIĘ KIEROWAĆ. Zasady są twarde, przykłady realne — wzięte z
faktycznych błędów, które się zdarzyły. Odstępstwa tylko za świadomą decyzją.
Powiązane: [standardy-kodu.md](./standardy-kodu.md) (dobre praktyki senior),
[publishing.md](./publishing.md) (cykl publikacji), [getting-started.md](./getting-started.md)
(nowy projekt), ../antigravity_zasady_agent.md (zasady dla AI).
---
## ZŁOTE ZASADY (łam tylko świadomie)
1. **Nic na sztywno.** Tekst, obraz, link, dane firmy → panel/baza, nie kod.
2. **Logika w pluginie, projekt podłącza.** Jeśli piszesz w projekcie coś, co
robi już plugin — zatrzymaj się, użyj pluginu.
3. **Next 16 = proxy.ts.** NIGDY middleware.ts. Jeśli istnieje — usuń.
4. **Weryfikuj każdy etap grepem.** Nie zakładaj, że zadziałało. Sprawdź.
5. **Napraw u źródła, nie łataj.** Bez `as any`, `@ts-ignore`, kopii logiki.
6. **Zmiana w pluginie nie działa, dopóki nie: build → publish → wciągnięcie.**
7. **Zmieniłeś API → zaktualizuj docs w tym samym commicie.** Docs jadą w
pakiecie; rozjazd kod↔docs = agent dostaje złą mapę.
---
## CZĘŚĆ A — ŁAŃCUCH ZMIANY W PLUGINIE (najważniejsze)
Najczęstsze źródło frustracji tej sesji: „zmieniłem kod, a nie działa". Prawie
zawsze przyczyna: **przerwany łańcuch**. Zmiana w pluginie przechodzi przez
PIĘĆ etapów. Pominięcie któregokolwiek = stara wersja w projekcie.
```
źródła (src) → build (dist) → publish (rejestr) → wciągnięcie (node_modules) → restart
```
### Sztywna procedura zmiany w pluginie
```bash
cd ~/payload-cms/ipal-kit
# 1. ŹRÓDŁA — nanieś zmianę, ZWERYFIKUJ że jest
grep -c "<symbol-zmiany>" src/<ścieżka> # MUSI być >0
# 1b. DOCS — jeśli zmiana dotyka API/zachowania, ZAKTUALIZUJ docs/
# (nowa funkcja, zmiana sygnatury, nowe pole panelu, nowy adapter...).
# Docs jadą w pakiecie (files: dist, docs) — nieaktualne docs = agent
# dostaje złą mapę. Kod i docs publikuj RAZEM.
# 2. BUILD — zbuduj, ZWERYFIKUJ że dist ma zmianę
pnpm build
grep -c "<symbol-zmiany>" dist/<ścieżka> # MUSI być >0
# 3. COMMIT (PRZED version — inaczej "working directory not clean")
git add -A && git commit -m "opis"
# 4. VERSION + PUBLISH
npm version patch # czyste repo wymagane
npm publish
# 5. PUSH
git push && git push --tags
# 6. PROJEKT — wciągnij, ZWERYFIKUJ że node_modules ma zmianę
cd ~/<projekt>
pnpm add @intecion/ipal-kit@<nowa-wersja>
grep -c "<symbol-zmiany>" node_modules/@intecion/ipal-kit/dist/<ścieżka> # MUSI być >0
# 7. RESTART dev (Payload buduje adaptery/config przy starcie!)
pnpm dev
```
### TRZY punkty kontrolne grep (nie pomijaj żadnego)
| Etap | Grep | Jeśli 0 |
|---|---|---|
| po edycji | `src/...` | zmiana nie zapisana / zły plik |
| po build | `dist/...` | build nie złapał / błąd typów |
| po pnpm add | `node_modules/...` | projekt ma starą wersję |
**Realny przykład (z tej sesji):** `buildSecurityHeaders is not a function`.
Przyczyna: moduł istniał w `src`, ale NIE był wyeksportowany w `src/index.ts`
→ `dist` go nie miał → import w projekcie = undefined. Grep `dist/index.js`
pokazał 0. Naprawa: dodać eksport, przejść łańcuch od nowa.
### Pułapki kolejności (realne błędy sesji)
- **`npm version` przed commitem** → "Git working directory not clean". ZAWSZE
commit przed version.
- **`npm publish` bez `pnpm build`** → publikujesz STARY dist. ZAWSZE build przed
publish, grep dist po buildzie.
- **`pnpm add` przy działającym dev** → proces ma stary adapter w pamięci.
Payload czyta email/config przy starcie. ZAWSZE restart po wciągnięciu.
- **Publikacja bez aktualizacji docs** → agent (Antigravity) po `pnpm add`
czyta `node_modules/@intecion/ipal-kit/docs/` z NIEAKTUALNĄ mapą. Jeśli
zmieniłeś API — docs w tym samym commicie.
---
## CZĘŚĆ B — GREP JAKO NARZĘDZIE (jak weryfikować dobrze)
Grep był w tej sesji głównym narzędziem diagnozy. Ale trzeba go używać mądrze.
### Reguła: grepuj TOKENY, nie całe frazy z kolejnością
**Realny błąd:** grep `"env.sender, name: senderName"` dał 0, choć kod był OK —
bo plik miał odwróconą kolejność kluczy (`name: senderName, address: env.sender`).
Obiekt JS ignoruje kolejność, ale grep nie.
```bash
# ŹLE — zależny od kolejności/formatowania:
grep -c "env.sender, name: senderName" plik.ts # 0 mimo poprawnego kodu
# DOBRZE — pojedynczy token, odporny:
grep -c "senderName" plik.ts # 3 ✓
```
Grepuj **nazwę symbolu** (funkcja, zmienna, eksport), nie całą linię z interpunkcją.
---
## CZĘŚĆ C — DIAGNOSTYKA „KOD DOBRY, ZACHOWANIE ZŁE"
Gdy grep potwierdza kod, wersja nowa, a zachowanie stare — przejdź listę:
1. **Dev nie zrestartowany?** Payload buduje adaptery/config przy starcie.
Ctrl+C + `pnpm dev`. (Najczęstsza przyczyna.)
2. **Zmiana zapisana w panelu?** Endpointy czytają z BAZY, nie z pola na ekranie.
Kliknij Save.
3. **Zdublowana zależność?** `@payloadcms/ui` w node_modules pluginu = dwie
instancje = hooki bez kontekstu. Sprawdź:
`ls node_modules/@intecion/ipal-kit/node_modules/@payloadcms/ui`
Jest? → peerDependency problem (patrz Część D).
4. **Cache klienta?** Np. klient pocztowy pokazuje zapamiętaną nazwę nadawcy
mimo poprawnych nagłówków. Sprawdź surowe źródło (View Source), wyślij na
inny adres.
5. **Import map nieaktualny?** Custom komponenty Payload:
`npx payload generate:importmap`.
**Realny przykład:** MaskedField rzucał "Cannot destructure property 'config'".
Kod OK. Przyczyna: dublet `@payloadcms/ui` (plugin miał własną kopię) →
`useField` z jednej instancji nie widział kontekstu z drugiej. Naprawa w Część D.
---
## CZĘŚĆ D — peerDependencies (dublety zależności)
**Zasada:** wszystko, co dostarcza PROJEKT, jest `peerDependency` w pluginie,
NIE `dependency`. Inaczej menedżer instaluje własną kopię dla pluginu → dublet
→ React/Payload context się rozjeżdża (dwie instancje nie widzą się nawzajem).
Peer (projekt dostarcza): `payload`, `@payloadcms/ui`, `@payloadcms/next`,
`@payloadcms/plugin-*`, `react`, `react-dom`, `next`.
**Realny błąd:** `@payloadcms/ui` był tylko w devDependencies (brak w peer) →
pnpm dołożył kopię pluginowi → MaskedField/TestEmailButton/CookieBanner
wszystkie się psuły (hooki bez kontekstu). Naprawa: dodać do peerDependencies,
opublikować, w projekcie `rm -rf node_modules/@intecion/ipal-kit && pnpm add`.
Weryfikacja braku dubletu:
```bash
ls node_modules/@intecion/ipal-kit/node_modules/@payloadcms/ui 2>/dev/null \
&& echo "DUBLET ✗" || echo "OK ✓"
```
---
## CZĘŚĆ E — NOWY PROJEKT KLIENCKI (kolejność)
Pełne szczegóły: [getting-started.md](./getting-started.md). Tu skrót kolejności.
1. **Szkielet** Payload 3 + Next 16, pnpm, Node 22
2. **`.npmrc`** — `legacy-peer-deps=true` + rejestr `@intecion`
3. **`pnpm add @intecion/ipal-kit`** + zależności peer
4. **build script z `--webpack`** (Next 16 + Payload; Turbopack konfliktuje)
5. **i18n.config.ts** — jedno źródło locale
6. **payload.config.ts** — ipalKit({...}), `email: mailAdapter()`
7. **Kolekcje/globale** — wszystko localized/upload (nic na sztywno)
8. **lib/content.ts + lib/payload.ts** — helpery, jedno źródło getCachedPayload
9. **proxy.ts** (NIE middleware.ts) — routing locale, obsługa roota
10. **Bloki** — dane przez enhanceProps, nie import lib (cykl)
11. **buildSlugField** zamiast ręcznego slug; **buildNoindexField** na pole noindex
12. **getLocalizedSlugs** zamiast zaszytej mapy ścieżek
13. **buildSecurityHeaders** w next.config
14. **instrumentation.ts** — `assertEnv(ipalEnvRules({...}))` (walidacja ENV na starcie)
15. **Route'y z bazą** (`manifest.ts`, `llms.txt/route.ts`, `sitemap.xml/route.ts`) — `export const dynamic = 'force-dynamic'`
16. **resolveRedirect** w catch-all (+ `trackSlugHistoryHook` i pole `slugHistory` w kolekcjach)
17. **Formularz** — `useContactForm`/`useForm` (logika z pluginu, markup w projekcie)
18. **Test:** root `/` przekierowuje, formularz wysyła, panel działa, zmiana slug → 308 na nowy URL
---
## CZĘŚĆ F — EMAIL (SMTP vs Graph)
Pełne szczegóły: [email.md](./email.md). Decyzja transportu:
- **Klient na M365/Exchange** → Graph (SMTP AUTH na M365 często wyłączony)
- **Klient z własnym SMTP / Gmail** → SMTP
- **Przełącznik:** panel → Site Integrations → SMTP → Email Transport
- **Dyspozytor:** `email: mailAdapter()` czyta wybór przy każdej wysyłce
### Graph — checklist wdrożenia (Wasza strona, jednorazowo)
1. Azure: App registration → tenantId, clientId, clientSecret
2. Azure: Mail.Send APPLICATION permission + **Grant admin consent**
3. `.env` projektu: GRAPH_TENANT_ID, GRAPH_CLIENT_ID, GRAPH_CLIENT_SECRET, GRAPH_SENDER
4. Panel: From Name (nazwa nadawcy), From Address (→ reply-to)
### Realne pułapki Graph (wszystkie zdarzyły się w sesji)
| Błąd | Przyczyna | Naprawa |
|---|---|---|
| `ErrorSendAsDenied` | `from` ≠ sender | from.address = GRAPH_SENDER, klient w replyTo |
| nazwa „Noreply" mimo panelu | Exchange nadpisuje / cache klienta | display name skrzynki / sprawdź nagłówki |
| `Insufficient privileges` | brak admin consent | Grant admin consent w Azure |
| `AADSTS1002012` | zły scope | scope = `.../.default`, nie Mail.Send |
**Zasada from/replyTo:** `from.address` ZAWSZE = GRAPH_SENDER (wspólna skrzynka,
zero Send-As). Nazwa (`from.name`) z panelu — różna per projekt. Adres klienta
→ replyTo (odpowiedzi trafiają do klienta).
---
## CZĘŚĆ G — CO NALEŻY DO PLUGINU, A CO DO PROJEKTU
Powtarzalne pytanie. Reguła: **jeśli zależy od danych/domen konkretnego projektu
→ projekt. Jeśli identyczne wszędzie → plugin.**
| Rzecz | Gdzie | Dlaczego |
|---|---|---|
| i18n, SEO meta, forms, consent, blog | plugin | uniwersalne |
| Powiadomienia (teksty wyników) | plugin | uniwersalne, per język z panelu |
| Zgoda RODO (enforcement) | plugin | uniwersalne, server-side |
| Nagłówki bezpieczeństwa (HSTS...) | plugin | identyczne wszędzie |
| Email (SMTP + Graph) | plugin | uniwersalne, konfiguracja z panelu/env |
| **CSP** | **projekt** | zależy od domen projektu |
| **schema.org / JSON-LD** | **projekt** | zależy od danych firmy |
| **Breadcrumbs** | **projekt** | render z danych routingu projektu |
| **Dane rejestrowe firmy** | **projekt** | różne per typ firmy |
---
## CZĘŚĆ H — CHECKLIST PRZED „GOTOWE"
Nie mów „działa", dopóki:
- [ ] `pnpm build --webpack` przechodzi lokalnie (nie tylko dev)
- [ ] root `/` przekierowuje na locale (bez middleware.ts)
- [ ] formularz wysyła (test przez panel: Send test)
- [ ] panel: wszystkie teksty/obrazy edytowalne (nic na sztywno)
- [ ] brak dubletu @payloadcms/ui (Część D)
- [ ] grep potwierdza wersję pluginu w node_modules
- [ ] sekrety w .env (nie w repo), maskowane w panelu
- [ ] brak plików middleware.ts, brak zaszytej mapy slugów
- [ ] strona 404 (not-found.tsx) — edytowalna, per język, link powrotu
- [ ] app/robots.ts + app/sitemap.ts wystawione (Google widzi strony)
- [ ] `export const dynamic = 'force-dynamic'` na manifest.ts, llms.txt, sitemap.xml (build bez bazy nie wywala)
- [ ] `instrumentation.ts` z `assertEnv(ipalEnvRules({...}))` — build/boot łapie brak ENV
- [ ] zmiana slug → stary URL robi 308 na nowy (resolveRedirect + slugHistory)
- [ ] obrazki w blokach: po zapisie w jednym języku są też w pozostałych (buildCrossLocaleFieldSync)
- [ ] favicon PNG (nie SVG) w buildIconsMetadata; structured data (Organization, WebSite)
- [ ] formularz: logika z useForm/useContactForm (NIE skopiowana hydraulika), pola/teksty z buildera
- [ ] compliance: polityki, baner cookies, zgoda RODO w formularzach
(patrz [wymagania-prawne.md](./wymagania-prawne.md))
+35 -148
View File
@@ -1,152 +1,39 @@
# IPAL — Dokumentacja modułów
# Dokumentacja @intecion/ipal-kit
> **Zaczynasz wdrożenie?** Przeczytaj najpierw [WDROZENIE-PLAYBOOK.md](./WDROZENIE-PLAYBOOK.md) — sztywna procedura, kolejność, realne przykłady błędów.
| Kim jesteś | Czytaj |
|---|---|
| **Agent AI** pracujący w projekcie | [AGENT.md](./agent/AGENT.md) — reguły, struktura, budowa sekcji, kontrole przed „gotowe” |
| **Agent AI — skille** | [agent/skills/](./agent/skills) — 7 skilli `ipal-*` dla Antigravity/Claude Code (kopiowane do projektu: `pnpm ipal:skills`, AGENT.md §14) |
| **Programista** | [PROGRAMISTA.md](./dev/PROGRAMISTA.md) — instalacja, nowy projekt, env, wdrożenie, aktualizacja, publikacja pluginu, Gitea |
| **Osoba prowadząca agenta AI** | [vibe.md](./dev/vibe.md) — gotowe polecenia do wklejenia, krok po kroku, moduł po module |
**Instalacja pakietu** (token Gitea, rejestr vs repozytorium) → główny
[README](../README.md).
**Nowy projekt krok po kroku** → [getting-started.md](./getting-started.md).
Szczegóły API — jeden plik na moduł:
Ta dokumentacja opisuje **konfigurację i moduły** pluginu — zakłada, że
`@intecion/ipal-kit` jest już zainstalowany.
| Moduł | Plik |
|---|---|
| Role i dostęp do panelu | [access.md](./access.md) |
| Widget dostępności (opcjonalny) | [accessibility.md](./accessibility.md) |
| GA4, GTM, Meta Pixel, Clarity, LinkedIn, TikTok, `defer` | [analytics.md](./analytics.md) |
| Bloki, RenderBlocks, enhanceProps | [blocks.md](./blocks.md) |
| Zgoda cookies, baner | [consent.md](./consent.md) |
| Routing, archiwa, redirecty, Markdown, wyszukiwarka | [content.md](./content.md) |
| Email SMTP / Graph | [email.md](./email.md) |
| Walidacja env | [env.md](./env.md) |
| Formularze, useForm, honeypot | [forms.md](./forms.md) |
| Hooki | [hooks.md](./hooks.md) |
| i18n, proxy, przełącznik języka | [i18n.md](./i18n.md) |
| Serwer MCP strony | [mcp.md](./mcp.md) |
| Komunikaty formularzy | [notifications.md](./notifications.md) |
| Strony systemowe, 404, generateStaticParams | [pages.md](./pages.md) |
| Helpery Payload | [payload-helpers.md](./payload-helpers.md) |
| Rich text | [richtext.md](./richtext.md) |
| Nagłówki, CSP, 2FA | [security.md](./security.md) |
| SEO, metadata, sitemap, JSON-LD, llms.txt | [seo.md](./seo.md) |
| Auto-slug | [slug.md](./slug.md) |
| Media, R2 | [storage.md](./storage.md) |
| Turnstile | [turnstile.md](./turnstile.md) |
| White-label panelu | [white-label.md](./white-label.md) |
IPAL (Intecion Payload Advanced Library) to plugin do Payload CMS 3, który
dostarcza logikę i konfigurację; projekt klienta zawiera tylko komponenty
wizualne i podłączenia do Next.js.
## Zasada
- **Plugin** = logika, helpery, konfiguracja, globale.
- **Klient (projekt)** = komponenty (wygląd), pliki-podłączenia Next.js
(jednolinijkowe re-eksporty), konfiguracja front.
## Konfiguracja i wpięcie
### Wymagane zależności
Projekt klienta musi mieć (poza payloadem):
```json
"dependencies": {
"@payloadcms/plugin-seo": "3.84.1",
"@payloadcms/plugin-form-builder": "3.84.1",
"nodemailer": "^8.0.1",
"lucide-react": "^0.400.0",
"slugify": "^1.6.6",
"server-only": "^0.0.1"
}
```
Wersje `@payloadcms/*` **muszą** być identyczne z wersją `payload`. Wymuś
spójność przez `pnpm.overrides` (patrz niżej), inaczej Payload odrzuci wpięcie
pluginów (pusty tab SEO, brak kolekcji Forms) albo crashuje.
```json
"pnpm": {
"overrides": {
"payload": "3.84.1",
"@payloadcms/ui": "3.84.1",
"@payloadcms/next": "3.84.1",
"@payloadcms/db-sqlite": "3.84.1",
"@payloadcms/richtext-lexical": "3.84.1",
"@payloadcms/plugin-seo": "3.84.1",
"@payloadcms/plugin-form-builder": "3.84.1"
}
}
```
### Po wpięciu — wygeneruj importMap
Plugin dostarcza komponenty admina (pola SEO). Po dodaniu uruchom:
```bash
pnpm payload generate:importmap
```
Bez tego pola SEO nie wyrenderują się (błąd `PayloadComponent not found in
importMap`).
```ts
// payload.config.ts
import { ipalKit } from '@intecion/ipal-kit'
export default buildConfig({
// ...
plugins: [
ipalKit({
i18n: {
defaultLocale: 'pl',
locales: [
{ code: 'pl', label: 'Polski' },
{ code: 'en', label: 'English' },
],
},
access: { authCollection: 'users' },
pages: { slug: 'pages' },
seo: { collections: ['pages', 'posts'] },
forms: { redirectRelationships: ['pages'] },
}),
],
})
```
## Entry pointy pakietu
| Import | Zawiera | Kontekst |
|---|---|---|
| `@intecion/ipal-kit` | logika server-safe, plugin, helpery | server / config |
| `@intecion/ipal-kit/server` | runtime server-only (sendEmail, verifyTurnstile, submitForm) | Server Actions / route handlers |
| `@intecion/ipal-kit/client` | komponenty client (consent, Turnstile, Analytics) | `'use client'` |
| `@intecion/ipal-kit/rsc` | RenderBlocks (RSC) | server component |
| `@intecion/ipal-kit/next/middleware` | locale middleware (import bez zmian) | `proxy.ts` (Next 16; dawniej `middleware.ts`) |
## Moduły
| Moduł | Opis | Dok |
|---|---|---|
| i18n | Lokalizacja, negocjacja locale, ścieżki URL, strona jednojęzyczna | [i18n.md](./i18n.md) |
| hooks | Hooki: revalidate ISR, slug history, cross-locale sync, noindex, ochrona | [hooks.md](./hooks.md) |
| env | Walidacja zmiennych środowiskowych na starcie (assertEnv, fail fast) | [env.md](./env.md) |
| mcp | Read-only serwer MCP strony — Claude/agent podłącza się i odpytuje treść | [mcp.md](./mcp.md) |
| kolekcje-katalog | Jakie kolekcje budować, kiedy, jak wpiąć (minimum nie maksimum) | [kolekcje-katalog.md](./kolekcje-katalog.md) |
| fundamenty-projektu | Struktura katalogów, nazewnictwo, konwencje | [fundamenty-projektu.md](./fundamenty-projektu.md) |
| deployment | Zmienne .env, ISR/SSG, force-dynamic, Coolify/Docker | [deployment.md](./deployment.md) |
| pages | System pages (homepage/privacy/cookies) → ścieżki | [pages.md](./pages.md) |
| access | Role admin > editor > user, kontrola dostępu | [access.md](./access.md) |
| payload-helpers | getSiteSettings / getSiteIntegrations | [payload-helpers.md](./payload-helpers.md) |
| seo | Metadata, hreflang, auto-fill, plugin-seo | [seo.md](./seo.md) |
| migration | Migracja projektu na nową wersję | [migration.md](./migration.md) |
| AGENTS-TEMPLATE | Szablon agents.md do roota nowego projektu | [AGENTS-TEMPLATE.md](./AGENTS-TEMPLATE.md) |
| wymagania-prawne | **Polityki, regulaminy, baner cookies, RODO (compliance)** | [wymagania-prawne.md](./wymagania-prawne.md) |
| standardy-kodu | **Dobre praktyki senior: typy, architektura, antywzorce** | [standardy-kodu.md](./standardy-kodu.md) |
| architektura-tresci | **Jak budować, żeby klient wszystko edytował** (filozofia CMS) | [architektura-tresci.md](./architektura-tresci.md) |
| blocks | RenderBlocks — silnik renderowania bloków | [blocks.md](./blocks.md) |
| accessibility | Widget dostępności (WCAG): tekst, kontrast, szarość, animacje | [accessibility.md](./accessibility.md) |
| consent | Banner cookies GDPR, Google Consent Mode | [consent.md](./consent.md) |
| turnstile | Cloudflare Turnstile (widget + verify) | [turnstile.md](./turnstile.md) |
| email | Wysyłka: SMTP z panelu lub Microsoft Graph (M365) | [email.md](./email.md) |
| forms | Form-builder + submitForm + useForm/useContactForm (logika klienta) | [forms.md](./forms.md) |
| analytics | GA4 / GTM spięte z Consent Mode, pushDataLayer | [analytics.md](./analytics.md) |
| gtm-meta-pixel | Konfiguracja GTM + Meta Pixel krok po kroku (pod ten stack) | [gtm-meta-pixel.md](./gtm-meta-pixel.md) |
| slug | Auto-slug z tytułu, per locale | [slug.md](./slug.md) |
| notifications | Teksty wyników akcji (formularz) per język | [notifications.md](./notifications.md) |
| storage | Media na Cloudflare R2 (offload z .env) | [storage.md](./storage.md) |
| security | Nagłówki bezpieczeństwa HTTP (HSTS, X-Frame...) | [security.md](./security.md) |
| white-label | Branding panelu admina (logo + nazwa z SiteSettings) | [white-label.md](./white-label.md) |
| content | Blog/archiwa: kolekcje pod stroną-archiwum, listing, paginacja, redirecty (resolveRedirect) | [content.md](./content.md) |
Nowy projekt krok po kroku: [getting-started.md](./getting-started.md)
Referencja wdrożenia frontu: [getting-started.md](./getting-started.md)
Wydawanie nowych wersji wtyczki: [publishing.md](./publishing.md)
Jak komendy łączą się z Gitea (dla instalujących): [gitea-commands.md](./gitea-commands.md)
Working with a project repo on Gitea (clone/pull/push): [gitea-workflow.md](./gitea-workflow.md) · [🇵🇱 PL](./gitea-workflow.pl.md)
## Zasady dla wszystkich modułów
1. **Helpery przyjmują `payload` jako argument** — plugin nigdy nie woła
`getPayload` sam.
2. **Sekrety w panelu** — SMTP, Turnstile secret, R2 w SiteIntegrations
(admin-only). Odczyt server-side przez Local API.
3. **Client/server split** — kod z sekretami ma `server-only`; komponenty
client w `@intecion/ipal-kit/client`.
4. **Generyki na typy klienta** — helpery przyjmują `<T>` (np. wygenerowany
`SiteSetting`), bo plugin nie zna typów projektu.
Zasada utrzymania: zmiana API modułu → aktualizacja jego pliku w tym samym
commicie. Nowe reguły pracy → AGENT.md. Nowy krok procesu → PROGRAMISTA.md. Nowy etap budowy → vibe.md.
Nie dodawaj kolejnych plików ogólnych.
+1 -1
View File
@@ -190,4 +190,4 @@ to **opcja, nie obowiązek** — dodawaj gdy klient wymaga, nie z automatu.
Gdy dodajesz: widget sam w sobie NIE czyni strony w pełni dostępną — to pomoc dla
użytkownika. Pełna dostępność to też semantyczny HTML, alt teksty, nawigacja
klawiaturą, kontrast bazowy. Widget uzupełnia, nie zastępuje. Nie sprzedawaj
klientowi „mamy widget = jesteśmy zgodni z WCAG". Patrz wymagania-prawne.md.
klientowi „mamy widget = jesteśmy zgodni z WCAG". Patrz PROGRAMISTA.md §5.
-276
View File
@@ -1,276 +0,0 @@
<!--
SZABLON agents.md dla projektów na @intecion/ipal-kit.
UŻYCIE: skopiuj ten plik do ROOTA nowego projektu jako `agents.md` (albo
AGENTS.md). Agenci (Antigravity, Claude Code, Cursor) czytają go automatycznie.
NIE zostawiaj go w docs/ — musi być w katalogu głównym projektu.
Dostosuj tylko to, co oznaczone <!-- DOSTOSUJ -->; reszta to uniwersalne
reguły ekosystemu ipal-kit (nie zmieniaj bez powodu).
Źródło prawdy dla szczegółów: node_modules/@intecion/ipal-kit/docs/
-->
# Zasady i Standardy Projektowe — Payload CMS 3 + Next 16 + @intecion/ipal-kit
> **Projekt:** <!-- DOSTOSUJ: nazwa klienta, domena, rynek (PL/AU/US), branża -->
Niniejszy dokument stanowi bezwzględnie obowiązujące reguły pracy dla agenta (Antigravity) w niniejszym projekcie. Został sporządzony na podstawie dokumentacji w `/docs`. Każda zasada musi być ściśle przestrzegana, bez wyjątków i bez stosowania obejść/prowizorek.
---
## 1. ZASADA NADRZĘDNA: ipal-kit JEST OBOWIĄZKOWY
1. **Obowiązkowe użycie pluginu:**
- Każda funkcja dostarczana przez `@intecion/ipal-kit` (i18n, SEO, formularze, consent, email, slug, bezpieczeństwo, strony systemowe, storage R2, breadcrumbs, JSON-LD) **MUSI** być realizowana przez plugin.
- **NIGDY** nie twórz własnego kodu w projekcie dublującego możliwości pluginu.
2. **Sprawdzaj przed pisaniem:**
- Zanim napiszesz jakąkolwiek funkcję, helper czy komponent — sprawdź dokumentację w `node_modules/@intecion/ipal-kit/docs/` oraz definicje typów `.d.ts`. Jeśli funkcja istnieje w pluginie, **musisz** jej użyć.
3. **Gdy w pluginie czegoś brakuje:**
- **NIE** obchodź braku prowizorką ani własnym kodem w projekcie (to tworzy dług technologiczny i rozbieżności).
- **Zgłoś brak funkcji do rozbudowy pluginu**, zamiast łatać to lokalnie.
- Logika uniwersalna (przydatna w innych projektach) trafia do pluginu. W projekcie znajduje się **wyłącznie** specyfika danego klienta (jego bloki, wygląd, struktura danych).
4. **Gdy coś w pluginie nie działa:**
- **Zgłoś problem i błąd**, zamiast tworzyć ciche obejścia, prowizoryczne hooki czy hardkodowane patche.
---
## 2. KROK 0: INSTALACJA I DOSTĘP DO DOKUMENTACJI PLUGINU
1. **Utwórz `.npmrc` w katalogu projektu:**
```ini
legacy-peer-deps=true
@intecion:registry=https://git.intecion.net/api/packages/IntecionSoftware/npm/
```
*(Scoped override: tylko `@intecion/*` z Gitea, rejestr publiczny bez tokena).*
2. **Instalacja pluginu:**
```bash
pnpm add @intecion/ipal-kit
```
*(NIGDY nie instaluj z gita `git+https://...` — psuje React Client Manifest w Next).*
3. **Lokalizacja dokumentacji źródłowej:**
```bash
ls node_modules/@intecion/ipal-kit/docs/
```
Zawsze korzystaj z plików w `docs/` pluginu (`getting-started.md`, `seo.md`, `forms.md`, `email.md`, `storage.md`, `i18n.md`, `blocks.md`, `turnstile.md` itd.).
---
## 3. ABSOLUTNY ZAKAZ HARDKODOWANIA
### A. Treść i teksty:
- **ZAKAZ:** Tekst widoczny dla użytkownika wpisany w JSX, etykiety i komunikaty w kodzie, instrukcje `if (locale === 'pl')`, tablice z tekstami w kodzie.
- **WYMAGANE:** Każdy tekst pochodzi z pola `localized: true`, pobierany z panelu CMS.
- **Częsty błąd (ukryty hardkod w fallbacku):** `siteName || 'Nazwa Klienta'` lub `catch { return { name: 'Firma...' } }` to **niedopuszczalny hardkod**! Gdy brak danych z panelu/env: **pomiń pole** (np. `...(val ? { name: val } : {})`), nie wstawiaj danych klienta w fallbacku `||` ani w bloku `catch`.
### B. Obrazy i multimedia:
- **ZAKAZ:** `import logo from '@/assets/...'`, ścieżki `src="/images/..."`.
- **WYMAGANE:** Pole `type: 'upload', relationTo: 'media'`, renderowane z `media.url`. Do kolekcji `Media` obowiązkowo wepnij `normalizeFilenameHook`.
- **Preconnect:** Użyj `<MediaPreconnect />` z pluginu (czyta `R2_PUBLIC_URL` z env), nigdy sztywnego tagu `<link>` z domeną.
- **Favicon:** Użyj `buildIconsMetadata(settings.favicon)` z panelu (format PNG, nie ręczny SVG).
### C. Linki i routing:
- **ZAKAZ:** `href="/pl/kontakt"`, menu jako statyczna tablica w kodzie, oraz **sztywna mapa zlokalizowanych ścieżek** (`const localizedRoutes = {...}` — kardynalny antywzorzec).
- **WYMAGANE:** `getLocalizedSlugs` / `switchLocalePath` z bazy danych, `getSystemPagePath`, relacje `relationship -> pages` w panelu CMS.
### D. Konfiguracja i dane firmy:
- **ZAKAZ:** `locale as 'pl' | 'en'`, zaszyty slug kolekcji, dane firmy, NIP, adres, telefon w kodzie.
- **WYMAGANE:** Jedno źródło prawdy `i18n.config.ts`, `locale as never`, dane firmy z globala (np. `siteSettings` / `CompanyInfo`), infrastruktura wyłącznie w `.env`.
### E. Renderer bloków, kolekcje, formularze (częste błędy):
- **Renderer rich text:** ZAWSZE `RenderRichText` z pluginu (`@intecion/ipal-kit/rsc`, wrapper nad oficjalnym konwerterem Lexical). NIGDY własny parser Lexical (switch po node.type, flagi node.format, dangerouslySetInnerHTML, hardkod `.pl`). Styl przez `converters`. Patrz richtext.md.
- **Renderer bloków:** ZAWSZE `RenderBlocks` z pluginu + mapa `registry`. NIGDY własny `switch (block.blockType)` — to gadatliwe, bez enhanceProps, rośnie liniowo. Mapa deklaratywna, silnik z pluginu.
- **MINIMUM kolekcji, nie maksimum:** Domyślnie tylko rdzeń (pages, media, settings, navigation, footer + globale). Kolekcję treści (blog/produkty) TYLKO gdy klient JAWNIE wymaga. NIGDY nie twórz: `users` (WBUDOWANE w Payload — nie duplikuj!), `daneFirmy`/`settings` jako kolekcje (to GLOBALE), FAQ/hero/features jako kolekcje (to BLOKI). Test przed stworzeniem: lista rekordów + własny URL + jawna potrzeba + Payload nie ma wbudowanego. Patrz `kolekcje-katalog.md`.
- **Formularze z buildera:** ZAWSZE pola/etykiety/komunikaty z buildera w panelu (kolekcja Forms) + `submitForm`. NIGDY nie hardkoduj pól ani tekstów w JSX. Turnstile: `TurnstileProvider` (siteKey raz w layoutcie) + `useTurnstile()`.
- **Logika formularza z pluginu:** stan/walidacja/Turnstile/submit przez `useForm` (dowolne pola) lub `useContactForm` (preset) z `@intecion/ipal-kit/client` — hooki NIE renderują markupu, wygląd zostaje w projekcie. NIGDY nie kopiuj ręcznej hydrauliki (useState na pola, regex e-maila, obsługa tokenu, try/catch submitu) do projektu — to antywzorzec, który hook eliminuje. Walidacja przez `buildValidator` + reguły (`required`, `email`, `minLength`, `pattern`…). Patrz `forms.md`.
- **Wartości lokalizowane:** ZAWSZE `resolveLocalized(value, locale)` z pluginu. NIGDY własny `getSafeString`/`(v as any)[locale]` kopiowany do JSON-LD, rich text czy topiców formularza.
- **ZAKAZ:** `locale as 'pl' | 'en'`, zaszyty slug kolekcji, dane firmy, NIP, adres, telefon w kodzie.
- **WYMAGANE:** Jedno źródło prawdy `i18n.config.ts`, `locale as never`, dane firmy z globala (np. `siteSettings` / `CompanyInfo`), infrastruktura wyłącznie w `.env`.
---
## 4. ARCHITEKTURA I STRUKTURA PROJEKTU
### A. Next 16 + Payload 3:
- **NIGDY nie twórz `middleware.ts`.** W Next 16 stosuje się **WYŁĄCZNIE `proxy.ts`** (funkcja `proxy`). Jeśli plik `middleware.ts` istnieje — usuń go natychmiast.
- **Struktura katalogów:**
```
src/
app/
(frontend)/
styles.css # Tailwind + @source na plugin
[locale]/
layout.tsx # root layout bez sztywnego <head>
not-found.tsx # 404 (treść z panelu)
[[...slug]]/
page.tsx # render stron z bloków (podwójne nawiasy!)
(payload)/ # panel admina
manifest.ts # PWA z panelu — WYMAGANE export const dynamic = 'force-dynamic'
sitemap.ts # z lib/content + export const dynamic = 'force-dynamic'
robots.ts # z lib/content
instrumentation.ts # assertEnv(ipalEnvRules(...)) — walidacja ENV na starcie
blocks/
<NazwaBloku>/
config.ts # schemat pól bloku
Component.tsx # render komponentu
registry.ts # mapa blockType -> komponent
collections/
Pages.ts # layout typu blocks
Media.ts # upload + normalizeFilenameHook
globals/ # siteSettings, siteIntegrations, navigation, footer
lib/
content.ts # createContentHelpers — JEDNO źródło
payload.ts # helpery projektu (getSettings...)
i18n.config.ts # locale — jedno źródło
payload.config.ts
proxy.ts # routing locale (NIE middleware.ts)
```
### B. Przepływ danych i zależności:
- **Brak cykli importów:** Warstwa niższa (bloki) **NIE** może importować warstwy wyższej (`lib/*`). Dane zewnętrzne (np. klucze Turnstile) przekazuj przez `enhanceProps` w `page.tsx`.
- **Dostęp do Payloada:** Jedno źródło `getCachedPayload` w `lib/content.ts`.
- **Server Components (RSC) domyślnie:** Pobieranie danych po stronie serwera; `'use client'` stosuj wyłącznie dla komponentów z lokalnym stanem/interakcją. Chroń wrażliwe moduły przez `import 'server-only'`.
### C. Kluczowe wymagania SEO i Renderingu:
1. **Brak jawnego `<head>` w layoutcie:** Sztywny `<head>` wypycha metatagi Next.js do `<body>`. Pozwól Next.js zarządzać nagłówkiem. `<MediaPreconnect />` umieszczaj w `<body>` (React 19 automatycznie hoistuje tag link do head).
2. **Wymagane ISR:** `export const revalidate = 3600` w `page.tsx` stron (zapobiega race condition streamingu metadanych i zapewnia TTFB ~20ms).
3. **Wymagane `generateStaticParams`:** W `[[...slug]]/page.tsx` eksportuj `generateStaticParams` z `lib/content` (`export { generateStaticParams } from '@/lib/content'`). Gwarantuje synchroniczne generowanie metadanych w `<head>` dla robotów.
4. **`htmlLimitedBots`:** Skonfiguruj w `next.config.ts` zgodnie z `seo.md`.
5. **`export const dynamic = 'force-dynamic'` na route'ach odpytujących bazę:** `manifest.ts`, `llms.txt/route.ts`, `sitemap.xml/route.ts`. Bez tego Next próbuje prerenderować je podczas `docker build` (baza offline → crash). Handlery pluginu mają try/catch jako drugą warstwę, ale `dynamic` to eksport modułowy — MUSI być w pliku route'a, handler nie ustawi go za Ciebie.
6. **Walidacja ENV na starcie:** `instrumentation.ts` z `assertEnv(ipalEnvRules({ ... }))` — fail fast przy brakującej konfiguracji, zamiast kryptograficznego crashu w buildzie. Patrz `env.md`.
---
## 5. STANDARDY KODU I TYPOWANIA (POZIOM SENIOR)
1. **Zero `any` i zero `@ts-ignore`:**
- Zawsze typuj precyzyjnie. Jeśli kształt danych z zewnątrz jest nieznany, użyj `unknown` + zawężenie (type guard).
- Wyjątek: wąskie rzutowanie `as unknown as Record<string, unknown>` przy udokumentowanych rozbieżnościach generatora Payload (np. pole zlokalizowane przy `locale: 'all'`).
2. **Typy generowane:** Importuj typy z `@/payload-types` (`pnpm generate:types`), nie twórz ręcznych duplikatów interfejsów.
3. **Generyki przy wywołaniu:** Stosuj np. `getSiteSettings<SiteSetting>(payload)`, a nie rzutowanie `as SiteSetting` na wyniku.
4. **`satisfies` dla konfiguracji:** Używaj `as const satisfies I18nConfig`.
5. **Obsługa błędów:** Nigdy nie połykaj błędów (`catch {}`). Loguj konkretny komunikat i zwracaj kontrolowany błąd. Stosuj guard clauses (płaski kod).
6. **Transakcje i hooki:** W hookach Payload zawsze przekazuj `req` do kolejnych operacji bazodanowych. Chroń hooki przed nieskończonymi pętlami za pomocą flagi w `context` (np. `context.skip`). Przy `payload.find` pamiętaj o `overrideAccess: false`, jeśli operacja ma respektować uprawnienia usera.
---
## 6. NAZEWNICTWO I KONWENCJE
- **Foldery bloków i pliki kolekcji:** PascalCase (`blocks/HeroSection/`, `collections/Pages.ts`).
- **Pliki bloku:** `config.ts` + `Component.tsx` w jednym folderze.
- **Slugi kolekcji:** camelCase, liczba mnoga (`pages`, `blogPosts`, `products`).
- **Slugi bloków:** camelCase (`hero`, `textSection`). Klucz w `registry.ts` musi być identyczny ze slugiem bloku.
- **Wspólne nazwy pól (obowiązkowe w każdym projekcie):**
- Nagłówek: `heading`
- Podtytuł: `subheading`
- Treść: `body` (textarea) lub `content` (richText)
- Obraz: `image` (upload -> media)
- Przycisk CTA: `ctaLabel` (text, localized)
- Cel CTA: `ctaTarget` (relationship -> pages)
- Link zewn.: `url` (text)
- Zgoda prawna: `consent` (checkbox)
---
**Globale Company/Header/Footer → PROJEKT, nie plugin.** Model danych firmy różni się per kraj (NIP/PL, ABN/AU, EIN/US) i branżę. NIE szukaj buildCompanyGlobal w pluginie — zdefiniuj własny src/globals/Company.ts. Schema.org: klocki pluginu (buildOrganizationJsonLd...) + JsonLdGraph, zmapuj SWOJE dane na @type (LegalService/PL, HVACBusiness/AU). Patrz seo.md.
## 6b. WYMAGANIA PRAWNE (COMPLIANCE)
Każda strona (PL/EU) MUSI mieć: polityka prywatności, polityka cookies, baner
zgody cookies, zgoda RODO w formularzach. Plugin dostarcza MECHANIZM:
- **Strony polityk** → System Pages (role: privacyPolicy, cookiePolicy, termsOfService), linkowane przez `getSystemPagePath`.
- **Baner cookies** → CookieBanner + CookieButton + ConsentProvider (analytics/marketing gated — NIE ładują się przed zgodą).
- **Zgoda RODO** → checkbox `consent` w formularzu (enforcement server-side w submitForm).
- **Strony noindex** → polityki/regulamin zaznacz `noindex` w panelu SEO (kanibalizacja fraz).
- **Ochrona:** hook `buildPreventDeleteSystemPage` blokuje usunięcie strony systemowej.
Granica: MY dostarczamy mechanizm, TREŚĆ prawną (tekst polityk) tworzy klient/prawnik.
**Widget dostępności (a11y)** — OPCJONALNY, NIE dodawaj domyślnie. Wymagany tylko
dla podmiotów publicznych / części e-commerce (European Accessibility Act). Dla
zwykłych stron komercyjnych to opcja — dodawaj GDY klient wymaga (AccessibilityProvider
+ AccessibilityWidget + CSS projektu). Patrz `accessibility.md`.
Patrz `wymagania-prawne.md`.
## 6c. HOOKI PLUGINU (automatyzacja)
Wpinaj w kolekcje gdzie dotyczy (patrz `hooks.md`):
- **buildRevalidateHook** (afterChange/afterDelete) — ISR odświeżany po zapisie (redaktor od razu widzi zmianę). `revalidatePath` wstrzykiwany z projektu.
- **trackSlugHistoryHook** (beforeChange) — zmiana slug → zapis starego slug. Odczyt robi **resolveRedirect** (patrz niżej) — NIE pisz własnego lookupu.
- **resolveRedirect** (moduł content) — w catch-all, gdy `resolveRoute` nic nie znajdzie: czyta slugHistory i zwraca cel 301/308; projekt woła `permanentRedirect` (plugin nie importuje `next/navigation`). Domyka trackSlugHistoryHook.
- **buildCrossLocaleFieldSync** (afterChange) — kopiuje pola wspólne dla języków (obrazki) wewnątrz lokalizowanego `blocks` między locale. Lista języków z `config` (NIGDY hardkod `['pl','en',…]`). Zastępuje ręczny hook z zahardkodowaną listą.
- **buildNoindexField** (pole, nie hook) — sidebarowy checkbox `noindex` zgrany z `meta.noindex`, bez `any`. Zamiast ręcznego checkboxa + hooka glue.
- **setPublishedAtHook** — auto-data publikacji (blog).
- **normalizeFilenameHook** — czyste nazwy plików (Media, obowiązkowo).
- **buildPreventDeleteSystemPage** / **buildValidateUniqueRole** — ochrona stron systemowych.
## 6d. BEZPIECZEŃSTWO (nagłówki)
- **buildSecurityHeaders** w next.config — HSTS, COOP, nosniff, Referrer-Policy (z automatu, uniwersalne).
- **buildCsp** — generator CSP z twardymi regułami (base-uri, object-src, frame-ancestors). Flagi: turnstile, analytics, youtube, r2Url. Wdrażaj przez `report-only` → sprawdź konsolę → `enforce`.
- **2FA WYMUSZONE** — `pnpm add @clocklimited/payload-2fa@3.0.0-beta.7`, potem WSTRZYKNIJ: `import { payloadTotp } from '@clocklimited/payload-2fa'` + `ipalKit({ twoFactor: { issuer: 'Nazwa Firmy', plugin: payloadTotp } })`. Wstrzyknięcie obowiązkowe — bez niego plugin robi dynamiczny import, którego Next nie wbundluje → „Cannot find module" na froncie. (Ewentualnie: `serverExternalPackages: ['@clocklimited/payload-2fa']` w next.config.) Wymuszone dla WSZYSTKICH (forceSetup), bez opcji per user. NIE `twoFactor: false` (chyba że klient wprost odmawia). Patrz security.md.
- **Ścieżka panelu** — `ipalKit({ adminRoute: '/its' })` ukrywa panel. WYMAGA przeniesienia folderu `app/(payload)/admin/` → `app/(payload)/its/`. To obscurity, nie security (2FA to prawdziwa ochrona).
- CSP zostaje w projekcie (domeny), ale skeleton z pluginu. NIE Trusted Types (psuje Turnstile/GA).
## 7. PODZIAŁ PRACY I RÓL
- **Antigravity (Agent):** Buduje architekturę, logikę, kolekcje, bloki, routing, edytowalność przez panel, integracje oraz dba o brak hardkodów.
- **Impeccable (osobne narzędzie):** Dopracowuje wygląd, system wizualny na bazie `PRODUCT.md` i `DESIGN.md`. Antigravity nie „dopieszcza" styli ad-hoc kosztem logiki i edytowalności.
- **Klient / Redaktor:** Samodzielnie zarządza każdą treścią z poziomu panelu CMS.
---
## 8. PROCEDURA RAPORTOWANIA DO PLUGINU
Jeśli w trakcie pracy:
1. Funkcja okaże się brakująca w `@intecion/ipal-kit`,
2. Wystąpi błąd wewnętrzny w bibliotece pluginu,
3. Pojawi się powtarzalna potrzeba biznesowa przydatna w wielu projektach,
**Należy natychmiast przygotować raport proponowanej zmiany/rozbudowy pluginu:**
- Dokładny opis problemu / brakującej funkcjonalności,
- Proponowany interfejs API / sygnatura funkcji lub konfiguracji,
- Uzasadnienie uniwersalności dla innych projektów.
**Nie wolno tworzyć cichej łaty w kodzie projektu.**
---
## 9. MAPA DOKUMENTACJI — gdzie szukać szczegółów
Ten plik to skondensowane reguły. Szczegóły w `node_modules/@intecion/ipal-kit/docs/`:
| Chcę... | Plik |
|---|---|
| Zbudować projekt od zera | `getting-started.md` |
| Strukturę, nazewnictwo, konwencje | `fundamenty-projektu.md` |
| Jakie kolekcje budować (minimum!) | `kolekcje-katalog.md` |
| SEO, metadane, sitemap, favicon, structured data, llms.txt | `seo.md` |
| Hooki (revalidate, slug history, cross-locale sync, ochrona) | `hooks.md` |
| Redirecty 301/308 (resolveRedirect) | `content.md` |
| Walidacja ENV na starcie (assertEnv) | `env.md` |
| Czytelność dla AI: Markdown per strona, llms-full, boty AI w robots | `content.md`, `seo.md` |
| Serwer MCP strony (Claude podłącza się do treści) | `mcp.md` |
| GTM + Meta Pixel — konfiguracja krok po kroku | `gtm-meta-pixel.md` |
| White-label panelu admina (logo/nazwa z SiteSettings) | `white-label.md` |
| Bezpieczeństwo, CSP, COOP | `security.md` |
| Formularze, Turnstile, submitForm, useForm/useContactForm | `forms.md`, `turnstile.md` |
| i18n, strona jednojęzyczna, ścieżki | `i18n.md` |
| Strony systemowe, routing | `pages.md` |
| Bloki, RenderBlocks | `blocks.md` |
| Media, R2, MediaPreconnect | `storage.md` |
| Email (SMTP/Graph) | `email.md` |
| Consent, cookies | `consent.md` |
| Deployment, ISR/SSG, Coolify | `deployment.md` |
| Wymagania prawne, compliance | `wymagania-prawne.md` |
| Filozofia CMS, edytowalność, Impeccable | `architektura-tresci.md` |
| Standardy kodu, antywzorce | `standardy-kodu.md` |
---
## 10. ZAPISZ REGUŁY PROJEKTU
Kluczowe ustalenia projektu (stack, decyzje, tryby stron) zapisz we własnym pliku
kontekstu (`agents.md` / `.agents/context/`), żeby nie gubić ich między sesjami.
Nie polegaj tylko na pamięci sesji.
+241 -11
View File
@@ -1,22 +1,58 @@
# analytics
Ładuje GA4 albo Google Tag Manager, spięte z modułem consent: Consent Mode
dostaje decyzję odwiedzającego, zanim tag się załaduje, i aktualizację w
momencie kliknięcia w banerze.
Ładuje tagi analityczne i marketingowe wpisane w panelu, każdy zgodnie ze
zgodą z modułu consent:
- **Google (GA4 / GTM)** — przez Consent Mode v2: tag ładuje się od razu, ale
dostaje decyzję odwiedzającego, zanim cokolwiek zmierzy.
- **Pozostałe (Meta Pixel, Microsoft Clarity, LinkedIn Insight, TikTok Pixel)** —
nie mają Consent Mode, więc ładują się **dopiero po zgodzie** na właściwą
kategorię. Reagują na żywo: klik „Akceptuj” → tag startuje bez przeładowania.
## Config
Brak opcji w `payload.config` — plugin czyta ID z globala **Site Integrations**
(Settings → Site Integrations):
- **GA4 Measurement ID** — `G-XXXXXXXXXX`
- **GTM Container ID** — `GTM-XXXXXXX`
| Pole | Format | Kategoria zgody |
|---|---|---|
| GA4 Measurement ID | `G-XXXXXXXXXX` | Consent Mode (analytics_storage) |
| GTM Container ID | `GTM-XXXXXXX` | Consent Mode (wszystkie sygnały) |
| Meta Pixel ID | `1234567890123456` | **marketing** |
| Microsoft Clarity Project ID | `abcdefghij` | **analytics** |
| LinkedIn Partner ID | `1234567` | **marketing** |
| TikTok Pixel ID | `CXXXXXXXXXXXXXXXXXXX` | **marketing** |
Gdy ustawione są oba, wygrywa GTM. Gdy żadne — komponent nie robi nic.
GA4 + GTM ustawione jednocześnie → wygrywa GTM. Puste pole = tag się nie ładuje.
To jedyne pola z Site Integrations, które trafiają na klienta — są publiczne
(widać je w źródle każdej strony z GA). `getAnalyticsConfig` czyta wyłącznie je,
więc sekrety (Turnstile, SMTP) nie mają jak wyciec.
Wszystkie te ID są publiczne (widać je w źródle strony). `getAnalyticsConfig`
czyta wyłącznie je, więc sekrety (Turnstile, SMTP) nie mają jak wyciec.
### Pixel w panelu czy w GTM?
**Jedno albo drugie, nigdy oba** — inaczej każde zdarzenie liczy się
podwójnie. Zasada:
- Klient bez GTM / prosta strona → wpisz Pixel ID w panelu (najprościej,
zgoda obsłużona automatycznie).
- Klient ma agencję/marketera, który zarządza tagami w GTM → zostaw pole Pixel
puste, Pixel konfiguruje się w GTM z warunkiem `ad_storage` (patrz sekcja
„Meta Pixel przez GTM” niżej).
### Zdarzenia konwersji (non-Google)
`Analytics` wysyła tylko `PageView`. Konwersje (np. Lead po formularzu) wołasz
sam — globale istnieją dopiero po zgodzie, więc zawsze ze strażnikiem:
```ts
window.fbq?.('track', 'Lead') // Meta
window.ttq?.track('SubmitForm') // TikTok
window.lintrk?.('track', { conversion_id: 123 }) // LinkedIn
```
Niskopoziomowe loadery (`loadMetaPixel`, `loadClarity`, `loadLinkedIn`,
`loadTikTok`) są eksportowane z `/client`, ale normalnie nie są potrzebne —
NIE wołaj ich z pominięciem zgody.
## Front
@@ -41,7 +77,30 @@ export default async function LocaleLayout({ children, params }) {
```
`Analytics` nie renderuje nic — wstrzykuje skrypty. Zamontuj raz, wysoko w
drzewie.
drzewie. **Musi być wewnątrz `ConsentProvider`** (od 1.8.0 czyta stan zgody na
żywo — poza providerem rzuci błąd kontekstu).
## Tryb Core Web Vitals — `defer` (opcjonalny)
```tsx
<Analytics {...analytics} defer /> // domyślnie 3500 ms
<Analytics {...analytics} defer deferTimeoutMs={5000} />
```
Wszystkie tagi (GA4/GTM i pixele) ładują się z sieci dopiero przy **pierwszej
interakcji** (scroll, klik, dotyk, klawisz) albo `deferTimeoutMs` po `load`,
w zależności od tego, co nastąpi pierwsze. ~100+ KiB JS wypada z okna FCP/LCP.
Defer zmienia **kiedy**, nigdy **czy**:
- domyślny stan Consent Mode nadal idzie od razu (to tylko push do dataLayer, bez
ruchu sieciowego), więc GA nigdy nie startuje bez niego;
- pixele non-Google nadal wymagają zgody na swoją kategorię.
Koszt: odwiedzający, którzy wyjdą przed interakcją i przed upływem timeoutu, nie
zostaną policzeni (trochę mniej sesji w GA). Domyślnie `defer` jest wyłączony.
**Nie kopiuj `Analytics` do projektu, żeby to zmienić.** Brakujące opcje dodajemy
w ipal-kit (core = engine).
## Jak działa Consent Mode
@@ -68,6 +127,11 @@ W konsoli: `window.dataLayer` — powinien zawierać `Arguments(3)` z `consent`
Ciasteczko `_ga` pojawia się dopiero po zgodzie na analytics — to jest sedno
Consent Mode.
Pixele non-Google: przed zgodą w Network **nie może** być żądań do
`connect.facebook.net`, `clarity.ms`, `snap.licdn.com`, `analytics.tiktok.com`.
Po kliknięciu zgody pojawiają się od razu. Meta Pixel Helper (rozszerzenie
Chrome) powinien pokazać `PageView` dopiero po akceptacji marketingu.
## Zdarzenia do GTM — pushDataLayer
Do wypchnięcia własnego zdarzenia (np. `form_submit` pod tag Lead w GTM) jest
@@ -95,4 +159,170 @@ czysty event, na którym tag może się odpalić, gdy zgoda jest udzielona.
Publish, nie sam zapis) tagu GA4 w kontenerze wszystko wygląda dobrze:
`gtm.load` w dataLayer, Tag Assistant widzi kontener — a `_ga` nie ma, bo nic go
nie tworzy. Przy debugowaniu warto tymczasowo wyczyścić GTM Container ID i
zostawić samo GA4, żeby wyeliminować kontener jako zmienną.
zostawić samo GA4, żeby wyeliminować kontener jako zmienną.
---
## Meta Pixel przez GTM — krok po kroku
Wariant dla klientów, u których tagami zarządza marketer w GTM (wtedy pole
**Meta Pixel ID** w panelu zostaje **puste** — inaczej podwójne zliczanie).
Plugin ładuje kontener i obsługuje Consent Mode v2 (`marketing` →
`ad_storage`, `ad_user_data`, `ad_personalization`); zdarzenie `form_submit`
z parametrami ustawia się w panelu formularza. W kodzie projektu nic poza
jednorazowym `onSuccess` w rendererze formularza.
### 0. Wymagania wstępne (panel Payload)
1. **GTM Container ID** w Settings → Site Integrations (`GTM-XXXXXXX`).
2. **Baner cookies** aktywny (`CookieBanner` + `ConsentProvider`) — inaczej
Consent Mode nie dostanie decyzji.
3. **Pole analityki na formularzu** — dodaj `buildFormAnalyticsFields()` do
kolekcji Forms (patrz [forms.md](./forms.md) → „Zarządzanie z panelu"), a w
rendererze: `onSuccess: formAnalyticsOnSuccess(form.analytics)`. W panelu (po
angielsku), na formularzu kontaktowym w grupie **Analytics (GTM / dataLayer)**
ustaw: **Event name** `form_submit`, parametr `form_name = $topic` (albo
stała, np. `kontakt`).
---
### 1. Pixel ID jako zmienna GTM
Events Manager → Źródła danych → Twój pixel → skopiuj **Pixel ID** (15–16 cyfr).
GTM → Zmienne → Zmienne zdefiniowane przez użytkownika → **Nowa** → **Stała** →
wartość = Pixel ID → nazwij `Meta Pixel ID`.
### 2. Szablon tagu Meta
Meta nie ma natywnego tagu w GTM. Dwie drogi:
- **Szablon społeczności (wygodniej):** Szablony → Szablony tagów → Przeszukaj
galerię → „Facebook Pixel" → Dodaj do obszaru roboczego.
- **Custom HTML:** wklej kod bazowy pixela z Events Manera (wariant dla pełnej
kontroli; wtedy pomijasz szablon i robisz tagi jako Custom HTML).
Poniżej zakładam szablon.
### 3. Tag bazowy — PageView
Tagi → **Nowy** → typ **Facebook Pixel**:
- **Pixel ID:** `{{Meta Pixel ID}}`
- **Event:** Standard → `PageView`
- **Ustawienia zgody** (Zaawansowane → Consent Settings): wymagaj **`ad_storage`**.
- **Trigger:** `All Pages` + (dla Next.js) drugi trigger **History Change** —
patrz sekcja SPA niżej.
Nazwij np. `Meta – Base + PageView`.
### 4. Zmienna dla parametru z formularza
Zmienne → **Nowa** → **Zmienna warstwy danych**:
- Nazwa zmiennej warstwy danych: `form_name`
- Wersja: Wersja 2
- Nazwij u góry dokładnie `DLV – form_name`.
> Nazwa w tagu i w zmiennej musi być **znak w znak** taka sama, łącznie z
> myślnikiem. Jeśli w tagu jest długi myślnik „–", a w zmiennej wpiszesz zwykły
> „-", GTM uzna to za dwie różne zmienne. Najbezpieczniej skopiuj tekst spomiędzy
> `{{` a `}}`.
### 5. Trigger — wysłanie formularza
Triggery → **Nowy** → **Zdarzenie niestandardowe**:
- Nazwa zdarzenia: `form_submit` (dokładnie tak, jak event z panelu formularza)
- Uruchamiany na: Wszystkie zdarzenia niestandardowe.
Nazwij `CE – form_submit`.
### 6. Tag konwersji — Lead
Tagi → **Nowy** → **Facebook Pixel**:
- **Pixel ID:** `{{Meta Pixel ID}}`
- **Event:** Standard → `Lead`
- **Object Properties / parametry:** `content_name` = `{{DLV – form_name}}`
- **Ustawienia zgody:** wymagaj **`ad_storage`** (tak samo jak tag bazowy).
- **Trigger:** `CE – form_submit`.
Nazwij `Meta – Lead`.
Inne konwersje analogicznie, każda jako osobny tag z tego samego szablonu:
- **Contact** — trigger na kliknięcie w `tel:` / `mailto:`.
- **ViewContent / AddToCart / Purchase** — parametry (`value`, `currency`,
`content_ids`) ze zmiennych warstwy danych; zdarzenie pushowane z kodu/panelu
tam, gdzie zachodzi akcja.
---
### 7. Zgoda (RODO) — krytyczne
Pixel marketingowy **nie może odpalić przed zgodą**. W każdym tagu Meta ustaw
Consent Settings → wymagaj `ad_storage`. Plugin trzyma `ad_storage = denied` do
czasu akceptacji w banerze i wysyła `update` po kliknięciu — tag odpali się
dopiero wtedy. Bez tego warunku pixel strzeli mimo braku zgody (naruszenie RODO).
W Podglądzie sprawdź: **przed** akceptacją baner → tag `Meta – Base + PageView`
ma być **zablokowany**; **po** akceptacji → „Uruchomiono".
### 8. Next.js / SPA — PageView przy zmianie trasy
Przy nawigacji po stronie klienta (routing Next.js bez pełnego przeładowania)
`All Pages` odpali się tylko raz. Dwie opcje:
- **W GTM (bez kodu, zalecane):** dodaj do tagu PageView drugi trigger typu
**Zmiana historii** (History Change). GTM łapie zmianę trasy.
- **Z kodu (jeśli wolisz jawne eventy):** pushuj `page_view` do dataLayer przy
zmianie trasy (`pushDataLayer('page_view')` na zmianę `usePathname`) i zrób
trigger `CE – page_view`.
W Podglądzie / Events Manager policz: ma być **jeden** PageView na zmianę
podstrony i brak podwójnego liczenia pierwszego wejścia.
### 9. Duplikaty
Jeśli pixel jest też wklejony na sztywno w kodzie strony albo przez inną wtyczkę
— **usuń go stamtąd**. Ma być tylko w GTM, inaczej zdarzenia liczą się podwójnie.
---
### 10. Test
1. **Podgląd GTM** (prawy górny róg) → podaj adres strony.
2. Zaakceptuj cookies marketingowe.
3. Tag Assistant: `Meta – Base + PageView` = „Uruchomiono" (przed zgodą
zablokowany).
4. Wyślij formularz → w lewej kolumnie zdarzenie `form_submit`, przy nim tag
`Meta – Lead` „Uruchomiono"; w zakładce Zmienne `DLV – form_name` ma wartość
(np. `kontakt`).
5. **Meta Pixel Helper** (rozszerzenie Chrome) → widzi PageView i Lead.
6. **Events Manager → Testuj zdarzenia** → wpisz adres → `PageView` i po
wysłaniu formularza `Lead` z parametrem `content_name`.
### 11. Publikacja
GTM → **Prześlij** → nazwa wersji (np. „Meta Pixel – PageView + Lead") →
**Opublikuj**. Do tego momentu nic nie działa na produkcji — sam zapis tagu nie
wystarczy.
---
### 12. (Opcjonalnie) Conversions API (CAPI)
Żeby wysyłać zdarzenia także z serwera (odporność na blokery/iOS), każde
zdarzenie potrzebuje wspólnego `event_id` w pixelu i w CAPI, żeby Meta mogła je
deduplikować. To osobny temat (server-side GTM albo wysyłka z backendu) — w tym
stacku `submitForm` (server) mógłby generować `event_id`, a `pushDataLayer`
używałby tego samego. Jeśli wchodzicie w CAPI, zgłoś — to rozszerzenie modułu
forms + analytics, nie konfiguracja GTM.
---
### Ściąga — kto co robi
| Element | Gdzie |
|---|---|
| Ładowanie GTM, Consent Mode | plugin (auto) |
| Event `form_submit` + parametry | panel Payload (grupa „Analytics" na formularzu) |
| Pixel ID, tagi, triggery, warunki zgody | panel GTM |
| Publikacja kontenera | panel GTM |
| Kod projektu | nic (poza jednorazowym `onSuccess` w rendererze) |
+18 -7
View File
@@ -20,6 +20,20 @@ treścią bannera (message, przyciski, kategorie, settingsTitle) w panelu,
localized. Link do polityki prywatności bierze się z system pages
(`privacyPolicy`), nie z osobnego pola.
**Link do polityki prywatności w banerze (od 1.8.1)** — zero kodu:
| Co | Skąd |
|---|---|
| Dokąd prowadzi | Site Settings → System Pages → Privacy Policy |
| Tekst linku | Cookie Settings → `privacyLinkLabel` (per język) |
| Gdy tekst pusty | tytuł strony polityki w danym języku |
Opcje `privacyPolicy` w `getConsentTexts`: pomiń (automat), `false` (bez
linku), `{ page }` (własna strona, odczytana z `locale: 'all'`). Parametr
`label` jest **przestarzały** — tekst wpisany w kodzie łamie A0 przy kilku
językach; działa tylko, gdy pole w panelu jest puste. Usuń go z projektów przy
okazji aktualizacji.
## Front — Provider + banner
Provider owija aplikację, banner i button renderują się same. Import z
@@ -34,12 +48,9 @@ export default async function Layout({ children, params }) {
const { locale } = await params
const payload = await getPayload({ config })
// teksty z CookieSettings + link do polityki z system pages
const settings = await payload.findGlobal({ slug: 'site-settings', locale: 'all', depth: 1 })
const texts = await getConsentTexts({
payload, config: i18nConfig, locale,
privacyPolicy: { label: 'Polityka prywatności', page: settings.privacyPolicy },
})
// teksty z Cookie Settings; link do polityki automatycznie:
// cel = System Pages → Privacy Policy, tekst = Cookie Settings → privacyLinkLabel
const texts = await getConsentTexts({ payload, config: i18nConfig, locale })
return (
<ConsentProvider texts={texts}>
@@ -131,7 +142,7 @@ Dostępne tokeny (każdy ma odpowiednik `-dark` używany pod `dark:`):
| `--ipal-hover` | `#f5f5f5` | hover przycisków drugorzędnych |
| `--ipal-radius` | `0.375rem` | zaokrąglenie przycisków |
Wymaga `@source` skanującego pakiet (patrz getting-started.md) — inaczej Tailwind
Wymaga `@source` skanującego pakiet (patrz PROGRAMISTA.md §2.5) — inaczej Tailwind
nie wygeneruje tych klas.
### Gdy tokeny nie wystarczą
+1223
View File
File diff suppressed because it is too large Load Diff
-86
View File
@@ -1,86 +0,0 @@
# Jak komendy rozmawiają z git.intecion.net
Ten plik tłumaczy, co robi każda komenda, gdy instalujesz `@intecion/ipal-kit`.
Rejestr pakietów jest **publiczny do odczytu** — instalacja nie wymaga tokenu.
Token jest potrzebny tylko przy publikowaniu nowych wersji (patrz
[publishing.md](./publishing.md)).
## Rejestr scoped — co to znaczy
W `.npmrc` masz jedną linię:
```
@intecion:registry=https://git.intecion.net/api/packages/IntecionSoftware/npm/
```
To reguła: „pakiety zaczynające się od `@intecion/` pobieraj z tego adresu".
**Nie zmienia** domyślnego rejestru — wszystko inne (`react`, `next`,
`@payloadcms/*`) dalej idzie z publicznego npm. To override dla jednego scope,
nie przełączenie całego źródła.
Dlatego mieszana instalacja działa bez konfliktu:
- `@intecion/ipal-kit` → Gitea
- `react`, `payload`, `lucide-react` → npm
## Komenda po komendzie
### edycja `.npmrc` (linia z registry)
**Co robi:** zapisuje regułę „scope `@intecion` → rejestr Gitea". Nic nie
pobiera — to plik konfiguracyjny, czytany dopiero przy instalacji.
**Rozmowa z serwerem:** żadna przy samym zapisie.
Ponieważ rejestr jest publiczny, ta linia **nie zawiera tokenu** — plik jest
bezpieczny do zacommitowania i musi trafić do repo, żeby serwer deploymentu też
wiedział, skąd brać `@intecion/*`.
### `pnpm add @intecion/ipal-kit`
**Co robi:** to komenda, która faktycznie łączy się z rejestrem.
Krok po kroku:
1. pnpm widzi scope `@intecion` → sprawdza `.npmrc` → znajduje regułę „→ Gitea".
2. Łączy się z rejestrem Gitea. Rejestr publiczny, więc **bez tokenu**.
3. Rejestr odsyła metadane pakietu (wersje, adres `.tgz`).
4. pnpm pobiera i rozpakowuje do `node_modules/@intecion/ipal-kit` — **czysta
ścieżka**, bez hasha commita.
Ta czysta ścieżka jest ważna: komponenty klienta pluginu (baner zgód, analytics,
Turnstile) rozwiązują się poprawnie tylko z niej. Instalacja z gita dawała
pokręconą ścieżkę z hashem, która łamała React Client Manifest.
**Gdy to zawiedzie:**
- `404` — brakuje linii `@intecion:registry` w `.npmrc`, więc pnpm poszedł do
publicznego npm, gdzie pakietu nie ma. Sprawdź, czy `.npmrc` istnieje i ma tę
linię.
### `pnpm install`
**Co robi:** odtwarza wszystkie zależności z `package.json` / lockfile, w tym
`@intecion/ipal-kit`. Ta sama rozmowa z Gitea dla części `@intecion`, reszta z
npm. Różnica względem `add`: `install` odtwarza to, co już zapisane, `add`
dopisuje nowe.
## Sprawdzenie, czy rejestr odpowiada
Bez tokenu, publiczny endpoint:
```bash
curl -s -o /dev/null -w "%{http_code}\n" \
https://git.intecion.net/api/packages/IntecionSoftware/npm/@intecion%2Fipal-kit
```
`200` → rejestr działa, pakiet dostępny. `404` → zła ścieżka/nazwa.
## Krótkie podsumowanie
| Komenda | Rozmawia z serwerem? | Token? | Po co |
|---|---|---|---|
| edycja `.npmrc` (registry) | nie | nie | reguła scope na później |
| `pnpm add @intecion/ipal-kit` | tak | nie (publiczny) | pobiera pakiet |
| `pnpm install` | tak (dla @intecion) | nie | odtwarza zależności |
| `curl .../npm/@intecion%2F...` | tak | nie | test dostępności |
Publikowanie wersji (osobna rola, **wymaga** tokenu `write:package`):
[publishing.md](./publishing.md).
+602
View File
@@ -0,0 +1,602 @@
# PROGRAMISTA.md — instalacja, nowy projekt, wdrożenie, rozwój ipal-kit
> **Dla kogo:** człowiek — programista w agencji. Reguły pisania kodu (dla AI i
> dla ludzi) są w [AGENT.md](../agent/AGENT.md); API modułów w plikach modułów (mapa w
> AGENT.md §12). Tu jest proces: jak postawić, wdrożyć, zaktualizować projekt i
> jak wydać nową wersję pluginu.
>
> Budujesz projekt z agentem AI? Gotowe polecenia, krok po kroku: [vibe.md](./vibe.md).
Spis: 1. Instalacja · 2. Nowy projekt · 3. Zmienne środowiskowe · 4. Wdrożenie
(Coolify) · 5. Compliance · 6. Aktualizacja starego projektu · 7. Diagnostyka ·
8. Rozwój i publikacja ipal-kit · 9. Git i Gitea
---
## 1. INSTALACJA ipal-kit W PROJEKCIE
**`.npmrc` w roocie projektu (commituj — nie ma sekretu):**
```ini
legacy-peer-deps=true
@intecion:registry=https://git.intecion.net/api/packages/IntecionSoftware/npm/
```
To reguła tylko dla scope `@intecion/*` — reszta (`react`, `payload`…) dalej z
npm. Rejestr jest publiczny do odczytu, instalacja bez tokenu.
```bash
pnpm add @intecion/ipal-kit
pnpm add @payloadcms/plugin-seo @payloadcms/plugin-form-builder \
nodemailer lucide-react slugify server-only
pnpm add @clocklimited/[email protected] # 2FA (wymuszone)
pnpm add tailwindcss @tailwindcss/postcss
```
**Nigdy z gita** (`git+https://…`) — ścieżka z hashem łamie React Client Manifest
(komponenty `'use client'` pluginu padają w runtime).
**Wersje `@payloadcms/*` muszą być identyczne z `payload`** — inaczej pusty tab
SEO, brak kolekcji Forms albo crash. W `package.json`:
```json
"pnpm": {
"overrides": {
"payload": "3.90.2",
"@payloadcms/ui": "3.90.2",
"@payloadcms/next": "3.90.2",
"@payloadcms/db-postgres": "3.90.2",
"@payloadcms/richtext-lexical": "3.90.2",
"@payloadcms/plugin-seo": "3.90.2",
"@payloadcms/plugin-form-builder": "3.90.2"
}
}
```
(adapter bazy dopasuj: `db-postgres` / `db-mongodb`). Potem
`rm -rf node_modules pnpm-lock.yaml && pnpm install`.
**Build z webpackiem** (Turbopack konfliktuje z `withPayload`):
```json
"build": "cross-env NODE_OPTIONS=\"--max-old-space-size=3072\" next build --webpack"
```
Sprawdzenie, czy rejestr odpowiada:
```bash
curl -s -o /dev/null -w "%{http_code}\n" \
https://git.intecion.net/api/packages/IntecionSoftware/npm/@intecion%2Fipal-kit # 200
```
---
## 2. NOWY PROJEKT — KOLEJNOŚĆ
Pnpm, Node 22+, Next 16, Payload 3. Kolejność ma znaczenie.
### 2.1 Szkielet
```bash
npx create-payload-app@latest moj-projekt # Blank; Postgres albo Mongo
cd moj-projekt
```
Usuń starter `(frontend)/layout.tsx` i `(frontend)/page.tsx` — rootem zostaje
layout pod `[locale]` (bo `<html lang>` musi znać język).
### 2.1a Skille i AGENTS.md
```json
// package.json projektu
"scripts": {
"ipal:skills": "mkdir -p .agents/skills && cp -R node_modules/@intecion/ipal-kit/docs/agent/skills/. .agents/skills/"
}
```
`pnpm ipal:skills` po instalacji i po każdej aktualizacji ipal-kit; `.agents/skills/`
commituj. W roocie `AGENTS.md` wg szablonu z [AGENT.md §13](../agent/AGENT.md).
Lista skilli: AGENT.md §14.
### 2.2 Locale — jedno źródło
```ts
// src/i18n.config.ts
import type { I18nConfig } from '@intecion/ipal-kit'
export const i18nConfig = {
defaultLocale: 'pl',
locales: [
{ code: 'pl', label: 'Polski' },
{ code: 'en', label: 'English' },
],
} as const satisfies I18nConfig
```
Strona jednojęzyczna: jeden locale, bez folderu `[locale]` (i18n.md).
### 2.3 payload.config.ts
```ts
import { buildConfig } from 'payload'
import { ipalKit, mailAdapter } from '@intecion/ipal-kit'
import { payloadTotp } from '@clocklimited/payload-2fa'
import { i18nConfig } from '@/i18n.config'
import { contentConfig } from '@/content.config'
import { Pages } from '@/collections/Pages'
import { Media } from '@/collections/Media'
export default buildConfig({
collections: [Pages, Media], // users wbudowane — nie twórz
email: mailAdapter(), // bez tego maile form-buildera nie wyjdą
plugins: [
ipalKit({
i18n: i18nConfig,
access: { authCollection: 'users' },
pages: { slug: 'pages' }, // System Pages (homepage, 404, polityki)
content: contentConfig, // kolekcje z archiwum (blog…), opcjonalnie
seo: { collections: ['pages'] },
forms: { redirectRelationships: ['pages'] },
twoFactor: { issuer: 'Nazwa Klienta', plugin: payloadTotp },
whiteLabel: true, // logo/nazwa z Site Settings w panelu
// adminRoute: '/its', // + przenieś app/(payload)/admin → its
}),
],
})
```
### 2.4 Kolekcje, bloki, wspólne pola
- `Pages`: `title` (localized), `buildSlugField({ from: 'title' })`,
`buildNoindexField()`, `layout` typu `blocks` (min. 1 blok), `trackSlugHistoryHook`,
`buildRevalidateHook`.
- `Media`: upload z `mimeTypes` (obrazy + PDF), `alt` (required, localized),
`normalizeFilenameHook`; R2 przez `buildR2Storage(['media'])` (storage.md).
- `src/fields/` (link, sectionHeader, sectionSettings) i `src/components/ui/`
(CMSLink, Button, Media, Section, SectionHeader) — gotowy kod w AGENT.md §6.
Załóż je **przed** pierwszym blokiem.
### 2.5 Tailwind
```js
// postcss.config.mjs
export default { plugins: { '@tailwindcss/postcss': {} } }
```
```css
/* src/app/(frontend)/styles.css */
@import "tailwindcss";
@source "../../../node_modules/@intecion/ipal-kit/dist/**/*.js";
```
Bez `@source` komponenty pluginu (baner cookies, Turnstile) są bez stylów.
Kolory komponentów pluginu: `--ipal-primary`, `--ipal-radius` (consent.md).
### 2.6 Proxy (NIE middleware.ts)
```ts
// src/proxy.ts
import { NextResponse } from 'next/server'
import { createProxy } from '@intecion/ipal-kit'
import { i18nConfig } from '@/i18n.config'
export const proxy = createProxy(i18nConfig, { NextResponse })
// Literał inline — Next analizuje statycznie; import zmiennej = proxy na /admin → 500
export const config = { matcher: ['/((?!api|admin|_next|.*\\..*).*)'] }
```
Ustawia `x-locale` / `x-pathname`, cookie języka za zgodą, przekierowuje `/`.
### 2.7 Warstwa danych — jedno źródło
```ts
// src/lib/content.ts
import { createContentHelpers } from '@intecion/ipal-kit'
import config from '@/payload.config'
import { i18nConfig } from '@/i18n.config'
import { contentConfig } from '@/content.config'
export const {
getCachedPayload, getSettings, getConfiguredLocales, resolveRoute, getEntries,
getNotFoundPage, generateStaticParams, sitemap, robots,
} = createContentHelpers({
config,
content: contentConfig,
i18n: i18nConfig,
baseUrl: process.env.NEXT_PUBLIC_SERVER_URL,
})
```
### 2.8 Trasy
```tsx
// src/app/(frontend)/[locale]/layout.tsx
import { notFound } from 'next/navigation'
import { getConsentTexts, getAnalyticsConfig } from '@intecion/ipal-kit'
import { ConsentProvider, CookieBanner, CookieButton, Analytics } from '@intecion/ipal-kit/client'
import { MediaPreconnect } from '@intecion/ipal-kit/rsc'
import { i18nConfig } from '@/i18n.config'
import { getCachedPayload, getConfiguredLocales } from '@/lib/content'
import '../styles.css'
type Props = { children: React.ReactNode; params: Promise<{ locale: string }> }
export default async function LocaleLayout({ children, params }: Props) {
const { locale } = await params
if (!(await getConfiguredLocales()).includes(locale)) notFound()
const payload = await getCachedPayload()
const [texts, analytics] = await Promise.all([
getConsentTexts({ config: i18nConfig, locale, payload }), // link do polityki — automatycznie (consent.md)
getAnalyticsConfig(payload),
])
return (
<html lang={locale}>
{/* BEZ <head> — Next zarządza nim sam */}
<body>
<MediaPreconnect />
<ConsentProvider texts={texts}>
<main>{children}</main>
<CookieBanner />
<CookieButton />
<Analytics {...analytics} /> {/* wewnątrz providera; opcja defer — analytics.md */}
</ConsentProvider>
</body>
</html>
)
}
```
```tsx
// 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 { createPageMetadata, resolveRedirect } from '@intecion/ipal-kit'
import { i18nConfig } from '@/i18n.config'
import { blockRegistry } from '@/blocks/registry'
import { getCachedPayload, resolveRoute } from '@/lib/content'
export { generateStaticParams } from '@/lib/content' // SSG → <head> synchroniczny
export const revalidate = 3600 // ISR
const pageMetadata = createPageMetadata({ config: i18nConfig, baseUrl: process.env.NEXT_PUBLIC_SERVER_URL })
type Args = { params: Promise<{ locale: string; slug?: string[] }> } // bez searchParams!
export async function generateMetadata({ params }: Args): Promise<Metadata> {
const { locale, slug } = await params
return pageMetadata({ payload: await getCachedPayload(), locale, slug })
}
export default async function Page({ params }: Args) {
const { locale, slug } = await params
const route = await resolveRoute(locale, slug ?? [], 1)
if (!route) {
const target = await resolveRedirect({ payload: await getCachedPayload(), locale, segments: slug, config: i18nConfig })
if (target) permanentRedirect(target)
notFound()
}
const enhanceProps = () => ({ locale }) // locale dla CMSLink w blokach
const doc = route.doc as { layout?: unknown[] }
return <RenderBlocks blocks={doc.layout as never} components={blockRegistry} enhanceProps={enhanceProps} />
}
```
Opcje `resolveRedirect` (`collections`, `homeSlug`): content.md.
Archiwum z paginacją (`?page=`) — osobna trasa albo świadomie dynamiczna (pages.md).
404 z panelu: `src/app/(frontend)/[locale]/not-found.tsx` z `getNotFoundPage`
(przykład w pages.md).
```ts
// src/app/sitemap.ts
export { sitemap as default } from '@/lib/content'
export const dynamic = 'force-dynamic'
// src/app/robots.ts
export { robots as default } from '@/lib/content'
// src/app/manifest.ts
import { createManifestHandler } from '@intecion/ipal-kit'
import { getCachedPayload } from '@/lib/content'
import { i18nConfig } from '@/i18n.config'
export const dynamic = 'force-dynamic'
export default createManifestHandler({ getCachedPayload, config: i18nConfig })
// src/app/llms.txt/route.ts
import { createLlmsTxtRoute } from '@intecion/ipal-kit'
export const dynamic = 'force-dynamic'
export const GET = createLlmsTxtRoute({ getCachedPayload, config: i18nConfig,
baseUrl: process.env.NEXT_PUBLIC_SERVER_URL! })
// src/app/api/health/route.ts
import { createHealthRoute } from '@intecion/ipal-kit'
export const dynamic = 'force-dynamic'
export const GET = createHealthRoute({ getCachedPayload })
```
Albo `sitemap.ts`, albo `sitemap.xml/route.ts` (`createSitemapRouteHandler`) —
nigdy oba.
### 2.9 next.config.ts i instrumentation.ts
```ts
// next.config.ts
import { withPayload } from '@payloadcms/next/withPayload'
import { buildSecurityHeaders } from '@intecion/ipal-kit'
const securityHeaders = buildSecurityHeaders({ hsts: process.env.NODE_ENV === 'production' })
export default withPayload({
htmlLimitedBots:
/Googlebot|Google-InspectionTool|Storebot-Google|Bingbot|Yandex|DuckDuckBot|Baiduspider|Screaming Frog|AhrefsBot|SemrushBot/i,
async headers() {
return [{ source: '/:path*', headers: securityHeaders }]
},
})
```
CSP (`buildCsp`) — najpierw `report-only`, po sprawdzeniu konsoli `enforce`
(security.md). `src/instrumentation.ts`: `assertEnv(ipalEnvRules({...}))` (env.md).
### 2.10 Generowanie i start
```bash
pnpm generate:types
pnpm payload generate:importmap # po każdej zmianie komponentów admina
pnpm dev
```
### 2.11 Konfiguracja w panelu (`/admin`)
1. Pierwszy użytkownik (admin) + konfiguracja 2FA.
2. **Site Settings → General** — nazwa witryny, logo, favicon (PNG).
3. **Pages** — strona główna z tytułem **w każdym języku** (pusty slug EN = 404 na `/en`).
4. **Site Settings → System Pages** — Homepage (bez tego `/pl` → 404), 404,
polityki; archiwa kolekcji treści.
5. **Cookie Settings** — teksty banera per język.
6. **Notifications** — komunikaty formularzy per język.
7. **Site Integrations** — SMTP/Graph (From Name, From Address), Turnstile, ID
analityki/pikseli.
`/` → przekierowanie na `/pl`. Klucze testowe Turnstile: site
`1x00000000000000000000AA`, secret `1x0000000000000000000000000000000AA`.
---
## 3. ZMIENNE ŚRODOWISKOWE
| Zmienna | Wymagana | Opis |
|---|---|---|
| `DATABASE_URI` | ✅ | Postgres / Mongo (dev może być SQLite) |
| `PAYLOAD_SECRET` | ✅ | losowy, ≥32 znaki, inny na produkcji |
| `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` | ⬜ | media w Cloudflare R2 (brak → dysk lokalny) |
Przykład R2:
```bash
R2_BUCKET=klient-media
R2_ENDPOINT=https://<ACCOUNT_ID>.r2.cloudflarestorage.com
R2_ACCESS_KEY_ID=<access-key>
R2_SECRET_ACCESS_KEY=<secret-key>
R2_PUBLIC_URL=https://media.klient.pl # custom domena podpięta do bucketa
```
Zasady: sekrety tylko w `.env` (dev) i runtime hostingu (prod), nigdy w repo.
`.env.example` (bez wartości) zawsze w repo. Treść edytowalna przez redaktora →
panel, nie env. Infrastruktura (R2, Graph, baza) → env, nie panel.
---
## 4. WDROŻENIE (Hetzner + Coolify)
### 4.1 Przed deployem
- [ ] `pnpm build` przechodzi lokalnie (nie tylko dev)
- [ ] env ustawione w runtime Coolify; `NEXT_PUBLIC_*` dostępne też w buildzie
- [ ] `NEXT_PUBLIC_SERVER_URL` = produkcyjny URL, `PAYLOAD_SECRET` produkcyjny
- [ ] HSTS włączony, media w R2 (albo wolumen — lokalne media znikają przy redeployu)
- [ ] polityki + baner cookies (§5)
### 4.2 Kolejność
```bash
pnpm install --frozen-lockfile
pnpm generate:types
pnpm build
pnpm payload migrate # Postgres z migracjami
pnpm start
```
### 4.3 Baza w czasie buildu
- **Build widzi bazę** → `generateStaticParams` prerenderuje strony (SSG, `●`),
`<head>` kompletny. Tego chcemy.
- **Build nie widzi bazy** → plugin nie wywali buildu (zwraca `[]`), ale strony
renderują się on-demand (`ƒ`) i SEO wraca do problemu metadata w body.
Zapewnij bazę w tej samej sieci Docker co build stage.
- Trasy czytające bazę (`sitemap`, `manifest`, `llms.txt`, `health`) mają
`force-dynamic` — nie są prerenderowane.
Test braku bazy: `DATABASE_URI=mongodb://invalid-host:27017/x pnpm build` → kod 0.
### 4.4 Health check
Coolify → health check na `/api/health` (`createHealthRoute`: round-trip do bazy,
200/503, `no-store`). Daj start period, jeśli baza wstaje wolniej niż aplikacja.
### 4.5 Po deployu
- [ ] `/` przekierowuje na locale, panel i logowanie (2FA) działają
- [ ] formularz wysyła (panel → Send test), media się wyświetlają (R2 bez 403)
- [ ] `curl -A "Googlebot" URL | grep canonical` — w `<head>`
- [ ] `/sitemap.xml`, `/robots.txt` odpowiadają; favicon w `<head>`
- [ ] nagłówki bezpieczeństwa (securityheaders.com)
### 4.6 Email — SMTP czy Graph
Klient na M365/Exchange → Graph (SMTP AUTH bywa wyłączony). Własny SMTP/Gmail →
SMTP. Przełącznik w panelu (Site Integrations → SMTP → Email Transport).
Graph jednorazowo: App registration w Azure, uprawnienie aplikacyjne `Mail.Send`
+ **Grant admin consent**, zmienne `GRAPH_*`. `from.address` zawsze =
`GRAPH_SENDER` (inaczej `ErrorSendAsDenied`); nazwa nadawcy z panelu; adres
klienta idzie w `replyTo`. Więcej: email.md.
---
## 5. COMPLIANCE (PL/EU) — CHECKLIST PRZED ODDANIEM
**Granica:** dostarczamy mechanizm. Treść polityk i regulaminu pisze klient albo
jego prawnik — nie jesteśmy kancelarią. Warto to zapisać w umowie.
- [ ] Strony polityk utworzone (prywatność, cookies, regulamin jeśli usługi/sprzedaż/konta)
- [ ] Role przypisane w System Pages; treść wpisana (nie placeholder); `noindex` na politykach
- [ ] Baner pokazuje się przy pierwszej wizycie; „Odrzuć” równie łatwe jak „Akceptuj”
- [ ] Analytics i pixele **nie** ładują się przed zgodą (sprawdź Network)
- [ ] `CookieButton` otwiera ustawienia ponownie; cookies znikają po wycofaniu zgody
- [ ] Formularze mają checkbox `consent` (required, enforcement server-side) z linkiem do polityki
- [ ] Dane administratora danych w globalu (polityka + stopka)
- [ ] Wszystko w każdym języku
- [ ] Widget dostępności tylko gdy wymagany (podmioty publiczne, część e-commerce — EAA)
---
## 6. AKTUALIZACJA STAREGO PROJEKTU DO NAJNOWSZEGO ipal-kit
**Jedna zasada:** gdy plugin dostarcza coś, co projekt ma napisane ręcznie —
**usuń lokalną wersję**. Dwie wersje = podwójne działanie.
Rób po jednej pozycji, buduj, sprawdzaj. Kolejność wg wagi:
| # | Co | Zrób | Doc |
|---|---|---|---|
| 1 | Metadata w `<body>` | `htmlLimitedBots`, usuń `<head>` z layoutu, `revalidate`, `generateStaticParams`, usuń `await searchParams` | seo.md, pages.md |
| 2 | `middleware.ts` / ręczny proxy | `createProxy` (§2.6) | i18n.md |
| 3 | Trasy manifest/sitemap/llms | `createManifestHandler`, `sitemap`, `createLlmsTxtRoute` + `force-dynamic`; usuń workaroundy `_status` | seo.md |
| 4 | `ConsentWrapper` z `setTimeout` | usuń — `CookieBanner`/`CookieButton` mają własny mount guard | consent.md |
| 5 | Przełącznik języka z 404 | `LanguageSwitcher` / `switchLocalePath` z `getLocalizedSlugs` | i18n.md |
| 6 | Własny parser Lexical | `RenderRichText` | richtext.md |
| 7 | Ręczna logika formularza, `getSafeString` | `useForm`/`useContactForm`, `resolveLocalized`, honeypot | forms.md |
| 8 | Hook z listą `['pl','en']` | `buildCrossLocaleFieldSync` | hooks.md |
| 9 | Ręczny checkbox noindex + hook | `buildNoindexField` | seo.md |
| 10 | Stare slugi → 404 | `trackSlugHistoryHook` + `resolveRedirect` w catch-all | hooks.md, content.md |
| 11 | Brak walidacji env | `instrumentation.ts` + `assertEnv` | env.md |
| 12 | Skrypty firm trzecich bez zgody | `ConsentScript` / `Analytics` | consent.md, analytics.md |
| 13 | Brak health checku | `createHealthRoute` (§2.8) | — |
| 14 | 2FA crash „Cannot find module” | wstrzyknij `plugin: payloadTotp` | security.md |
| 15 | Pola `ctaLabel`/`pdfUrl`, sekcje-monolity | refaktor wg AGENT.md §6.7 (z migracją danych!) | AGENT.md |
| 16 | 404 na sztywno | rola 404 w System Pages + `getNotFoundPage` | pages.md |
| 16a | `privacyPolicy: { label: 'Polityka prywatności', … }` w layoucie | usuń cały parametr; tekst wpisz w Cookie Settings → Privacy link label | consent.md |
| 17 | Opcjonalnie — AI/GEO | Markdown per strona, llms-full, boty AI w robots, MCP, wyszukiwarka, speakable, aiSummary | content.md, seo.md, mcp.md |
Po aktualizacji pakietu: `pnpm ipal:skills` (nowe wersje skilli), `rm -rf .next`, restart dev, grep nowego symbolu w
`node_modules/@intecion/ipal-kit/dist`.
---
## 7. DIAGNOSTYKA
| Objaw | Przyczyna / naprawa |
|---|---|
| Pusty tab SEO, brak kolekcji Forms | rozjazd wersji `@payloadcms/*` — `pnpm.overrides` |
| `PayloadComponent not found in importMap` | `pnpm payload generate:importmap` |
| `Cannot destructure property 'config'` | dublet `@payloadcms/ui` w pluginie — `ls node_modules/@intecion/ipal-kit/node_modules/@payloadcms/ui` |
| `Cannot find module '@clocklimited/payload-2fa'` | wstrzyknij `plugin: payloadTotp` w `twoFactor` |
| Baner bez stylów | brak Tailwinda albo `@source` na plugin |
| `/admin`, `/_next` → 500 | matcher proxy nie jest literałem inline |
| `slug.join is not a function` | `[slug]` zamiast `[[...slug]]` |
| `/pl` → 404 | Homepage nieprzypisany w System Pages |
| `/en/*` → 404, `/pl/*` działa | pusty tytuł/slug w EN |
| `Missing <html> and <body>` | usunięty root layout, a `[locale]/layout.tsx` ich nie ma |
| Trasy `ƒ` mimo `generateStaticParams` | build nie widzi bazy (§4.3) |
| Build pada na `ENOTFOUND` / Mongoose | trasa czytająca bazę bez `force-dynamic` |
| Maile nie wychodzą | brak `email: mailAdapter()` albo pusty transport w panelu |
| Zmiana w pluginie niewidoczna | nie zrestartowany dev / stara wersja w node_modules / `rm -rf .next` |
| Zmiana w panelu niewidoczna na froncie | nie kliknięto Save, albo ISR — `buildRevalidateHook` |
| Nazwa nadawcy maila stara | cache klienta poczty — sprawdź surowe nagłówki |
**„Kod dobry, zachowanie złe” — po kolei:** restart dev (Payload buduje adaptery
przy starcie) → zapis w panelu → dublet zależności → importmap → cache.
---
## 8. ROZWÓJ I PUBLIKACJA ipal-kit
### 8.1 Łańcuch zmiany
Zmiana nie działa w projekcie, dopóki nie przejdzie wszystkich etapów:
```
src → build (dist) → commit → version → publish → pnpm add w projekcie → restart
```
```bash
cd ~/payload-cms/ipal-kit
grep -c "<symbol>" src/<ścieżka> # >0 — zmiana zapisana
# docs/: zmiana API/zachowania → zaktualizuj plik modułu W TYM SAMYM commicie
pnpm clean && pnpm build
grep -c "<symbol>" dist/<ścieżka> # >0 — build ją złapał (eksport w index.ts!)
git add -A && git commit -m "opis" # PRZED version
npm version patch # minor = nowe API, major = łamiące
npm publish
git push && git push --tags
cd ~/<projekt>
pnpm add @intecion/ipal-kit@<wersja>
grep -c "<symbol>" node_modules/@intecion/ipal-kit/dist/<ścieżka> # >0
pnpm dev # restart
```
Grepuj **pojedynczy symbol**, nie frazę — kolejność kluczy w obiekcie daje
fałszywe 0. Typowe pułapki: `npm version` przed commitem (brudne repo),
`publish` bez `build` (stary dist), brak eksportu w `src/index.ts` (`is not a
function` w projekcie), `pnpm add` przy działającym dev.
### 8.2 package.json pluginu
- `"files": ["dist", "docs"]` — **docs jadą w pakiecie**; agenci w projektach
czytają `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md`. Bez `docs` nie mają nic.
- Jeden blok `exports`, wszystkie ścieżki na `./dist/` (nie `./src/`).
- `payload`, `@payloadcms/*`, `next`, `react`, `react-dom` → **`peerDependencies`**
(w `dependencies` = druga kopia = hooki bez kontekstu).
- Brak self-reference (nigdy `pnpm add` w katalogu pluginu).
- Plugin nigdy nie importuje `next/server`, `next/cache`, `@payload-config` ani
opcjonalnych pakietów wprost — projekt je wstrzykuje (wzorzec `NextResponse`,
`revalidatePath`, `payloadTotp`).
```bash
grep -c '"exports"' package.json # 1
grep -c "git+https.*ipal-kit" package.json # 0
grep '"import"' package.json | head -1 # ./dist/
```
### 8.3 Token do publikacji
Gitea → Settings → Applications → token z `write:package`, w **globalnym**
`.npmrc` (`~/.npmrc`, Windows `%USERPROFILE%\.npmrc`):
```
//git.intecion.net/api/packages/IntecionSoftware/npm/:_authToken=${GITEA_TOKEN}
```
### 8.4 Weryfikacja po publikacji
```bash
pnpm store prune
pnpm add @intecion/ipal-kit
node -e "console.log(require.resolve('@intecion/ipal-kit/next/middleware'))" # → dist/…
ls node_modules/@intecion/ipal-kit/docs/agent/AGENT.md
```
| Objaw | Przyczyna |
|---|---|
| `Cannot find module …/src/…ts` | `exports` wskazuje `src` |
| „Module not found” mimo pliku | dwa bloki `exports` |
| `ENOENT …ipal-kit.tgz` | self-reference w `dependencies` |
| stary kod mimo reinstalacji | nie podniesiona wersja; `pnpm store prune` + `rm -rf .next node_modules/@intecion` |
Wersje: 1.x = Payload 3. Przejście na Payload 4 → ipal-kit 2.0.
---
## 9. GIT I GITEA (`git.intecion.net`)
### 9.1 Dostęp (raz)
**HTTPS + token:** Gitea → Settings → Applications → token `write:repository`.
Przy `clone`/`push`: login z Gitea, jako hasło **token** (hasło konta nie działa).
Zapamiętanie: macOS `git config --global credential.helper osxkeychain`, Windows
`… manager`, Linux `… 'cache --timeout=3600'`.
**SSH:** `ssh-keygen -t ed25519 -C "[email protected]"`, klucz publiczny do Gitea →
Settings → SSH / GPG Keys, test `ssh -T -p 22222 [email protected]`.
```bash
git clone https://git.intecion.net/IntecionSoftware/<projekt>.git
git clone ssh://[email protected]:22222/IntecionSoftware/<projekt>.git
```
### 9.2 Codziennie
```bash
git pull # przed pracą i przed push
git checkout -b <funkcja> # praca na branchu
git add . && git commit -m "co i po co"
git push -u origin <funkcja> # potem Pull Request do main w Gitea
```
Nigdy `git push --force` na `main` (tylko na własnym branchu).
### 9.3 Kilka projektów
Każdy projekt to osobny katalog i repo (`~/projekty/klient-a`, `~/projekty/ipal-kit`).
Git działa na katalogu, w którym jesteś — po `cd` zawsze `git status` i
`git remote -v`, zanim cokolwiek wypchniesz.
### 9.4 Błędy
| Komunikat | Naprawa |
|---|---|
| `Permission denied (publickey)` | klucz nie dodany w Gitea albo zły port (`-p 22222`) |
| `Unauthorized` / pytanie o hasło w kółko | użyj tokenu zamiast hasła; zakres `write:repository` |
| `non-fast-forward`, „tip … is behind” | `git pull`, rozwiąż konflikty, `git push` |
| `repository not found` | zły adres albo brak dostępu do repo |
| 404 przy `pnpm add @intecion/…` | brak linii `@intecion:registry` w `.npmrc` projektu |
-116
View File
@@ -1,116 +0,0 @@
# Wydawanie nowej wersji
> **Instalacja jest publiczna** — rejestr Gitea pozwala pobierać pakiety bez
> tokenu. Ten plik dotyczy **publikowania** nowych wersji, co wymaga tokenu
> `write:package`. Instrukcja instalacji: główny [README](../README.md).
Dla osób rozwijających samą wtyczkę. Instalacja (dla użytkowników) jest w głównym
[README](../README.md) — ten plik dotyczy publikowania kolejnych wersji do
rejestru Gitea.
## package.json — co musi się zgadzać
Przed pierwszą publikacją sprawdź, że manifest jest poprawny — te pola były
źródłem większości problemów przy dystrybucji:
```json
{
"name": "@intecion/ipal-kit",
"version": "1.0.0",
"files": ["dist"],
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": { "...": "wszystkie subpath na ./dist/*.js i ./dist/*.d.ts" },
"publishConfig": {
"registry": "https://git.intecion.net/api/packages/IntecionSoftware/npm/"
}
}
```
Kontrola przed publikacją:
```bash
grep -c '"exports"' package.json # 1 — jeden blok, nie dwa
grep -c "git+https.*ipal-kit" package.json # 0 — brak self-reference
grep '"import"' package.json | head -1 # ./dist/ — nie ./src/
node -e "JSON.parse(require('fs').readFileSync('package.json','utf8'))" # bez błędu
```
- **`exports` na `dist`, nie `src`** — jeden blok, wszystkie ścieżki na `./dist/`.
- **jeden blok `exports`** — nie zostawiaj drugiego (np. w starym
`publishConfig.exports`); dwa bloki rozjeżdżają rozwiązywanie modułów.
- **brak self-reference** — pakiet nie może mieć siebie w `dependencies`.
Wchodzi, gdy odpalisz `pnpm add` w katalogu wtyczki — **nigdy tego nie rób**.
- **peer, nie dependencies** — `payload`, `next`, `react`,
`@payloadcms/plugin-seo`, `@payloadcms/plugin-form-builder` w
`peerDependencies`. W `dependencies` inaczej zaciągną drugą kopię Payloada.
## Rejestr — droga zalecana
Rejestr npm w Gitea. Pracownicy pobierają gotowy `dist`, nie budują u siebie.
**Token** z zakresem `write:package` (Gitea → Settings → Applications), w
globalnym `.npmrc` (ścieżka zależna od systemu — patrz tabela w głównym
[README](../README.md#route-a--from-the-registry-recommended); na Windows to
`%USERPROFILE%\.npmrc`):
```
//git.intecion.net/api/packages/IntecionSoftware/npm/:_authToken=${GITEA_TOKEN}
```
**Wydanie:**
```bash
pnpm clean && pnpm build
npm version patch # 1.0.0 → 1.0.1 (minor/major wg zmian)
npm publish
```
Podnoś wersję przy każdym wydaniu — pnpm rozpoznaje pakiet po numerze, więc nowy
numer znosi cały cykl czyszczenia pamięci podręcznej, który męczy przy
zostawaniu na jednej wersji.
## Alternatywa — dystrybucja z repozytorium (bez rejestru)
Jeśli nie publikujesz do rejestru, a instalujesz bezpośrednio z Gitea
(`git+https://...`), obowiązują dodatkowe reguły:
- **`dist/` musi być zacommitowany** w repozytorium — instalacja z git nie
buduje pakietu. Buduj i commituj `dist` przed każdym wydaniem:
```bash
pnpm build
git add -f dist/ # -f, jeśli .gitignore normalnie ignoruje dist
git commit -m "build dist"
git push
```
- **BRAK `prepare: pnpm build`** w package.json — inaczej pnpm próbuje budować
przy instalacji i żąda `onlyBuiltDependencies`.
- **sprawdzaj repozytorium, nie plik lokalny** — pnpm z git bierze stan repo:
```bash
git show origin/main:package.json | grep '"import"' | head -1 # ./dist/
```
Commit z nazwą „fix" nie znaczy, że poprawka jest w commicie.
## Weryfikacja po publikacji
W czystym projekcie testowym:
```bash
pnpm store prune
pnpm add @intecion/ipal-kit # albo git+https://... dla drogi repo
node -e "console.log(require.resolve('@intecion/ipal-kit/next/middleware'))"
```
Ostatnia komenda ma wypisać ścieżkę do `dist/exports/next-middleware.js` — nie
błąd. Jeśli pokazuje `src/...ts`, główny `exports` wskazuje źródła zamiast builda.
## Diagnostyka
| Objaw | Przyczyna |
|---|---|
| `Cannot find module .../src/...ts` | główny `exports` na `src`; przy instalacji z git `publishConfig` jest ignorowane |
| Turbopack „Module not found" mimo pliku na dysku | dwa bloki `exports`; Node bierze zły |
| `ENOENT ...ipal-kit.tgz` | self-reference w `dependencies` |
| `ERR_PNPM_GIT_DEP_PREPARE_NOT_ALLOWED` | `prepare` w package.json (droga repo) |
| stary kod mimo reinstall | pamięć podręczna; podnieś wersję albo `pnpm store prune` + `rm -rf .next node_modules/@intecion` |
+388
View File
@@ -0,0 +1,388 @@
# vibe.md — polecenia dla AI, krok po kroku
> **Dla kogo:** osoba, która buduje projekt klienta, prowadząc agenta AI
> (Antigravity, Claude Code, Cursor). Tu są **gotowe polecenia do wklejenia**, w
> kolejności, moduł po module. Reguły, których agent ma się trzymać, są w
> [AGENT.md](../agent/AGENT.md); proces dla człowieka w [PROGRAMISTA.md](./PROGRAMISTA.md).
---
## Jak pracować z agentem (przeczytaj raz)
1. **Jeden krok = jedno polecenie = jeden commit.** Nie wklejaj trzech kroków
naraz. Agent, który robi wszystko jednocześnie, gubi reguły.
2. **Najpierw plan, potem kod.** Każde polecenie kończy się prośbą o plan; kod
dopiero po Twoim „OK”. Plan sprawdzasz w 30 sekund, zły kod poprawiasz godzinę.
3. **Każdy krok kończy się dowodem:** wynik `pnpm build` i kontroli z AGENT.md §11.
„Gotowe” bez wyniku komend = nie gotowe.
4. **Nowa rozmowa co kilka kroków.** Długi kontekst rozmywa reguły. Każda nowa
rozmowa zaczyna się od **Polecenia 0**.
5. **Wartości w `<…>` uzupełniasz Ty** przed wklejeniem.
6. Gdy agent łamie regułę — użyj poleceń naprawczych z końca pliku, nie tłumacz
od nowa.
**Skille zamiast długich poleceń.** Gdy w projekcie są skille ipal-kit
(`pnpm ipal:skills`, AGENT.md §14), większość kroków to jedno krótkie
polecenie, np. `/ipal-block Hero — <opis/zrzut>`. Polecenia poniżej działają
też bez skilli; przy krokach podana jest wersja skrótowa.
**Prefiks do każdego polecenia** (wklej na początku, jeśli agent nie czyta
`AGENTS.md` sam):
```
Pracujesz zgodnie z node_modules/@intecion/ipal-kit/docs/agent/AGENT.md i AGENTS.md projektu.
Najpierw plan (pliki do utworzenia/zmiany + co w nich), czekaj na moje OK, potem kod.
Na końcu pokaż wynik pnpm build i kontroli z AGENT.md §11.
```
---
## KROK 0 — Kontekst (początek każdej nowej rozmowy)
```
Przeczytaj w całości node_modules/@intecion/ipal-kit/docs/agent/AGENT.md oraz AGENTS.md
w roocie projektu. Nie pisz jeszcze kodu.
Odpowiedz w 10 punktach, jakie zasady z AGENT.md są dla tego projektu
najważniejsze, i wypisz, na którym kroku z node_modules/@intecion/ipal-kit/docs/dev/vibe.md jesteśmy
(sprawdź stan repo: git log, istniejące pliki).
```
Sprawdź: agent wymienia m.in. proxy.ts zamiast middleware, zakaz hardkodowania,
linksField/CMSLink, minimum kolekcji. Jeśli nie — każ mu przeczytać jeszcze raz.
---
## KROK 1 — Szkielet i instalacja
Skrót: `/ipal-setup` (prowadzi przez kroki 1–8, etap po etapie).
```
Postaw nowy projekt Payload 3 + Next 16 zgodnie z PROGRAMISTA.md §1 i §2.1:
- .npmrc z rejestrem @intecion,
- @intecion/ipal-kit + zależności z PROGRAMISTA.md §1 (w tym @clocklimited/payload-2fa),
- pnpm.overrides na 3.90.2 dla payload i wszystkich @payloadcms/*,
- skrypt build z --webpack,
- usuń starter (frontend)/layout.tsx i page.tsx,
- .env.example z PROGRAMISTA.md §3 (bez wartości), .env w .gitignore.
Baza: <postgres|mongo>. NIE twórz middleware.ts.
Plan najpierw.
```
Sprawdź: `pnpm install` bez błędów, brak `middleware.ts`, `.npmrc` w repo.
---
## KROK 2 — AGENTS.md projektu
```
Utwórz AGENTS.md w roocie wg szablonu z AGENT.md §13. Dane:
klient <nazwa>, domena <domena>, rynek <PL/AU/…>, branża <…>,
języki <pl, en, …> (domyślny <pl>), media <R2/lokalne>, email <SMTP/Graph>.
Ustalenia projektu: <np. „blog z kategoriami”, „404 = osobna strona”, „bez sklepu”>.
Nie kopiuj reguł z AGENT.md — tylko odnośnik.
```
---
## KROK 3 — Konfiguracja: i18n + payload.config
```
Zrób src/i18n.config.ts (as const satisfies I18nConfig) z językami <…>
i payload.config.ts wg PROGRAMISTA.md §2.3:
ipalKit z i18n, access, pages (slug 'pages'), seo, forms,
twoFactor z WSTRZYKNIĘTYM payloadTotp (issuer: '<nazwa klienta>'), whiteLabel: true,
email: mailAdapter(). Kolekcji treści jeszcze nie dodawaj.
Plan najpierw.
```
Sprawdź: lista języków istnieje tylko w `i18n.config.ts` (grep `'pl'` w `src`).
---
## KROK 4 — Kolekcje rdzenia + wspólne pola
```
Zrób zgodnie z AGENT.md §5.3 i §6.2:
1. src/fields/link.ts, sectionHeader.ts, sectionSettings.ts — kod 1:1 z AGENT.md §6.2.
2. collections/Media.ts: upload (mimeTypes obrazy + PDF + mp4), alt required localized,
normalizeFilenameHook; jeśli R2 — buildR2Storage(['media']) z env (storage.md).
3. collections/Pages.ts: title localized, buildSlugField, buildNoindexField,
layout typu blocks (na razie jeden blok Content: sectionHeaderField + content richText),
trackSlugHistoryHook, buildRevalidateHook (hooks.md).
NIE twórz kolekcji users, settings, navigation ani żadnych innych.
Potem pnpm generate:types i payload generate:importmap.
Plan najpierw.
```
Sprawdź: w `collections/` są tylko `Pages.ts` i `Media.ts`; w `payload-types.ts`
są typy `CmsLink`, `SectionHeaderData`, `SectionSettings`.
---
## KROK 5 — Design tokeny i prymitywy UI
Wcześniej: `/impeccable init` i `/impeccable document` → `PRODUCT.md`, `DESIGN.md`.
```
Na podstawie DESIGN.md zrób src/app/(frontend)/styles.css wg AGENT.md §6.11:
@theme z tokenami (primary, background, foreground, muted + fonty), @source na plugin,
mapowanie --ipal-primary / --ipal-radius. Fonty przez next/font.
Potem prymitywy 1:1 z AGENT.md §6.3: lib/links.ts, components/ui/CMSLink.tsx,
Button.tsx, Media.tsx, Section.tsx, SectionHeader.tsx, oraz components/icons wg §6.10.
Zero hexów w komponentach — tylko tokeny.
Plan najpierw.
```
---
## KROK 6 — Routing, layout, strony
```
Zrób zgodnie z PROGRAMISTA.md §2.6–2.8 i AGENT.md §4:
- src/proxy.ts z createProxy, matcher jako literał inline,
- src/lib/content.ts z createContentHelpers (w tym getNotFoundPage, generateStaticParams),
- app/(frontend)/[locale]/layout.tsx: BEZ <head>, MediaPreconnect w body,
ConsentProvider + CookieBanner + CookieButton + Analytics wewnątrz providera,
- [locale]/[[...slug]]/page.tsx: revalidate, generateStaticParams, BEZ searchParams,
resolveRedirect przed notFound, enhanceProps wstrzykuje locale do bloków,
- [locale]/not-found.tsx z getNotFoundPage (pages.md).
Plan najpierw.
```
Sprawdź: `/` → `/<domyślny język>`; `pnpm build` pokazuje strony jako `●`;
`grep -rn "<head" src/app` = 0.
---
## KROK 7 — SEO, trasy systemowe, bezpieczeństwo
```
Zrób wg PROGRAMISTA.md §2.8–2.9 i seo.md:
- app/sitemap.ts, robots.ts, manifest.ts (createManifestHandler), llms.txt/route.ts,
api/health/route.ts — każda trasa czytająca bazę z export const dynamic = 'force-dynamic',
- next.config.ts: htmlLimitedBots, buildSecurityHeaders,
- metadata strony przez createPageMetadata, favicon przez buildIconsMetadata,
- JSON-LD w root layoucie: Organization + WebSite (seo.md) z danych z panelu,
- src/instrumentation.ts z assertEnv(ipalEnvRules(...)) (env.md).
CSP jeszcze nie — będzie w kroku 14.
Plan najpierw.
```
Sprawdź: `curl -A "Googlebot" http://localhost:3000/pl | grep canonical` — w `<head>`.
---
## KROK 8 — Header, Footer, dane firmy
Skrót: `/ipal-nav <pozycje menu, kolumny stopki, rynek>`.
```
Zrób wg AGENT.md §6.8:
- globals/Header.ts, Footer.ts (kod z §6.8),
- globals/Company.ts dla rynku <PL/AU/…>: nazwa, adres, <NIP/ABN/…>, telefon, email —
wszystko localized tam, gdzie tekst,
- lib/navigation.ts (resolveNav), components/layout/Header.tsx, Footer.tsx, MobileNav.tsx,
- linki prawne w stopce z ról System Pages, NIE ręcznie,
- hook afterChange na globalach z revalidatePath('/', 'layout').
Podepnij w [locale]/layout.tsx. Etykiety a11y z panelu.
Plan najpierw.
```
---
## KROK 9 — Bloki (powtarzaj dla każdej sekcji)
Jedna sekcja = jedno polecenie. Najpierw lista, potem po kolei.
**9a. Lista bloków z projektu graficznego:**
```
Oto projekt strony: <link / zrzuty / opis sekcji>.
Wypisz listę bloków do zbudowania (slug camelCase, nazwa, pola wg słownictwa
AGENT.md §6.5, które sekcje to ten sam blok z innym wariantem).
Cel: jak najmniej bloków, każdy wielokrotnego użytku. Nie pisz kodu.
```
**9b. Jeden blok:**
Skrót: `/ipal-block <Nazwa> — <pola z 9a>, <opis wyglądu / zrzut>`.
```
Zbuduj blok <nazwa> wg AGENT.md §6 (warstwa 3):
- src/blocks/<Nazwa>/config.ts: sectionHeaderField, linksField, media, items,
sectionSettingsField — tylko pola z listy z kroku 9a, nazwy z §6.5,
- Component.tsx: Section + SectionHeader + Media + CMSLink, max ~80 linii JSX,
powtarzalne elementy w <Nazwa>Card.tsx, interakcja w osobnym pliku 'use client' (§6.9),
- dodaj do Pages.layout i do blocks/registry.ts,
- pnpm generate:types, typy propsów z @/payload-types.
Wygląd: <opis / zrzut>. Zero tekstów, linków i hexów w kodzie.
Plan najpierw.
```
Sprawdź kontrolami z AGENT.md §11 (grep na `ctaLabel`, `href="/`, `<img`, długość pliku).
---
## KROK 10 — Formularze, Turnstile, email
```
Zrób wg forms.md, turnstile.md, email.md:
- blok formularza korzystający z form-buildera pluginu (pola i teksty z panelu),
- logika przez useForm/useContactForm z @intecion/ipal-kit/client — bez ręcznego useState,
- checkbox consent (zgoda RODO) z linkiem do polityki przez getSystemPagePath,
- TurnstileProvider w layoucie, turnstileSiteKey do bloku przez enhanceProps,
- honeypot, zdarzenie form_submit (formAnalyticsOnSuccess).
Plan najpierw.
```
Sprawdź: panel → Site Integrations → Send test; wysłanie formularza bez zgody → odrzucone.
---
## KROK 11 — Zgoda cookies i analityka
```
Zweryfikuj i dokończ wg consent.md i analytics.md:
- Analytics wewnątrz ConsentProvider, ID tylko z Site Integrations,
- czy włączyć defer (Core Web Vitals) — <tak/nie>,
- Meta Pixel: <w panelu | w GTM> (nigdy oba),
- link do polityki w banerze: automatyczny (bez parametru privacyPolicy w kodzie).
Pokaż, jak sprawdzić w Network, że przed zgodą nic nie ładuje się do
facebook.net / clarity.ms / google-analytics.
```
---
## KROK 12 — Kolekcje treści (tylko gdy klient wymaga)
Skrót: `/ipal-collection <czego klient potrzebuje>`.
```
Klient potrzebuje: <blog / realizacje / produkty>. Zrób test z AGENT.md §5.3
i potwierdź, że to kolekcja. Potem wg content.md i §5.4:
- collections/<Nazwa>.ts: title, buildSlugField, tab SEO, buildNoindexField,
trackSlugHistoryHook, setPublishedAtHook (blog), relacje <…>,
- content.config.ts z { slug, perPage } — prefiks URL z panelu (archiwum), NIE w kodzie,
- blok listy wpisów (EntriesList) + strona wpisu, JSON-LD Article (seo.md).
Plan najpierw.
```
---
## KROK 13 — Hooki i redirecty
```
Sprawdź wg hooks.md, że są wpięte:
buildRevalidateHook (Pages + kolekcje treści + globale), trackSlugHistoryHook + resolveRedirect,
buildCrossLocaleFieldSync (języki z configu), buildPreventDeleteSystemPage, buildValidateUniqueRole.
Pokaż test: zmień slug strony → stary URL daje 308 na nowy.
```
---
## KROK 14 — CSP i panel
```
Wg security.md: buildCsp w trybie report-only z flagami <turnstile, analytics, youtube, r2Url>.
Wypisz, co trzeba sprawdzić w konsoli przeglądarki, zanim przełączymy na enforce.
Sprawdź white-label panelu (logo, nazwa, credit Intecion) i 2FA dla wszystkich.
Opcjonalnie adminRoute '<ścieżka>' z przeniesieniem folderu.
```
---
## KROK 15 — Wygląd (Impeccable)
Osobne narzędzie, po kroku 9 dla gotowych bloków:
```
/impeccable polish <strona/sekcja>
```
Po każdym przebiegu Impeccable — polecenie dla agenta:
```
Sprawdź zmiany Impeccable kontrolami z AGENT.md §11. Czy pojawił się tekst w JSX,
hex zamiast tokenu, nowe pole o zakazanej nazwie albo plik >80 linii JSX? Popraw.
```
---
## KROK 16 — Audyt przed oddaniem
Skrót: `/ipal-audit` (skrypt), potem test redaktora i compliance ręcznie.
```
Zrób pełny audyt projektu:
1. Wszystkie kontrole z AGENT.md §11 — pokaż wyniki komend.
2. Test redaktora z AGENT.md §11 — dla każdego punktu wskaż, gdzie w panelu to się zmienia.
3. Checklist compliance z PROGRAMISTA.md §5.
4. pnpm build — trasy ● czy ƒ?
Wypisz listę problemów z priorytetem. Niczego jeszcze nie poprawiaj.
```
Potem poprawki po jednej, każda osobnym poleceniem.
---
## KROK 17 — Wdrożenie
Robisz Ty, wg PROGRAMISTA.md §4. Agentowi możesz dać:
```
Przygotuj listę zmiennych do Coolify dla tego projektu (PROGRAMISTA.md §3)
i checklistę §4.1 i §4.5 wypełnioną dla tego projektu. Bez wartości sekretów.
```
---
## POLECENIA NAPRAWCZE (gdy agent zbacza)
**Hardkod / tekst w kodzie:**
```
Stop. To łamie AGENT.md §2. Każdy tekst, link, obraz i plik idzie z panelu.
Przenieś <co> do pola w <bloku/globalu> i pokaż diff.
```
**Zoo pól CTA / sekcja-monolit:**
```
Stop. AGENT.md §6.5–6.6: CTA = linksField() + CMSLink, obraz = media + Media,
max ~80 linii JSX. Zrefaktoruj <blok> wg §6.7. Jeśli w bazie jest treść — najpierw migracja.
```
**Agent pisze coś, co ma plugin:**
```
Stop. Sprawdź w node_modules/@intecion/ipal-kit/docs i dist/*.d.ts, czy plugin
już to ma (AGENT.md §1.1, §7). Jeśli ma — usuń swój kod i użyj pluginu.
```
**Pluginowi czegoś brakuje / plugin ma błąd:**
Skrót: `/ipal-plugin-gap <co nie działa>`.
```
Nie łataj w projekcie. Przygotuj raport wg AGENT.md §1.3: problem, proponowane API,
dlaczego uniwersalne. Do czasu poprawki w pluginie zostaw TODO z odnośnikiem do raportu.
```
**Nowa kolekcja, której nie zamawiałeś:**
```
Stop. AGENT.md §5.3 — minimum kolekcji. Przejdź test 4 pytań dla <kolekcja>.
Jeśli to blok albo global — przerób.
```
**„Gotowe” bez dowodu:**
```
Uruchom /ipal-audit (bez --quick) i pokaż pełny wynik. Bez tego krok nie jest skończony.
```
**Agent zgubił reguły (długa rozmowa):**
```
Przeczytaj ponownie node_modules/@intecion/ipal-kit/docs/agent/AGENT.md w całości
i sprawdź swoje ostatnie zmiany pod kątem §0 (kompas). Wypisz naruszenia.
```
---
## ISTNIEJĄCY PROJEKT — aktualizacja do najnowszego ipal-kit
Skrót: `/ipal-upgrade`.
```
Zaktualizuj @intecion/ipal-kit do najnowszej wersji. Potem przejdź tabelę
z PROGRAMISTA.md §6 pozycja po pozycji: dla każdej sprawdź, czy dotyczy projektu
(pokaż dowód: grep / plik), i wypisz listę do zrobienia. Nie zmieniaj jeszcze kodu.
```
Potem jedna pozycja z listy = jedno polecenie:
```
Zrób pozycję <nr> z PROGRAMISTA.md §6 wg wskazanego pliku docs. Usuń lokalną
wersję, którą zastępuje plugin. Plan najpierw, na końcu pnpm build.
```
+1 -1
View File
@@ -4,7 +4,7 @@
WSZYSTKIMI brakami naraz — zamiast kryptograficznego crashu gdzieś w połowie
builda (`getaddrinfo ENOTFOUND`) albo runtime'u. Fail fast.
Powiązane: [deployment.md](./deployment.md), [storage.md](./storage.md),
Powiązane: [PROGRAMISTA.md §3–4](./PROGRAMISTA.md), [storage.md](./storage.md),
[forms.md](./forms.md).
## Dlaczego bez zod
-245
View File
@@ -1,245 +0,0 @@
# Frontend — wymagane implementacje
Co projekt klienta musi zrobić na froncie, żeby plugin działał. Zebrane z
realnego wdrożenia (ipal-test). W przyszłości → pełny poradnik "first setup".
## Wymagania środowiska
### Tailwind CSS (WYMÓG)
Komponenty pluginu (CookieBanner, Turnstile widget, i inne) są w czystym
Tailwind. Klient MUSI mieć Tailwind + skanować pakiet pluginu:
```bash
pnpm add tailwindcss @tailwindcss/postcss # v4
```
`postcss.config.mjs` (root):
```js
export default { plugins: { '@tailwindcss/postcss': {} } }
```
W globalnym CSS (np. app/(frontend)/styles.css):
```css
@import "tailwindcss";
@source "../../../node_modules/@intecion/ipal-kit/dist/**/*.js";
```
**@source jest kluczowy** — Tailwind domyślnie NIE skanuje node_modules, więc
bez tego klasy komponentów pluginu się nie wygenerują (komponenty renderują
się bez stylów). Ścieżka relatywna do pliku CSS.
### Przestylowanie pod klienta
Komponenty pluginu (CookieBanner, CookieButton) mają domyślny wygląd i działają
bez konfiguracji. Kolory/zaokrąglenia przez CSS custom properties z fallbackami
— nadpisz w swoim CSS:
```css
:root {
--ipal-primary: #16a34a;
--ipal-radius: 1rem;
}
```
Pełna lista tokenów + opcja classNames (gdy tokeny nie starczą): docs/consent.md.
Bloki są Twoje — plugin ich nie stylizuje, RenderBlocks nie dodaje markupu.
### Wymagane zależności (transitive)
Instalacja z npm zaciąga automatycznie. Przy lokalnym tarballu doinstaluj:
```
@payloadcms/plugin-seo @payloadcms/plugin-form-builder nodemailer
lucide-react slugify server-only
```
### Spójność wersji @payloadcms/*
pnpm.overrides wymuszające jedną wersję (patrz README).
### generate:importmap
Po wpięciu pluginu: `pnpm payload generate:importmap` (dla pól SEO w adminie).
## Struktura tras (lokalizacja)
```
src/app/(frontend)/
layout.tsx # root (<html><body>) — istniejący
[locale]/
layout.tsx # walidacja locale + ConsentProvider
[[...slug]]/
page.tsx # render strony (bloki)
```
**[[...slug]] MUSI być podwójny nawias** (opcjonalny catch-all):
- `[slug]` → string (błąd `slug.join is not a function`)
- `[[...slug]]` → tablica (poprawne), łapie /pl (home) i /pl/o-nas jednym plikiem
## i18n — jedno źródło prawdy
Wydziel config locale do osobnego pliku, importuj wszędzie:
```ts
// src/i18n.config.ts
export const i18nConfig = {
defaultLocale: 'pl',
locales: [
{ code: 'pl', label: 'Polski' },
{ code: 'en', label: 'English' },
],
} as const // as const — inaczej TS: locales nie pasuje do niepustej tuple
```
Importuj w: payload.config (ipalKit({ i18n: i18nConfig })), proxy.ts.
Layout może czytać locale z payload config (config.localization.locales) —
też jedno źródło.
## Proxy (dawniej middleware)
> **Next 16:** konwencja `middleware.ts` jest deprecated na rzecz `proxy.ts`
> (plik `proxy.ts`, funkcja `export function proxy`). Logika pluginu bez zmian —
> `createLocaleMiddleware` działa tak samo, zmienia się tylko nazwa pliku i
> funkcji po stronie projektu. Migracja jedną komendą:
> `npx @next/codemod@canary middleware-to-proxy .`
```ts
// src/proxy.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { createLocaleMiddleware } from '@intecion/ipal-kit/next/middleware'
import { i18nConfig } from '@/i18n.config'
const localeMiddleware = createLocaleMiddleware({ config: i18nConfig })
export function proxy(request: NextRequest) {
const result = localeMiddleware(request)
if (result.type === 'next') return NextResponse.next()
const response = NextResponse.redirect(result.location)
// cookie tylko gdy jest zgoda na kategorię functional — inaczej undefined
if (result.cookie) response.cookies.set(result.cookie.name, result.cookie.value)
return response
}
// matcher MUSI być inline (Next analizuje statycznie, nie wykonuje importów —
// import DEFAULT_MIDDLEWARE_MATCHER byłby zignorowany → proxy łapie
// /admin /_next /api → 500)
export const config = {
matcher: ['/((?!api|admin|_next|.*\\..*).*)'],
}
```
## Rozwiązywanie strony (page.tsx)
- brak slug (/pl) → home przez System Pages (settings.homepage), NIE hardkod slug
- slug (/pl/o-nas) → payload.find by slug w danym locale
- depth: 2 → żeby relacje w blokach (form) się populowały
## Consent (layout [locale])
Layout (server) czyta getConsentTexts, przekazuje jako prop do ConsentProvider
(client). Banner + button renderują się same:
```ts
import { getConsentTexts } from '@intecion/ipal-kit'
import { ConsentProvider, CookieBanner, CookieButton } from '@intecion/ipal-kit/client'
const texts = await getConsentTexts({ config, locale, payload, privacyPolicy })
// <ConsentProvider texts={texts}>{children}<CookieBanner/><CookieButton/></ConsentProvider>
```
## Bloki (RenderBlocks)
Klient definiuje bloki (config + komponent) — plugin jest block-agnostic.
- `blocks/<Nazwa>/config.ts` — schemat Payload (Block)
- `blocks/<Nazwa>/Component.tsx` — komponent (dane bloku jako propsy)
- `blocks/registry.ts` — mapa blockType → komponent
- Pages: pole `layout` typu blocks z listą bloków
- page.tsx: `<RenderBlocks blocks={doc.layout} components={registry} />`
**Puste blocks: [] crashuje** (traverseFields) — zawsze z co najmniej jednym
blokiem.
enhanceProps — wstrzykiwanie server-side wartości do bloku bez wiedzy pluginu
(np. turnstileSiteKey, email do FormBlock):
```ts
const enhanceProps = ({ block }) => {
if (block.blockType === 'formBlock') return { turnstileSiteKey, notificationTo }
return {}
}
```
## Formularz (FormBlock)
- FormRenderer (client) — renderuje pola form-buildera (text/email/select/
country/checkbox/textarea/number/state/message)
- Turnstile widget (@intecion/ipal-kit/client) — siteKey jako prop, wstrzykiwany przez
enhanceProps (z SiteIntegrations, publiczny — bezpieczny na kliencie)
- server action → submitForm (@intecion/ipal-kit/server) — weryfikuje Turnstile i zapisuje
Maili NIE składa się w kodzie. Po zapisie submission form-builder sam wysyła
wiadomości skonfigurowane przez edytora (Forms → dany formularz → Emails:
Email To / CC / BCC / Subject / Message z placeholderami {{pole}}, {{*}},
{{*:table}}). Idą przez payload.sendEmail → panelSmtpAdapter → SMTP z panelu.
Wymaga w payload.config:
```ts
import { ipalKit, panelSmtpAdapter } from '@intecion/ipal-kit'
export default buildConfig({
email: panelSmtpAdapter(),
plugins: [ipalKit({ ... })],
})
```
Wymaga w SiteIntegrations: SMTP (host, port, user, password, from) + Turnstile.
Turnstile testowe klucze Cloudflare (zawsze pass):
site 1x00000000000000000000AA, secret 1x0000000000000000000000000000000AA.
Walidacja server-side (limit długości pól) w actions.ts — browserowy `required`
da się obejść wołając akcję bezpośrednio.
## Metadata (SEO na froncie)
createMetadataGenerator zwraca funkcję `({ payload, params, locale })` — Next
woła `generateMetadata({ params })` bez payload/locale, a plugin nigdy nie
wywołuje getPayload sam, więc klient opakowuje:
```ts
const generate = createMetadataGenerator({
config: i18nConfig,
baseUrl: process.env.NEXT_PUBLIC_SERVER_URL,
homeSlug: 'homepage', // home zwija się do /pl, nie /pl/homepage
resolveDocument: async ({ params, locale }) => { ... }, // locale: 'all'!
resolveSiteName: async ({ locale }) => { ... },
resolveImageUrl: async ({ doc }) => { ... },
})
export async function generateMetadata({ params }) {
const { locale, slug } = await params
const payload = await getPayload({ config: await config })
return generate({ payload, params: { slug: slug ?? [] }, locale })
}
```
resolveDocument MUSI pobrać dokument z `locale: 'all'` — wtedy `slug` jest mapą
locale→wartość, z której budowane są hreflang alternates. Zwykły fetch (jeden
locale) da tylko string i hreflang nie powstanie.
Next uruchamia generateMetadata i komponent strony niezależnie — bez React
cache() każde żądanie odpytuje bazę dwa razy o ten sam dokument.
## Analytics
W layoucie [locale], WEWNĄTRZ ConsentProvider (Analytics ustawia Consent Mode
ze stored choice, zanim załaduje tag):
```ts
const analytics = await getAnalyticsConfig(payload) // tylko publiczne GA4/GTM ID
// <ConsentProvider texts={texts}> ... <Analytics {...analytics} /> </ConsentProvider>
```
ID z SiteIntegrations. GTM ma priorytet nad GA4, gdy oba ustawione.
-527
View File
@@ -1,527 +0,0 @@
# Setup projektu — od zera do wdrożenia
Pełny przewodnik: od pustego katalogu do działającej, wielojęzycznej strony z
blokami, consentem, formularzem i SEO. Łączy szkielet projektu (kolejność
kroków) z wymaganiami frontendu (Tailwind, trasy, bloki, metadata).
> **Instalacja pluginu** (token Gitea, rejestr vs git) jest w głównym
> [README](../README.md). Ten przewodnik zakłada, że `@intecion/ipal-kit` jest
> zainstalowany, i przeprowadza przez konfigurację.
>
> **Zaczynasz wdrożenie produkcyjne?** Najpierw [WDROZENIE-PLAYBOOK.md](./WDROZENIE-PLAYBOOK.md)
> — zasady, procedura, pułapki.
Kolejność jest istotna — kilka kroków zależy od poprzednich (schemat bazy,
importMap, kolejność wpięcia). Zakłada: pnpm, Node 22, Next 16.
---
## 1. Szkielet Payloada
```bash
npx create-payload-app@latest moj-projekt
# → Blank, SQLite (dev) / Postgres (prod)
cd moj-projekt
```
## 2. Plugin i zależności
Zainstaluj `@intecion/ipal-kit` zgodnie z [README](../README.md). Dodaj
zależności współdzielone z Payloadem, których plugin nie zaciąga sam:
```bash
pnpm add @payloadcms/plugin-seo @payloadcms/plugin-form-builder \
nodemailer lucide-react slugify server-only
```
### Spójność wersji @payloadcms/* (KRYTYCZNE)
Wersje `@payloadcms/*` **muszą** zgadzać się z wersją `payload` — inaczej
zagnieżdżone pluginy się nie wpinają (pusty tab SEO, brak kolekcji Forms) albo
projekt się wywala. Wymuś w `package.json`:
```json
"pnpm": {
"overrides": {
"payload": "3.88.0",
"@payloadcms/ui": "3.88.0",
"@payloadcms/next": "3.88.0",
"@payloadcms/db-postgres": "3.88.0",
"@payloadcms/richtext-lexical": "3.88.0",
"@payloadcms/plugin-seo": "3.88.0",
"@payloadcms/plugin-form-builder": "3.88.0"
}
}
```
```bash
rm -rf node_modules pnpm-lock.yaml && pnpm install
```
### Build script z --webpack (Next 16)
Next 16 domyślnie Turbopack, który konfliktuje z withPayload. W `package.json`:
```json
"build": "cross-env NODE_OPTIONS=\"--max-old-space-size=3072\" next build --webpack"
```
## 3. Konfiguracja locale — jedno źródło
Proxy działa przed Payloadem i potrzebuje listy locale synchronicznie, więc nie
może jej czytać z gotowego configu. Wydziel osobny plik, importuj wszędzie:
```ts
// src/i18n.config.ts
export const i18nConfig = {
defaultLocale: 'pl',
locales: [
{ code: 'pl', label: 'Polski' },
{ code: 'en', label: 'English' },
],
} as const // as const — inaczej TS nie uzna locales za niepustą tuple
```
Importuj w: `payload.config` (ipalKit({ i18n: i18nConfig })) i `proxy.ts`.
## 4. payload.config.ts
```ts
import { ipalKit, mailAdapter } from '@intecion/ipal-kit'
import { i18nConfig } from '@/i18n.config'
import { Pages } from '@/collections/Pages'
export default buildConfig({
collections: [Users, Media, Pages],
// Dyspozytor email: czyta transport (SMTP/Graph) z panelu przy każdej wysyłce.
// Bez tego maile form-buildera nie wyjdą (Payload podstawia mocka).
email: mailAdapter(),
plugins: [
ipalKit({
i18n: i18nConfig,
access: { authCollection: 'users' },
pages: { slug: 'pages' },
seo: { collections: ['pages'] },
forms: { redirectRelationships: ['pages'] },
}),
],
})
```
## 5. Kolekcja Pages
```ts
// src/collections/Pages.ts
import type { CollectionConfig } from 'payload'
import { buildSlugField } from '@intecion/ipal-kit'
import { ContentBlock } from '@/blocks/Content/config'
export const Pages: CollectionConfig = {
slug: 'pages',
admin: { useAsTitle: 'title' },
access: { read: () => true },
fields: [
{ name: 'title', type: 'text', required: true, localized: true },
buildSlugField({ from: 'title' }), // NIGDY ręczny slug — plugin to ma
{
name: 'layout',
type: 'blocks',
blocks: [ContentBlock], // NIGDY pusta lista — Payload crashuje
},
],
}
```
## 6. Pierwszy blok
Bloki należą do projektu — plugin ich nie zna i nie stylizuje.
```ts
// src/blocks/Content/config.ts
import type { Block } from 'payload'
export const ContentBlock: Block = {
slug: 'content',
fields: [
{ name: 'heading', type: 'text', localized: true },
{ name: 'body', type: 'textarea', localized: true, required: true },
],
}
```
```tsx
// src/blocks/Content/Component.tsx
export function ContentBlockComponent({ heading, body }: { heading?: string; body?: string }) {
return (
<section className="mx-auto max-w-3xl px-4 py-12">
{heading && <h2 className="mb-4 text-2xl font-bold">{heading}</h2>}
{body && <p className="whitespace-pre-line leading-relaxed">{body}</p>}
</section>
)
}
```
```ts
// src/blocks/registry.ts
import type { BlockComponentMap } from '@intecion/ipal-kit/rsc'
import { ContentBlockComponent } from '@/blocks/Content/Component'
export const blockRegistry: BlockComponentMap = {
content: ContentBlockComponent, // klucz = slug bloku
}
```
> **Jak budować treść, żeby klient mógł wszystko edytować** (filozofia
> CMS, kolejność komponent→blok→strona): [architektura-tresci.md](./architektura-tresci.md).
**Puste `blocks: []` crashuje** (traverseFields) — zawsze co najmniej jeden blok.
### enhanceProps — wstrzykiwanie danych server-side do bloków
Bloki NIE importują `lib/*` (cykl importów). Wartości server-side (turnstileSiteKey,
odbiorca formularza) wstrzykuje się przez enhanceProps — bez wiedzy pluginu:
```ts
const enhanceProps = ({ block }) => {
if (block.blockType === 'formBlock') return { turnstileSiteKey, notificationTo }
return {}
}
```
## 7. Tailwind (WYMÓG)
Blank template go nie ma, a komponenty pluginu (banner cookies, Turnstile) są w
czystym Tailwindzie.
```bash
pnpm add tailwindcss @tailwindcss/postcss
```
```js
// postcss.config.mjs (root)
export default { plugins: { '@tailwindcss/postcss': {} } }
```
```css
/* src/app/(frontend)/styles.css — na górze */
@import "tailwindcss";
@source "../../../node_modules/@intecion/ipal-kit/dist/**/*.js";
```
**`@source` jest KONIECZNY** — Tailwind nie skanuje `node_modules`, więc bez
niego klasy komponentów pluginu nie powstaną (banner wyrenderuje się goły).
Ścieżka relatywna do pliku CSS.
### Przestylowanie pod klienta
Komponenty pluginu mają domyślny wygląd. Kolory/zaokrąglenia przez CSS custom
properties (fallbacki wbudowane):
```css
:root {
--ipal-primary: #16a34a;
--ipal-radius: 1rem;
}
```
Pełna lista tokenów + opcja classNames: [consent.md](./consent.md).
## 8. Proxy (routing locale) — NIGDY middleware.ts
> **Next 16 używa `proxy.ts`, NIE `middleware.ts`.** Plik `proxy.ts`, funkcja
> `proxy`. `middleware.ts` jest przestarzały — jeśli istnieje, USUŃ go. Nigdy
> obu naraz. Migracja starego: `npx @next/codemod@canary middleware-to-proxy .`
>
> Import z pluginu zostaje `@intecion/ipal-kit/next/middleware` — to nazwa
> subpath eksportu, NIE nazwa pliku. Nie myl ich.
```ts
// src/proxy.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { createLocaleMiddleware } from '@intecion/ipal-kit/next/middleware'
import { i18nConfig } from '@/i18n.config'
const localeMiddleware = createLocaleMiddleware({ config: i18nConfig })
export function proxy(request: NextRequest) {
const result = localeMiddleware(request)
// Cookie zapisywany w OBU wynikach (redirect na '/' i next przy zmianie
// języka), TYLKO gdy jest zgoda na functional.
const response =
result.type === 'next'
? NextResponse.next()
: NextResponse.redirect(result.location)
if (result.cookie) {
response.cookies.set(result.cookie.name, result.cookie.value)
}
return response
}
// Matcher INLINE (nie import) — Next analizuje statycznie, nie wykonuje importów.
// Import stałej byłby zignorowany → proxy złapałby /admin /_next /api → 500.
// Ten wzorzec łapie root '/' (negocjacja locale), pomija api/admin/_next/pliki.
export const config = {
matcher: ['/((?!api|admin|_next|.*\\..*).*)'],
}
```
### Zlokalizowane ścieżki — getLocalizedSlugs (NIGDY zaszyta mapa)
Do przełącznika języka / budowania ścieżek NIE twórz zaszytej mapy slugów.
Slugi są w bazie (pole `slug` localized):
```ts
import { getLocalizedSlugs, switchLocalePath } from '@intecion/ipal-kit'
const doc = await payload.findByID({ collection: 'pages', id, locale: 'all' })
const slugs = getLocalizedSlugs({ slugField: doc.slug, config: i18nConfig })
switchLocalePath({ slugs, targetLocale: 'en', config: i18nConfig }) // → '/en/about'
```
## 9. Warstwa dostępu do danych — lib/ (jedno źródło)
```ts
// src/lib/content.ts — JEDYNE źródło helperów pluginu
import { createContentHelpers } from '@intecion/ipal-kit'
import payloadConfig from '@/payload.config'
import { i18nConfig } from '@/i18n.config'
export const {
getCachedPayload, getSettings, getConfiguredLocales, resolveRoute, getEntries, robots,
} = createContentHelpers({
config: payloadConfig, // PAYLOAD config (nie i18n!)
content: { collections: [] },
i18n: i18nConfig, // i18n OSOBNO
})
```
```ts
// src/lib/payload.ts — funkcje projektu, typowane
import { cache } from 'react'
import { getSiteSettings } from '@intecion/ipal-kit'
import { getCachedPayload } from './content' // z content, nie osobny getPayload
import type { SiteSetting } from '@/payload-types'
export const getSettings = cache(async (locale: string) =>
getSiteSettings<SiteSetting>(await getCachedPayload(), { locale: locale as never, depth: 2 }),
)
```
> NIE twórz `lib/pages.ts` (resolvePage) ani `lib/locales.ts` — plugin ma
> `resolveRoute` i `getConfiguredLocales`. Duplikaty = rozjazd.
## 10. Trasy
Usuń starter — `(frontend)/layout.tsx` i `(frontend)/page.tsx`. Rootem zostaje
layout locale (bo `<html lang>` musi znać język).
```
src/app/(frontend)/
styles.css
[locale]/
layout.tsx # walidacja locale + ConsentProvider + Analytics
[[...slug]]/
page.tsx # render bloków
```
**`[[...slug]]` — PODWÓJNE nawiasy** (opcjonalny catch-all). Pojedyncze `[slug]`
dają string (`slug.join is not a function`) i nie łapią samego `/pl`.
```tsx
// src/app/(frontend)/[locale]/layout.tsx
import { notFound } from 'next/navigation'
import { getConsentTexts, getAnalyticsConfig } from '@intecion/ipal-kit'
import { ConsentProvider, CookieBanner, CookieButton, Analytics } from '@intecion/ipal-kit/client'
import { i18nConfig } from '@/i18n.config'
import { getCachedPayload, getConfiguredLocales } from '@/lib/content'
import { getSettings } from '@/lib/payload'
import '../styles.css'
export default async function LocaleLayout({ children, params }) {
const { locale } = await params
const locales = await getConfiguredLocales()
if (!locales.includes(locale)) notFound()
const payload = await getCachedPayload()
const settings = await getSettings(locale)
const privacyPage = (settings as { privacyPolicy?: unknown }).privacyPolicy
const [texts, analytics] = await Promise.all([
getConsentTexts({
config: i18nConfig, locale, payload,
privacyPolicy: privacyPage && typeof privacyPage === 'object'
? { page: privacyPage, label: 'Polityka prywatności' } : undefined,
}),
getAnalyticsConfig(payload),
])
return (
<html lang={locale}>
{/* BEZ jawnego <head>! Sztywny <head> wypycha metadata do <body>
(canonical/title poza head → crawlery ich nie widzą). Next zarządza
<head> sam; MediaPreconnect w body, React 19 hoistuje link do head. */}
<body>
<MediaPreconnect /> {/* preconnect CDN, jeśli R2 */}
<ConsentProvider texts={texts}>
<main>{children}</main>
<CookieBanner />
<CookieButton />
<Analytics {...analytics} /> {/* WEWNĄTRZ ConsentProvider */}
</ConsentProvider>
</body>
</html>
)
}
export async function generateStaticParams() {
const locales = await getConfiguredLocales()
return locales.map((locale) => ({ locale }))
}
```
```tsx
// src/app/(frontend)/[locale]/[[...slug]]/page.tsx
import { notFound } from 'next/navigation'
import type { Metadata } from 'next'
import { RenderBlocks } from '@intecion/ipal-kit/rsc'
import { createPageMetadata } from '@intecion/ipal-kit'
import { i18nConfig } from '@/i18n.config'
import { blockRegistry } from '@/blocks/registry'
import { getCachedPayload, resolveRoute } from '@/lib/content'
const pageMetadata = createPageMetadata({
config: i18nConfig,
baseUrl: process.env.NEXT_PUBLIC_SERVER_URL,
})
// ISR — cache strony z gotowym <head>. Eliminuje race condition streamingu
// metadata (canonical/title zawsze w head, nie w body). TTFB ~20ms, brak 503.
// Redaktor widzi zmiany po rewalidacji — patrz seo.md (ISR a treść z panelu).
export const revalidate = 3600
export async function generateMetadata({ params }): Promise<Metadata> {
const { locale, slug } = await params
return pageMetadata({ payload: await getCachedPayload(), locale, slug })
}
export default async function Page({ params, searchParams }) {
const { locale, slug } = await params
const { page } = await searchParams
const route = await resolveRoute(locale, slug ?? [], page) // 3 args
if (!route) notFound()
return <RenderBlocks blocks={route.doc.layout as never} components={blockRegistry} />
}
```
- brak slug (`/pl`) → home przez System Pages (nie hardkod slug)
- slug (`/pl/o-nas`) → resolveRoute po slug w danym locale
- **ISR (`revalidate`)** → metadata zawsze w `<head>` (nie body), szybki TTFB.
KRYTYCZNE dla SEO — patrz seo.md (metadata w head).
- `depth: 2` → relacje w blokach (form) się populują
## 11. Metadata / SEO (szczegóły)
`createPageMetadata` obsługuje hreflang. Kluczowe: resolveDocument pobiera
dokument z **`locale: 'all'`** — wtedy `slug` jest mapą locale→wartość, z której
budują się hreflang alternates. Zwykły fetch (jeden locale) → tylko string,
hreflang nie powstanie.
Bez `NEXT_PUBLIC_SERVER_URL` canonical i hreflang wyjdą względne.
## 12. Nagłówki bezpieczeństwa
```ts
// next.config.ts
import { buildSecurityHeaders } from '@intecion/ipal-kit'
const securityHeaders = buildSecurityHeaders({
hsts: process.env.NODE_ENV === 'production', // off w dev (http)
additional: [ /* CSP projektu — zna swoje domeny */ ],
})
// async headers() { return [{ source: '/:path*', headers: securityHeaders }] }
```
Szczegóły: [security.md](./security.md).
## 13. Środowisko
```bash
# .env
DATABASE_URI=<postgres albo file:./dev.db>
PAYLOAD_SECRET=<losowy-ciąg>
NEXT_PUBLIC_SERVER_URL=http://localhost:3000
# Email przez Graph (opcjonalnie — sekrety agencyjne):
# GRAPH_TENANT_ID=... GRAPH_CLIENT_ID=... GRAPH_CLIENT_SECRET=... GRAPH_SENDER=...
```
## 14. Generowanie i start
```bash
pnpm generate:types
pnpm payload generate:importmap # pola SEO + custom komponenty (MaskedField...)
pnpm dev
```
`generate:importmap` powtarzaj po każdej zmianie dokładającej komponenty admina.
## 15. Konfiguracja w panelu
`http://localhost:3000/admin`
1. **Utwórz pierwszego użytkownika** (rola admin).
2. **Site Settings → General** — nazwa witryny, tytuł.
3. **Pages** — strona główna. Tytuł **w każdym locale** (slug per język; pusty
slug EN = 404 na `/en/…`).
4. **Site Settings → System Pages** — wskaż Homepage (bez tego `/pl` → 404).
5. **Cookie Settings** — treść bannera per język.
6. **Notifications** — teksty wyników formularza per język (opcjonalne, ma fallback).
7. **Site Integrations → SMTP** — transport (SMTP/Graph), From Name, From Address.
Wejdź na `/` — powinno przekierować na `/pl`.
---
## Opcjonalne
### Formularz z Turnstile
Wymaga bloku formularza (patrz [forms.md](./forms.md)) + Site Integrations →
Turnstile (klucze testowe Cloudflare: site `1x00000000000000000000AA`, secret
`1x0000000000000000000000000000000AA`). Maile wysyła form-builder przez
mailAdapter — nie pisze się ich w kodzie. Zgoda RODO: checkbox o nazwie `consent`.
### Blog / archiwum
Pełny opis: [content.md](./content.md). Kolekcja + content.config.ts +
przypisanie strony-archiwum w System Pages.
### Sitemapa i robots
```ts
// app/sitemap.ts
export { sitemap as default } from '@/lib/content'
export const dynamic = 'force-dynamic' // KONIECZNE dla deployu kontenerowego
// app/robots.ts
export { robots as default } from '@/lib/content'
```
`force-dynamic` w sitemap.ts jest wymagane przy deployu w kontenerze (Coolify/
Docker) — bez niego build próbuje prerenderować sitemap i łączy się z bazą,
której kontener budujący nie widzi → build pada. Szczegóły: [deployment.md](./deployment.md).
---
## Kiedy coś nie działa
| Objaw | Przyczyna |
|---|---|
| Pusty tab SEO / brak Forms | rozjazd wersji `@payloadcms/*` — sprawdź `pnpm.overrides` |
| `PayloadComponent not found in importMap` | `pnpm payload generate:importmap` |
| `Cannot destructure property 'config'` (custom pole) | dublet `@payloadcms/ui` — peerDependency (playbook D) |
| Banner bez stylów | brak `@source` na node_modules albo brak Tailwinda |
| `/admin` i `/_next` → 500 | matcher w proxy nie jest inline |
| `slug.join is not a function` | `[slug]` zamiast `[[...slug]]` |
| `/pl` → 404 | Homepage nieustawiony w System Pages |
| `/en/*` → 404, `/pl/*` działa | pusty tytuł/slug w locale EN |
| `Missing <html> and <body>` | root layout usunięty, a `[locale]/layout.tsx` ich nie ma |
| Zmiany w pluginie nie widać | `rm -rf .next`; sprawdź czy wciągnięto wersję (grep node_modules) |
| Maile nie wychodzą | brak `email: mailAdapter()` albo pusty SMTP/Graph |
| istnieje `middleware.ts` | USUŃ — Next 16 to `proxy.ts` |
| zaszyta mapa `localizedRoutes` | antywzorzec — `getLocalizedSlugs` z bazy |
+1 -1
View File
@@ -3,7 +3,7 @@
Plugin dostarcza hooki, które zdejmują z projektów powtarzalną robotę. Wpinasz je
w kolekcje; działają automatycznie. Wszystkie gotowe do użycia (import z pluginu).
Powiązane: [pages.md](./pages.md), [seo.md](./seo.md), [wymagania-prawne.md](./wymagania-prawne.md).
Powiązane: [pages.md](./pages.md), [seo.md](./seo.md), [PROGRAMISTA.md §5](./PROGRAMISTA.md).
---
+11
View File
@@ -94,6 +94,17 @@ niżej.
> eksportu, niezależna od nazwy pliku projektu. Migracja:
> `npx @next/codemod@canary middleware-to-proxy .`
> **Zalecane (aktualne): `createProxy`** — robi negocjację locale, redirect
> roota, cookie języka za zgodą i nagłówki `x-locale` / `x-pathname`:
> ```ts
> import { NextResponse } from 'next/server'
> import { createProxy } from '@intecion/ipal-kit'
> import { i18nConfig } from '@/i18n.config'
> export const proxy = createProxy(i18nConfig, { NextResponse })
> export const config = { matcher: ['/((?!api|admin|_next|.*\\..*).*)'] }
> ```
> Ręczny wariant poniżej tylko gdy potrzebujesz własnej logiki w proxy.
```ts
// proxy.ts (projekt klienta) — jedyna logika to podłączenie
import { NextResponse } from 'next/server'
+49 -3
View File
@@ -1,7 +1,7 @@
# pages
System pages: centralne przypisanie ról (homepage / privacyPolicy /
cookiePolicy) do dokumentów z klienckiej kolekcji Pages, w SiteSettings.
System pages: centralne przypisanie ról (homepage / notFound / privacyPolicy /
cookiePolicy / termsOfService) do dokumentów z klienckiej kolekcji Pages, w SiteSettings.
Front rozwiązuje rolę na ścieżkę locale-aware.
## Config (payload.config.ts)
@@ -51,9 +51,55 @@ stopce / bannerze cookies bierzesz z `getSystemPagePath({ role: privacyPolicy })
```ts
import { ALL_SYSTEM_PAGE_ROLES } from '@intecion/ipal-kit'
// ['homepage', 'privacyPolicy', 'cookiePolicy']
// ['homepage', 'notFound', 'privacyPolicy', 'cookiePolicy', 'termsOfService']
```
## Strona 404 — wybierana w panelu (od 1.8.0)
Site Settings → System Pages → **404 (Not Found)**. Edytor wybiera:
- dedykowaną stronę „Nie znaleziono” (np. slug `strona-nie-znaleziona`), **albo**
- stronę główną (część klientów tak woli), **albo**
- nic → projekt pokazuje wbudowany fallback z `not-found.tsx`.
Projekt (`app/(frontend)/[locale]/not-found.tsx`) — gotowy przykład w
`frontend/[locale]/not-found.tsx`:
```tsx
import { headers } from 'next/headers'
import { getNotFoundPage } from '@/lib/content' // z createContentHelpers
export default async function NotFound() {
const locale = (await headers()).get('x-locale') ?? i18nConfig.defaultLocale
const page = await getNotFoundPage(locale) // null → fallback
if (page?.layout?.length) return <RenderBlocks blocks={page.layout} components={blockRegistry} />
return <Fallback404 locale={locale} />
}
```
`not-found.tsx` nie dostaje `params` — locale bierzemy z nagłówka `x-locale`,
który ustawia proxy z `createProxy`. Status HTTP zostaje **404** (renderuje go
Next po `notFound()`), treść jest z panelu.
Co plugin robi automatycznie z przypisaną stroną 404:
| Miejsce | Zachowanie |
|---|---|
| `resolveRoute` | bezpośrednie wejście na `/pl/strona-nie-znaleziona` → `null` → `notFound()` → prawdziwy 404 (bez soft-404 / duplikatu z kodem 200) |
| sitemap | wykluczona po ID (slug może być dowolny) |
| `generateStaticParams` | pominięta (nie jest osobnym URL-em) |
| `getNotFoundPage` / `resolveNotFoundPage` | nigdy nie rzuca — brak bazy w buildzie = fallback |
Gdy 404 = strona główna, nic z powyższego nie ukrywa strony głównej — dalej
działa pod `/{locale}` i jest w sitemapie; dodatkowo jej treść pokazuje się pod
nieznanymi URL-ami (z kodem 404).
Bez `createContentHelpers`: `resolveNotFoundPage({ payload, locale })` z
`@intecion/ipal-kit`.
Wskazówka: zaznacz na dedykowanej stronie 404 **noindex** — wtedy wypada też z
llms.txt i wyszukiwarki.
## KRYTYCZNE: generateStaticParams dla [[...slug]] (SEO + head)
Trasa `[[...slug]]` (opcjonalny catch-all) BEZ `generateStaticParams` jest przez
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@intecion/ipal-kit",
"version": "1.7.6",
"version": "1.7.12",
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
"license": "MIT",
"repository": {
@@ -43,7 +43,8 @@
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"files": [
"dist"
"dist",
"docs"
],
"scripts": {
"build": "pnpm copyfiles && pnpm build:types && pnpm build:swc",
+8 -1
View File
@@ -8,8 +8,15 @@ export {
} from '../modules/accessibility/client.js'
export type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js'
export { Analytics } from '../modules/analytics/client.js'
export { pushDataLayer } from '../modules/analytics/client.js'
export type { AnalyticsProps } from '../modules/analytics/client.js'
export { pushDataLayer } from '../modules/analytics/client.js'
export {
loadClarity,
loadLinkedIn,
loadMetaPixel,
loadTikTok,
} from '../modules/analytics/client.js'
/**
* Entry point: ipal-kit/client
*
+13 -3
View File
@@ -1,11 +1,12 @@
import type { Field } from 'payload'
import { CONSENT_CATEGORIES } from '../../modules/consent/index.js'
import { CONSENT_CATEGORIES } from '../../modules/consent/categories.js'
/**
* Fields for the CookieSettings global — GDPR consent banner copy, editable
* per locale. The privacy-policy link is NOT stored here: it comes from the
* pages module (system page role 'privacyPolicy'), keeping one source of truth.
* per locale. The privacy-policy link TARGET is NOT stored here: it comes from
* the pages module (system page role 'privacyPolicy'), keeping one source of
* truth. Only the link's visible text lives here (privacyLinkLabel).
*/
export const cookieSettingsFields: Field[] = [
{
@@ -24,6 +25,15 @@ export const cookieSettingsFields: Field[] = [
},
localized: true,
},
{
name: 'privacyLinkLabel',
type: 'text',
admin: {
description:
'Text of the privacy-policy link in the banner, e.g. "Privacy policy". The link target is the page assigned as Privacy Policy in Site Settings → System Pages. Empty → the page title is used.',
},
localized: true,
},
{
name: 'buttons',
type: 'group',
@@ -1,15 +1,16 @@
import type { Field } from 'payload'
/**
* Analytics configuration — GA4 measurement ID and GTM container ID.
* IDs are public (exposed client-side), so no read restriction needed.
* 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
* after the matching consent category is granted (see modules/analytics).
*/
export const analyticsFields: Field[] = [
{
name: 'ga4MeasurementId',
type: 'text',
admin: {
description: 'Google Analytics 4 Measurement ID.',
description: 'Google Analytics 4 Measurement ID. (Google — Consent Mode)',
placeholder: 'G-XXXXXXXXXX',
},
},
@@ -17,8 +18,40 @@ export const analyticsFields: Field[] = [
name: 'gtmContainerId',
type: 'text',
admin: {
description: 'Google Tag Manager container ID.',
description: 'Google Tag Manager container ID. (Google — Consent Mode)',
placeholder: 'GTM-XXXXXXX',
},
},
{
name: 'metaPixelId',
type: 'text',
admin: {
description: 'Meta (Facebook) Pixel ID. Loads only after MARKETING consent.',
placeholder: '1234567890123456',
},
},
{
name: 'clarityProjectId',
type: 'text',
admin: {
description: 'Microsoft Clarity project ID (heatmaps). Loads only after ANALYTICS consent.',
placeholder: 'abcdefghij',
},
},
{
name: 'linkedInPartnerId',
type: 'text',
admin: {
description: 'LinkedIn Insight Tag partner ID. Loads only after MARKETING consent.',
placeholder: '1234567',
},
},
{
name: 'tiktokPixelId',
type: 'text',
admin: {
description: 'TikTok Pixel ID. Loads only after MARKETING consent.',
placeholder: 'CXXXXXXXXXXXXXXXXXXX',
},
},
]
+1
View File
@@ -56,6 +56,7 @@ export {
markdownResponse,
parsePageParam,
prefersMarkdown,
resolveNotFoundPage,
resolveRedirect,
resolveRoute,
searchContent,
+125 -20
View File
@@ -1,10 +1,12 @@
'use client'
import { useEffect } from 'react'
import { useEffect, useRef, useState } from 'react'
import type { AnalyticsConfig } from './types.js'
import { useConsentContext } from '../consent/client.js'
import { gtag } from '../consent/googleConsent.js'
import { CONSENT_COOKIE, DEFAULT_CONSENT, parseConsent, setDefaultConsent } from '../consent/index.js'
import { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from './pixels.js'
declare global {
interface Window {
@@ -33,38 +35,141 @@ function injectScript(src: string) {
document.head.appendChild(s)
}
/**
* Loads Google Analytics — GTM if a container ID is set, otherwise GA4 gtag.
*
* Consent Mode is initialised to the visitor's stored consent BEFORE the tag
* loads (via setDefaultConsent from the consent module), so tags respect the
* choice from the first hit; useConsent sends an update the moment the visitor
* decides. IDs are public and come from SiteIntegrations, passed in as props
* (the client project reads them server-side).
*
* Renders nothing — it only injects the scripts. Mount once, high in the tree
* (e.g. root layout), inside ConsentProvider.
*/
export function Analytics({ ga4MeasurementId, gtmContainerId }: AnalyticsConfig) {
export type AnalyticsProps = {
/**
* Core Web Vitals mode: hold back every tag's NETWORK load until the first
* user interaction (scroll, pointer, touch, key) or `deferTimeoutMs` after the
* window `load` event — whichever comes first. Keeps ~100+ KiB of third-party
* JS out of the FCP/LCP window.
*
* Consent is unaffected: the Consent Mode default is still pushed immediately
* (a synchronous dataLayer push, no network), and non-Google pixels still
* require their consent category. Defer changes WHEN a tag loads, never WHETHER.
*
* Trade-off: visitors who leave before interacting and before the timeout are
* not counted (slightly fewer sessions in GA). Default false.
*/
defer?: boolean
/** Fallback delay after window `load`, in ms. Default 3500. */
deferTimeoutMs?: number
} & AnalyticsConfig
const INTERACTION_EVENTS = ['scroll', 'pointerdown', 'touchstart', 'keydown'] as const
/** True once third-party tags may load (immediately, or per `defer` rules). */
function useDeferredReady(defer: boolean, timeoutMs: number): boolean {
const [ready, setReady] = useState(!defer)
useEffect(() => {
if (!defer || ready) {return}
let timer: ReturnType<typeof setTimeout> | undefined
const fire = () => setReady(true)
const onLoad = () => {
timer = setTimeout(() => {
if ('requestIdleCallback' in window) {
window.requestIdleCallback(fire, { timeout: 1000 })
} else {
fire()
}
}, timeoutMs)
}
for (const e of INTERACTION_EVENTS) {
window.addEventListener(e, fire, { once: true, passive: true })
}
if (document.readyState === 'complete') {onLoad()}
else {window.addEventListener('load', onLoad, { once: true })}
return () => {
for (const e of INTERACTION_EVENTS) {window.removeEventListener(e, fire)}
window.removeEventListener('load', onLoad)
if (timer) {clearTimeout(timer)}
}
}, [defer, ready, timeoutMs])
return ready
}
/**
* Loads every configured analytics / marketing tag, each respecting consent:
*
* - **Google (GA4 / GTM)** — Consent Mode: the visitor's stored choice is set as
* the default BEFORE the tag loads (always immediately, even with `defer`),
* and useConsent pushes an update the moment they decide. GTM wins if both
* IDs are set.
* - **Non-Google (Meta Pixel, Clarity, LinkedIn, TikTok)** — no Consent Mode, so
* each loads ONLY after its category is granted (marketing for
* Pixel/LinkedIn/TikTok, analytics for Clarity). Reacts live to the banner.
* - **`defer`** (opt-in) — additionally waits for first interaction / idle
* after load, for better LCP/INP. See AnalyticsProps.defer.
*
* All IDs are public and come from SiteIntegrations (getAnalyticsConfig), passed
* in as props. Renders nothing. Mount once, high in the tree, INSIDE
* <ConsentProvider> (required — it reads live consent state).
*/
export function Analytics(props: AnalyticsProps) {
const {
clarityProjectId,
defer = false,
deferTimeoutMs = 3500,
ga4MeasurementId,
gtmContainerId,
linkedInPartnerId,
metaPixelId,
tiktokPixelId,
} = props
// Live consent state — drives the non-Google pixels.
const { state } = useConsentContext()
const ready = useDeferredReady(defer, deferTimeoutMs)
const defaultConsentSet = useRef(false)
// --- Consent Mode default: immediately, once — never deferred ---
// No network cost, and it must precede any gtag('config') / GTM start, or
// Google assumes "granted".
useEffect(() => {
if (defaultConsentSet.current) {return}
if (!ga4MeasurementId && !gtmContainerId) {return}
// 1. Consent Mode default = the visitor's stored choice, before tags load.
setDefaultConsent(readConsent())
defaultConsentSet.current = true
}, [ga4MeasurementId, gtmContainerId])
// 2. Load the tag.
// --- Google: load once `ready`; Consent Mode handles gating ---
useEffect(() => {
if (!ready) {return}
if (!ga4MeasurementId && !gtmContainerId) {return}
if (gtmContainerId) {
window.dataLayer = window.dataLayer || []
window.dataLayer.push({ event: 'gtm.js', 'gtm.start': Date.now() })
injectScript(GTM_SCRIPT(gtmContainerId))
} else if (ga4MeasurementId) {
injectScript(GA4_SCRIPT(ga4MeasurementId))
// Uses the shared gtag (pushes `arguments`, as Google's tags expect);
// real gtag.js wires itself up once the script loads.
gtag('js', new Date())
gtag('config', ga4MeasurementId)
}
}, [ga4MeasurementId, gtmContainerId])
}, [ready, ga4MeasurementId, gtmContainerId])
// --- Non-Google: each when `ready` AND its consent category is granted ---
// Loaders are idempotent, so re-running on state changes is safe; a tag loads
// the first time both conditions hold and never doubles up.
useEffect(() => {
if (!ready) {return}
if (state.marketing) {
if (metaPixelId) {loadMetaPixel(metaPixelId)}
if (linkedInPartnerId) {loadLinkedIn(linkedInPartnerId)}
if (tiktokPixelId) {loadTikTok(tiktokPixelId)}
}
if (state.analytics && clarityProjectId) {loadClarity(clarityProjectId)}
}, [
ready,
state.marketing,
state.analytics,
metaPixelId,
linkedInPartnerId,
tiktokPixelId,
clarityProjectId,
])
return null
}
+4
View File
@@ -1,3 +1,7 @@
'use client'
export { Analytics } from './Analytics.js'
export type { AnalyticsProps } from './Analytics.js'
// Low-level pixel loaders — exported for manual conversion events if a project
// needs them (Analytics loads them automatically, consent-gated).
export { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from './pixels.js'
export { pushDataLayer } from './pushDataLayer.js'
+6 -3
View File
@@ -5,15 +5,18 @@ import type { AnalyticsConfig } from './types.js'
import { getSiteIntegrations } from '../payload/index.js'
/**
* Reads the public analytics IDs from SiteIntegrations, server-side.
*
* Returns only the two public IDs (GA4 / GTM) — safe to pass to the client
* Reads the public analytics / marketing tag IDs from SiteIntegrations,
* server-side. All are public (exposed client-side), so safe to pass to the
* <Analytics> component. Does NOT expose any secret from SiteIntegrations.
*/
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,
}
}
+118
View File
@@ -0,0 +1,118 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Loaders for non-Google marketing/analytics pixels. Each is idempotent (guards
* against double-init) and loads the vendor's own script + bootstrap.
*
* These are the one place `any` is unavoidable: vendor SDK bootstraps attach
* untyped globals (fbq, clarity, lintrk, ttq) to `window`. Casts are contained
* here; nothing else in the kit uses `any`.
*
* CONSENT: these vendors have no Google Consent Mode — the caller (Analytics)
* loads each ONLY after the matching consent category is granted:
* Meta Pixel / LinkedIn / TikTok → marketing
* Microsoft Clarity → analytics
*/
type Win = Record<string, any> & typeof window
/** Meta (Facebook) Pixel — fires PageView on load. */
export function loadMetaPixel(id: string): void {
if (typeof window === 'undefined') {return}
const w = window as Win
if (w.fbq) {return}
const n: any = (w.fbq = function (...args: unknown[]) {
if (n.callMethod) {
n.callMethod.apply(n, args)
} else {
n.queue.push(args)
}
})
if (!w._fbq) {w._fbq = n}
n.push = n
n.loaded = true
n.version = '2.0'
n.queue = []
const s = document.createElement('script')
s.async = true
s.src = 'https://connect.facebook.net/en_US/fbevents.js'
document.head.appendChild(s)
w.fbq('init', id)
w.fbq('track', 'PageView')
}
/** Microsoft Clarity — heatmaps / session recordings (analytics category). */
export function loadClarity(id: string): void {
if (typeof window === 'undefined') {return}
const w = window as Win
if (w.clarity) {return}
w.clarity = function (...a: unknown[]) {
;(w.clarity.q = w.clarity.q || []).push(a)
}
const s = document.createElement('script')
s.async = true
s.src = `https://www.clarity.ms/tag/${id}`
document.head.appendChild(s)
}
/** LinkedIn Insight Tag (marketing). */
export function loadLinkedIn(partnerId: string): void {
if (typeof window === 'undefined') {return}
const w = window as Win
w._linkedin_partner_id = partnerId
w._linkedin_data_partner_ids = w._linkedin_data_partner_ids || []
if (w._linkedin_data_partner_ids.includes(partnerId)) {
if (document.getElementById('ipal-linkedin-insight')) {return}
} else {
w._linkedin_data_partner_ids.push(partnerId)
}
if (document.getElementById('ipal-linkedin-insight')) {return}
const s = document.createElement('script')
s.async = true
s.id = 'ipal-linkedin-insight'
s.src = 'https://snap.licdn.com/li.lms-analytics/insight.min.js'
document.head.appendChild(s)
}
/** TikTok Pixel (marketing) — fires page view on load. */
export function loadTikTok(id: string): void {
if (typeof window === 'undefined') {return}
const w = window as Win
if (w.ttq) {return}
w.TiktokAnalyticsObject = 'ttq'
const ttq: any = (w.ttq = [])
ttq.methods = [
'page',
'track',
'identify',
'instances',
'debug',
'on',
'off',
'once',
'ready',
'alias',
'group',
'enableCookie',
'disableCookie',
]
ttq.setAndDefer = function (t: any, e: string) {
t[e] = function (...args: unknown[]) {
t.push([e, ...args])
}
}
for (const m of ttq.methods) {ttq.setAndDefer(ttq, m)}
ttq.load = function (e: string) {
const url = 'https://analytics.tiktok.com/i18n/pixel/events.js'
ttq._i = ttq._i || {}
ttq._i[e] = []
ttq._i[e]._u = url
ttq._t = ttq._t || {}
ttq._t[e] = Number(new Date())
const s = document.createElement('script')
s.async = true
s.src = `${url}?sdkid=${e}&lib=ttq`
document.head.appendChild(s)
}
ttq.load(id)
ttq.page()
}
+13 -3
View File
@@ -1,9 +1,19 @@
/**
* Analytics IDs, read from SiteIntegrations (public — safe on the client).
* Analytics / marketing tag IDs, read from SiteIntegrations (all public — safe
* on the client). Google tags (GA4/GTM) use Consent Mode; the rest load only
* after the matching consent category is granted (see Analytics).
*/
export type AnalyticsConfig = {
/** GA4 Measurement ID, e.g. 'G-XXXXXXXXXX'. */
/** Microsoft Clarity project ID. (analytics consent) */
clarityProjectId?: null | string
/** GA4 Measurement ID, e.g. 'G-XXXXXXXXXX'. (Google — Consent Mode) */
ga4MeasurementId?: null | string
/** GTM Container ID, e.g. 'GTM-XXXXXXX'. */
/** GTM Container ID, e.g. 'GTM-XXXXXXX'. (Google — Consent Mode) */
gtmContainerId?: null | string
/** LinkedIn Insight Tag partner ID. (marketing consent) */
linkedInPartnerId?: null | string
/** Meta (Facebook) Pixel ID, ~15–16 digits. (marketing consent) */
metaPixelId?: null | string
/** TikTok Pixel ID. (marketing consent) */
tiktokPixelId?: null | string
}
+35 -16
View File
@@ -1,4 +1,4 @@
import { getPayload } from 'payload'
import type { Payload } from 'payload'
/**
* White-label admin branding: the Payload admin panel's logo (login + nav) and
@@ -7,13 +7,13 @@ import { getPayload } from 'payload'
* automatically by `ipalKit({ whiteLabel: true })` (it injects
* admin.components.graphics.Logo/Icon pointing here).
*
* Server Components — they read the SiteSettings global at render. Data access
* uses the project's `@payload-config` alias (universal in Payload 3 Next apps),
* loaded via a variable specifier so the PLUGIN's own typecheck doesn't try to
* resolve it (same pattern as the optional 2FA import). Everything is wrapped in
* try/catch: on the login screen before the DB is ready, or a build with no DB,
* the component falls back to the site name text, then to null (Payload's own
* default) — never throws, never blocks the panel.
* Server Components — they read the SiteSettings global at render, using the
* `payload` instance Payload itself passes to admin server components. NO
* `import('@payload-config')`: a variable-specifier import isn't traced by the
* Next bundler ("Cannot find module '@payload-config'") — same bug class as the
* old 2FA import. Everything is wrapped in try/catch: no payload prop, DB not
* ready, etc. → site name text, then null (Payload's own default) — never
* throws, never blocks the panel.
*
* A0: no client brand in code. The logo/name come from the panel; if nothing is
* set, nothing is forced.
@@ -22,35 +22,54 @@ import { getPayload } from 'payload'
type BrandingProps = {
/** Upload field to render as the image. Default 'logo' (Logo) / 'favicon' (Icon). */
imageField?: string
/** Injected by Payload — current admin locale (object or code). */
locale?: { code?: string } | string
/** Field holding the site name. Default 'siteName'. */
nameField?: string
/** Injected by Payload into admin server components. */
payload?: Payload
/** SiteSettings global slug. Default 'site-settings'. */
settingsSlug?: string
}
type MediaLike = { url?: null | string } | null | undefined
/** A localized text field may arrive as a string or a { locale: value } map. */
function pickText(value: unknown, locale: string | undefined): null | string {
if (typeof value === 'string') {return value}
if (value && typeof value === 'object') {
const map = value as Record<string, unknown>
const preferred = locale ? map[locale] : undefined
if (typeof preferred === 'string') {return preferred}
const first = Object.values(map).find((v): v is string => typeof v === 'string')
return first ?? null
}
return null
}
async function loadBranding(
props: BrandingProps,
settingsSlug: string,
nameField: string,
imageField: string,
): Promise<{ name: null | string; url: null | string }> {
const { payload } = props
if (!payload) {return { name: null, url: null }}
try {
// Consumer alias — resolved in the project's build, hidden from plugin tsc.
const spec = '@payload-config'
const mod = (await import(spec)) as { default: unknown }
const payload = await getPayload({ config: mod.default as never })
const locale = typeof props.locale === 'string' ? props.locale : props.locale?.code
const settings = (await payload.findGlobal({
slug: settingsSlug as never,
depth: 1,
...(locale ? { locale: locale as never } : {}),
})) as Record<string, unknown>
const name = typeof settings[nameField] === 'string' ? (settings[nameField]) : null
const name = pickText(settings[nameField], locale)
const image = settings[imageField] as MediaLike
const url =
image && typeof image === 'object' && typeof image.url === 'string' ? image.url : null
return { name, url }
} catch {
} catch (error) {
console.warn('[ipal] admin branding: falling back to Payload default:', error)
return { name: null, url: null }
}
}
@@ -62,7 +81,7 @@ async function loadBranding(
*/
export async function AdminLogo(props: BrandingProps = {}) {
const { imageField = 'logo', nameField = 'siteName', settingsSlug = 'site-settings' } = props
const { name, url } = await loadBranding(settingsSlug, nameField, imageField)
const { name, url } = await loadBranding(props, settingsSlug, nameField, imageField)
if (url) {
return (
<img
@@ -79,7 +98,7 @@ export async function AdminLogo(props: BrandingProps = {}) {
/** Admin panel icon (small nav glyph). SiteSettings `favicon`, falls back to initials. */
export async function AdminIcon(props: BrandingProps = {}) {
const { imageField = 'favicon', nameField = 'siteName', settingsSlug = 'site-settings' } = props
const { name, url } = await loadBranding(settingsSlug, nameField, imageField)
const { name, url } = await loadBranding(props, settingsSlug, nameField, imageField)
if (url) {
return (
<img
+57 -11
View File
@@ -3,6 +3,7 @@ import type { BasePayload } from 'payload'
import type { I18nConfig } from '../i18n/index.js'
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'
@@ -32,37 +33,72 @@ const FALLBACK: ConsentTexts = {
settingsTitle: 'Cookie settings',
}
/** Last-resort link text — only when neither the panel nor the page has one. */
const FALLBACK_PRIVACY_LABEL = 'Privacy policy'
type CookieSettingsData = {
buttons?: null | Partial<ConsentTexts['buttons']>
categories?: Array<{ description?: null | string; key: string; title?: null | string }> | null
message?: null | string
privacyLinkLabel?: null | string
settingsTitle?: null | string
}
type PrivacyPage = { slug?: null | Record<string, unknown>; title?: unknown } | null
type GetConsentTextsArgs = {
config: I18nConfig
locale?: string
payload: BasePayload
/**
* Privacy-policy label + the system page (from SiteSettings.privacyPolicy,
* read with locale:'all') to link to. Optional — omit for no link.
* Privacy-policy link. Omit it — the page is read automatically from
* SiteSettings → System Pages → Privacy Policy, and the link text from
* CookieSettings → privacyLinkLabel (per locale, editable in the panel).
*
* - `false` → no link.
* - `{ page }` → use this page (SiteSettings.privacyPolicy read with locale:'all').
* - `label` → DEPRECATED (hardcoded text); used only when the panel field is empty.
*/
privacyPolicy?: {
label: string
page: { slug?: null | Record<string, unknown> } | null
privacyPolicy?:
| {
/** @deprecated Set CookieSettings → privacyLinkLabel in the panel instead. */
label?: string
page?: PrivacyPage
}
| false
/** SiteSettings global slug for the automatic privacy page lookup. Default 'site-settings'. */
settingsSlug?: string
}
/** Reads SiteSettings.privacyPolicy with all locales (slug + title as maps). */
async function readPrivacyPage(payload: BasePayload, settingsSlug: string): Promise<PrivacyPage> {
try {
const settings = (await payload.findGlobal({
slug: settingsSlug as never,
depth: 1,
locale: 'all' as never,
})) as { privacyPolicy?: unknown }
const page = settings.privacyPolicy
return page && typeof page === 'object' ? (page as PrivacyPage) : null
} catch (error) {
// No pages option / no privacyPolicy field / DB unreachable at build → no link.
console.warn('[ipal] getConsentTexts: privacy page lookup failed, banner without link:', error)
return null
}
}
/**
* Resolves consent banner texts from the CookieSettings global, falling back to
* English defaults per field. The privacy-policy link is built from the pages
* module (system page role), not stored in CookieSettings — one source of truth.
* English defaults per field. The privacy-policy link target comes from the
* pages module (system page role, read automatically); its text from
* CookieSettings.privacyLinkLabel — both editable in the panel, per locale.
*/
export async function getConsentTexts({
config,
locale,
payload,
privacyPolicy,
settingsSlug = 'site-settings',
}: GetConsentTextsArgs): Promise<ConsentTexts> {
const g = await getGlobal<CookieSettingsData>(payload, 'cookie-settings', { locale })
@@ -76,10 +112,20 @@ export async function getConsentTexts({
}
let privacyLink: ConsentTexts['privacyLink'] = null
if (privacyPolicy?.page && locale) {
const href = getSystemPagePath({ config, locale, page: privacyPolicy.page })
if (href) {
privacyLink = { href, label: privacyPolicy.label }
if (privacyPolicy !== false && locale) {
const page =
privacyPolicy?.page !== undefined
? privacyPolicy.page
: await readPrivacyPage(payload, settingsSlug)
const href = page ? getSystemPagePath({ config, locale, page }) : undefined
if (page && href) {
// Panel first, then the deprecated code label, then the page's own title.
const label =
g.privacyLinkLabel?.trim() ||
privacyPolicy?.label?.trim() ||
resolveLocalized(page.title, locale).trim() ||
FALLBACK_PRIVACY_LABEL
privacyLink = { href, label }
}
}
+1
View File
@@ -6,6 +6,7 @@ export { getArchiveEntries } from './getArchiveEntries.js'
export type { ArchiveEntries } from './getArchiveEntries.js'
export { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegotiation.js'
export { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js'
export { resolveNotFoundPage } from './resolveNotFoundPage.js'
export { resolveRedirect } from './resolveRedirect.js'
export { resolveRoute } from './resolveRoute.js'
export type { ResolvedRoute } from './resolveRoute.js'
@@ -0,0 +1,57 @@
import type { BasePayload } from 'payload'
type ResolveNotFoundPageArgs = {
locale: string
/** Client's Pages collection slug. Defaults to 'pages'. */
pagesSlug?: string
payload: BasePayload
/** SiteSettings global slug. Defaults to 'site-settings'. */
settingsSlug?: string
}
/**
* Returns the page the editor assigned as **404 (Not Found)** in System Pages,
* fully populated (depth 2, same shape as resolveRoute's pages), or null when
* the role is unassigned.
*
* Used by the project's `not-found.tsx`. The editor decides what a 404 looks
* like: a dedicated "Not found" page, or simply the homepage. Null means
* "render the project's built-in fallback view".
*
* Never throws — a missing DB (container build prerendering not-found) or a
* deleted page just yields null, so the 404 view can't crash the build.
*/
export async function resolveNotFoundPage({
locale,
pagesSlug = 'pages',
payload,
settingsSlug = 'site-settings',
}: ResolveNotFoundPageArgs): Promise<null | Record<string, unknown>> {
try {
const settings = (await payload.findGlobal({
slug: settingsSlug as never,
depth: 0,
locale: locale as never,
})) as Record<string, unknown>
const rel = settings.notFound
const id =
typeof rel === 'string' || typeof rel === 'number'
? rel
: rel && typeof rel === 'object'
? (rel as { id?: number | string }).id
: undefined
if (id === undefined) {return null}
const doc = await payload.findByID({
id,
collection: pagesSlug as never,
depth: 2,
locale: locale as never,
})
return (doc as null | Record<string, unknown>) ?? null
} catch (error) {
console.warn('[ipal] resolveNotFoundPage: falling back to built-in 404 view:', error)
return null
}
}
+17
View File
@@ -160,5 +160,22 @@ export async function resolveRoute({
const doc = found.docs[0]
if (!doc) {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
// it as not found, so the route calls notFound() and not-found.tsx renders
// that same page with a real 404 status. (If 404 = homepage, the homepage is
// served from the root branch above and never reaches here by its own slug
// in a way that matters — but guard anyway so we never hide the homepage.)
const notFound = settings.notFound
const homepage = settings.homepage
const notFoundId =
notFound && typeof notFound === 'object' ? (notFound as { id?: unknown }).id : notFound
const homepageId =
homepage && typeof homepage === 'object' ? (homepage as { id?: unknown }).id : homepage
const docId = (doc as { id?: unknown }).id
if (notFoundId != null && notFoundId === docId && notFoundId !== homepageId) {
return null
}
return { type: 'page', doc: doc as Record<string, unknown> }
}
+30 -2
View File
@@ -7,7 +7,11 @@ import type { ArchiveEntries, ContentOption, ResolvedRoute } from '../content/in
import type { I18nConfig } from '../i18n/index.js'
import type { RobotsRules, SitemapEntry } from '../seo/index.js'
import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js'
import {
getArchiveEntries,
resolveNotFoundPage,
resolveRoute as resolveRouteRaw,
} from '../content/index.js'
import { buildRobots, buildSitemapEntries } from '../seo/index.js'
type CreateContentHelpersArgs = {
@@ -96,6 +100,20 @@ export function createContentHelpers({
},
)
/**
* The page assigned as 404 in System Pages (or null → built-in fallback).
* For app/not-found.tsx; never throws. Locale comes from the x-locale header
* set by createProxy (not-found.tsx receives no params).
*/
const getNotFoundPage = cache(async (locale: string) => {
try {
const payload = await getCachedPayload()
return await resolveNotFoundPage({ locale, pagesSlug, payload, settingsSlug })
} catch {
return null // DB unreachable (container build) — fallback view
}
})
/** One page of a collection's entries, for an archive listing. */
const getEntries = cache(
async (
@@ -202,8 +220,16 @@ export function createContentHelpers({
// Home slug per locale, to exclude the homepage (it's the root, slug []).
const settings = (await payload
.findGlobal({ slug: settingsSlug as never, depth: 1, locale: 'all' as never })
.catch(() => null)) as { homepage?: { id?: number | string; slug?: unknown } } | null
.catch(() => null)) as {
homepage?: { id?: number | string; slug?: unknown }
notFound?: { id?: number | string } | null
} | null
const homeId = settings?.homepage?.id
// The assigned 404 page renders via not-found.tsx, never as its own URL.
const notFoundId =
settings?.notFound?.id !== undefined && settings.notFound.id !== homeId
? settings.notFound.id
: undefined
const EXCLUDED = new Set(['404', '500', 'error', 'not-found'])
const params: Array<{ locale: string; slug: string[] } | { slug: string[] }> = []
@@ -228,6 +254,7 @@ export function createContentHelpers({
}>) {
// Draft filter in memory (safe whether or not the collection has drafts).
if (raw._status && raw._status !== 'published') {continue}
if (notFoundId !== undefined && raw.id === notFoundId) {continue}
// NOTE: unlike the sitemap, we do NOT skip meta.noindex here. A noindex
// page (privacy, cookies, terms) still needs to render — users reach it
@@ -286,6 +313,7 @@ export function createContentHelpers({
getCachedPayload,
getConfiguredLocales,
getEntries,
getNotFoundPage,
getSettings,
resolveRoute,
robots,
+4 -1
View File
@@ -58,9 +58,12 @@ export function createHealthRoute(args: CreateHealthRouteArgs): () => Promise<Re
status: 200,
})
} catch (err) {
// Log the real error for ops; keep the PUBLIC body generic — a 503 with
// `db: 'down'` is all an orchestrator needs, and raw DB error text (host,
// credentials-in-URL, driver internals) must not leak on a public route.
console.warn('[ipal] createHealthRoute: database unreachable:', err)
const body = {
db: 'down',
error: err instanceof Error ? err.message : 'unknown',
status: 'error',
timestamp: new Date().toISOString(),
tookMs: Date.now() - startedAt,
+5 -1
View File
@@ -187,7 +187,11 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
if (p.name === 'get_page') {return rpcResult(id, toolText(await getPage(toolArgs)))}
return rpcResult(id, toolText(`Unknown tool: ${p.name}`, true))
} catch (err) {
return rpcResult(id, toolText(err instanceof Error ? err.message : 'Tool error', true))
// Log the real error server-side; return a GENERIC message to the
// (anonymous) caller so internal details — DB schema, host, stack —
// never leak over a public endpoint.
console.warn('[ipal] createMcpRoute: tool execution failed:', err)
return rpcResult(id, toolText('Tool execution failed.', true))
}
}
case 'tools/list':
+3
View File
@@ -8,6 +8,7 @@ import { ALL_SYSTEM_PAGE_ROLES } from './types.js'
const ROLE_LABELS: Record<SystemPageRole, string> = {
cookiePolicy: 'Cookie Policy',
homepage: 'Homepage',
notFound: '404 (Not Found)',
privacyPolicy: 'Privacy Policy',
termsOfService: 'Terms of Service',
}
@@ -16,6 +17,8 @@ const ROLE_LABELS: Record<SystemPageRole, string> = {
const ROLE_DESCRIPTIONS: Record<SystemPageRole, string> = {
cookiePolicy: 'Page linked from the cookie consent banner.',
homepage: 'Page served at the locale root (e.g. /pl, /en).',
notFound:
'Page shown for unknown URLs (404). Pick a dedicated "Not found" page, or reuse the homepage. If left empty, the project falls back to its built-in not-found view.',
privacyPolicy: 'Page linked as the privacy policy.',
termsOfService: 'Page linked as the terms of service / site regulations.',
}
+3 -1
View File
@@ -2,13 +2,15 @@
* Built-in "system page" roles — documents from the client's Pages
* collection that the site references by function rather than by slug.
*/
export type SystemPageRole = 'cookiePolicy' | 'homepage' | 'privacyPolicy' | 'termsOfService'
export type SystemPageRole =
'cookiePolicy' | 'homepage' | 'notFound' | 'privacyPolicy' | 'termsOfService'
/**
* All system roles in a stable order (used when no subset is configured).
*/
export const ALL_SYSTEM_PAGE_ROLES: readonly SystemPageRole[] = [
'homepage',
'notFound',
'privacyPolicy',
'cookiePolicy',
'termsOfService',