Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e6eada5d39 | ||
|
|
1b52060dce | ||
|
|
52977e67fc | ||
|
|
b25f221a50 | ||
|
|
f9d3d9ae97 | ||
|
|
962b9cb640 | ||
|
|
9b9bbc1a9f | ||
|
|
abf2e7d40f |
@@ -0,0 +1,256 @@
|
|||||||
|
# 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** — `ipalKit({ twoFactor: { issuer: 'Nazwa Firmy' } })` + `pnpm add @clocklimited/payload-2fa@3.0.0-beta.7`. Wymuszone dla WSZYSTKICH użytkowników (forceSetup), bez opcji wyłączenia per user. NIE ustawiaj `twoFactor: false` (chyba że klient wprost odmawia). Bez zależności = błąd buildu. 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` |
|
||||||
|
| 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.
|
||||||
Vendored
+6
-1
@@ -10,10 +10,15 @@ export { Analytics } from '../modules/analytics/client.js';
|
|||||||
* components. Kept separate from the main entry so server bundles don't pull in
|
* components. Kept separate from the main entry so server bundles don't pull in
|
||||||
* client-only code.
|
* client-only code.
|
||||||
*/
|
*/
|
||||||
export { ConsentProvider, CookieBanner, CookieButton, useConsent, useConsentContext, } from '../modules/consent/client.js';
|
export { ConsentProvider, ConsentScript, CookieBanner, CookieButton, useConsent, useConsentContext, } from '../modules/consent/client.js';
|
||||||
export type { CookieBannerClassNames } from '../modules/consent/client.js';
|
export type { CookieBannerClassNames } from '../modules/consent/client.js';
|
||||||
|
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js';
|
||||||
export { useContactForm } from '../modules/forms/useContactForm.js';
|
export { useContactForm } from '../modules/forms/useContactForm.js';
|
||||||
export type { ContactFormErrors, ContactFormValues, SubmitAction, } from '../modules/forms/useContactForm.js';
|
export type { ContactFormErrors, ContactFormValues, SubmitAction, } from '../modules/forms/useContactForm.js';
|
||||||
|
export { useForm } from '../modules/forms/useForm.js';
|
||||||
|
export type { FormErrors, FormSubmitAction, Validator } from '../modules/forms/useForm.js';
|
||||||
|
export { buildValidator, checked, custom, email, isEmail, maxLength, minLength, pattern, required, } from '../modules/forms/validators.js';
|
||||||
|
export type { Rule } from '../modules/forms/validators.js';
|
||||||
export { buildLocalizedPath, getLocaleCodes, getLocalizedSlugs, switchLocalePath, } from '../modules/i18n/index.js';
|
export { buildLocalizedPath, getLocaleCodes, getLocalizedSlugs, switchLocalePath, } from '../modules/i18n/index.js';
|
||||||
export type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js';
|
export type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js';
|
||||||
export { AlternateLinksProvider, AlternateLinksUpdater, LanguageSwitcher, useAlternateLinks, useSetAlternateLinks, } from '../modules/i18n/index.js';
|
export { AlternateLinksProvider, AlternateLinksUpdater, LanguageSwitcher, useAlternateLinks, useSetAlternateLinks, } from '../modules/i18n/index.js';
|
||||||
|
|||||||
Vendored
+4
-1
@@ -9,8 +9,11 @@ export { Analytics } from '../modules/analytics/client.js';
|
|||||||
* Client-side ('use client') exports — React hooks, providers, and UI
|
* Client-side ('use client') exports — React hooks, providers, and UI
|
||||||
* components. Kept separate from the main entry so server bundles don't pull in
|
* components. Kept separate from the main entry so server bundles don't pull in
|
||||||
* client-only code.
|
* client-only code.
|
||||||
*/ export { ConsentProvider, CookieBanner, CookieButton, useConsent, useConsentContext } from '../modules/consent/client.js';
|
*/ export { ConsentProvider, ConsentScript, CookieBanner, CookieButton, useConsent, useConsentContext } from '../modules/consent/client.js';
|
||||||
|
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js';
|
||||||
export { useContactForm } from '../modules/forms/useContactForm.js';
|
export { useContactForm } from '../modules/forms/useContactForm.js';
|
||||||
|
export { useForm } from '../modules/forms/useForm.js';
|
||||||
|
export { buildValidator, checked, custom, email, isEmail, maxLength, minLength, pattern, required } from '../modules/forms/validators.js';
|
||||||
// Pure i18n path helpers — no server/RSC deps, safe to import in client
|
// Pure i18n path helpers — no server/RSC deps, safe to import in client
|
||||||
// components (e.g. a LanguageSwitcher that computes locale URLs on the client).
|
// components (e.g. a LanguageSwitcher that computes locale URLs on the client).
|
||||||
export { buildLocalizedPath, getLocaleCodes, getLocalizedSlugs, switchLocalePath } from '../modules/i18n/index.js';
|
export { buildLocalizedPath, getLocaleCodes, getLocalizedSlugs, switchLocalePath } from '../modules/i18n/index.js';
|
||||||
|
|||||||
Vendored
+1
-1
@@ -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'\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 CookieBanner,\n CookieButton,\n useConsent,\n useConsentContext,\n} from '../modules/consent/client.js'\n\nexport type { CookieBannerClassNames } from '../modules/consent/client.js'\nexport { useContactForm } from '../modules/forms/useContactForm.js'\nexport type {\n ContactFormErrors,\n ContactFormValues,\n SubmitAction,\n} from '../modules/forms/useContactForm.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","ConsentProvider","CookieBanner","CookieButton","useConsent","useConsentContext","useContactForm","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;;;;;;CAMC,GACD,SACEC,eAAe,EACfC,YAAY,EACZC,YAAY,EACZC,UAAU,EACVC,iBAAiB,QACZ,+BAA8B;AAGrC,SAASC,cAAc,QAAQ,qCAAoC;AAMnE,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'\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'\n\nexport type { CookieBannerClassNames } from '../modules/consent/client.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","ConsentProvider","ConsentScript","CookieBanner","CookieButton","useConsent","useConsentContext","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;;;;;;CAMC,GACD,SACEC,eAAe,EACfC,aAAa,EACbC,YAAY,EACZC,YAAY,EACZC,UAAU,EACVC,iBAAiB,QACZ,+BAA8B;AAGrC,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"}
|
||||||
Vendored
+10
-2
@@ -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 { 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 { ConsentCategory, ConsentState, ConsentTexts } from './modules/consent/index.js';
|
||||||
export type { ContentCollectionOption, ContentOption, ResolvedRoute, } from './modules/content/index.js';
|
export type { ContentCollectionOption, ContentOption, ResolvedRoute, } from './modules/content/index.js';
|
||||||
export { archiveFieldName, buildArchivePath, buildEntryPath, getArchiveEntries, parsePageParam, resolveRoute, } from './modules/content/index.js';
|
export { archiveFieldName, buildArchivePath, buildEntryPath, getArchiveEntries, parsePageParam, resolveRedirect, resolveRoute, } from './modules/content/index.js';
|
||||||
export type { ArchiveEntries } from './modules/content/index.js';
|
export type { ArchiveEntries } from './modules/content/index.js';
|
||||||
export { graphAdapter } from './modules/email/graphAdapter.js';
|
export { graphAdapter } from './modules/email/graphAdapter.js';
|
||||||
export type { GraphAdapterArgs } from './modules/email/graphAdapter.js';
|
export type { GraphAdapterArgs } from './modules/email/graphAdapter.js';
|
||||||
@@ -15,10 +15,17 @@ export { mailAdapter } from './modules/email/mailAdapter.js';
|
|||||||
export type { MailAdapterArgs } from './modules/email/mailAdapter.js';
|
export type { MailAdapterArgs } from './modules/email/mailAdapter.js';
|
||||||
export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js';
|
export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js';
|
||||||
export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js';
|
export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js';
|
||||||
|
export { assertEnv, ipalEnvRules } from './modules/env/index.js';
|
||||||
|
export type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from './modules/env/index.js';
|
||||||
export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js';
|
export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js';
|
||||||
|
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './modules/forms/honeypot.js';
|
||||||
export type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption, } from './modules/forms/types.js';
|
export type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption, } from './modules/forms/types.js';
|
||||||
|
export type { FormErrors, FormSubmitAction, Validator } from './modules/forms/useForm.js';
|
||||||
|
export { buildValidator, checked, custom, email, isEmail, maxLength, minLength, pattern, required, } from './modules/forms/validators.js';
|
||||||
|
export type { Rule } from './modules/forms/validators.js';
|
||||||
export { createContentHelpers } from './modules/frontend/index.js';
|
export { createContentHelpers } from './modules/frontend/index.js';
|
||||||
export { buildPreventDeleteSystemPage, buildRevalidateHook, buildValidateUniqueRole, setPublishedAtHook, trackSlugHistoryHook, } from './modules/hooks/index.js';
|
export { createHealthRoute } from './modules/health/index.js';
|
||||||
|
export { buildCrossLocaleFieldSync, buildPreventDeleteSystemPage, buildRevalidateHook, buildValidateUniqueRole, setPublishedAtHook, trackSlugHistoryHook, } from './modules/hooks/index.js';
|
||||||
export type { I18nConfig, LocaleDefinition, LocalizedSlugs } from './modules/i18n/index.js';
|
export type { I18nConfig, LocaleDefinition, LocalizedSlugs } from './modules/i18n/index.js';
|
||||||
export { buildLocalizedPath, getDefaultLocale, getLocaleCodes, getLocaleDefinition, getLocalizedSlugs, isValidLocale, LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale, switchLocalePath, } from './modules/i18n/index.js';
|
export { buildLocalizedPath, getDefaultLocale, getLocaleCodes, getLocaleDefinition, getLocalizedSlugs, isValidLocale, LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale, switchLocalePath, } from './modules/i18n/index.js';
|
||||||
export type { LocaleMiddlewareResult } from './modules/i18n/index.js';
|
export type { LocaleMiddlewareResult } from './modules/i18n/index.js';
|
||||||
@@ -42,6 +49,7 @@ export type { AutoFillMapping, RobotsRules, SitemapEntry } from './modules/seo/i
|
|||||||
export { buildAutoFillMetaHook, buildRobots, buildSitemapEntries, createMetadataGenerator, createPageMetadata, injectAutoFillMeta, } from './modules/seo/index.js';
|
export { buildAutoFillMetaHook, buildRobots, buildSitemapEntries, createMetadataGenerator, createPageMetadata, injectAutoFillMeta, } from './modules/seo/index.js';
|
||||||
export { createLlmsTxtRoute, createManifestHandler, createSitemapRouteHandler, } from './modules/seo/index.js';
|
export { createLlmsTxtRoute, createManifestHandler, createSitemapRouteHandler, } from './modules/seo/index.js';
|
||||||
export { buildIconsMetadata, buildOrganizationJsonLd, validateFaviconField, } from './modules/seo/index.js';
|
export { buildIconsMetadata, buildOrganizationJsonLd, validateFaviconField, } from './modules/seo/index.js';
|
||||||
|
export { buildNoindexField } from './modules/seo/index.js';
|
||||||
export { buildBreadcrumbJsonLd, buildSiteNavigationJsonLd, buildWebSiteJsonLd, } from './modules/seo/index.js';
|
export { buildBreadcrumbJsonLd, buildSiteNavigationJsonLd, buildWebSiteJsonLd, } from './modules/seo/index.js';
|
||||||
export { buildFaqJsonLd, buildLocalBusinessJsonLd, buildServiceJsonLd, } from './modules/seo/index.js';
|
export { buildFaqJsonLd, buildLocalBusinessJsonLd, buildServiceJsonLd, } from './modules/seo/index.js';
|
||||||
export { buildArticleJsonLd } from './modules/seo/index.js';
|
export { buildArticleJsonLd } from './modules/seo/index.js';
|
||||||
|
|||||||
Vendored
+12
-2
@@ -2,16 +2,25 @@ export { adminOnly, adminOnlyField, adminOrEditor, adminOrEditorField, adminOrSe
|
|||||||
export { A11Y_COOKIE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y } from './modules/accessibility/index.js';
|
export { A11Y_COOKIE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y } from './modules/accessibility/index.js';
|
||||||
export { getAnalyticsConfig } from './modules/analytics/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 { 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, buildArchivePath, buildEntryPath, getArchiveEntries, parsePageParam, resolveRoute } from './modules/content/index.js';
|
export { archiveFieldName, buildArchivePath, buildEntryPath, getArchiveEntries, parsePageParam, resolveRedirect, resolveRoute } from './modules/content/index.js';
|
||||||
export { graphAdapter } from './modules/email/graphAdapter.js';
|
export { graphAdapter } from './modules/email/graphAdapter.js';
|
||||||
export { mailAdapter } from './modules/email/mailAdapter.js';
|
export { mailAdapter } from './modules/email/mailAdapter.js';
|
||||||
// Imported straight from the file, NOT from ./modules/email/index.js — that
|
// Imported straight from the file, NOT from ./modules/email/index.js — that
|
||||||
// barrel re-exports sendEmail, which imports 'server-only' and would crash when
|
// barrel re-exports sendEmail, which imports 'server-only' and would crash when
|
||||||
// Payload loads the config (or runs generate:importmap) as a plain Node script.
|
// Payload loads the config (or runs generate:importmap) as a plain Node script.
|
||||||
export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js';
|
export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js';
|
||||||
|
// Boot-time environment validation (fail fast on misconfigured deploys).
|
||||||
|
export { assertEnv, ipalEnvRules } from './modules/env/index.js';
|
||||||
export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js';
|
export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js';
|
||||||
|
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './modules/forms/honeypot.js';
|
||||||
|
// Validation rules are pure — exported server-side too, for re-validating a
|
||||||
|
// submission inside a server action. (useForm/useContactForm are client-only →
|
||||||
|
// '@intecion/ipal-kit/client'.)
|
||||||
|
export { buildValidator, checked, custom, email, isEmail, maxLength, minLength, pattern, required } from './modules/forms/validators.js';
|
||||||
export { createContentHelpers } from './modules/frontend/index.js';
|
export { createContentHelpers } from './modules/frontend/index.js';
|
||||||
export { buildPreventDeleteSystemPage, buildRevalidateHook, buildValidateUniqueRole, setPublishedAtHook, trackSlugHistoryHook } from './modules/hooks/index.js';
|
// Healthcheck route (Coolify/Docker liveness with a real DB round-trip).
|
||||||
|
export { createHealthRoute } from './modules/health/index.js';
|
||||||
|
export { buildCrossLocaleFieldSync, buildPreventDeleteSystemPage, buildRevalidateHook, buildValidateUniqueRole, setPublishedAtHook, trackSlugHistoryHook } from './modules/hooks/index.js';
|
||||||
export { buildLocalizedPath, getDefaultLocale, getLocaleCodes, getLocaleDefinition, getLocalizedSlugs, isValidLocale, LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale, switchLocalePath } from './modules/i18n/index.js';
|
export { buildLocalizedPath, getDefaultLocale, getLocaleCodes, getLocaleDefinition, getLocalizedSlugs, isValidLocale, LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale, switchLocalePath } from './modules/i18n/index.js';
|
||||||
export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './modules/i18n/index.js';
|
export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './modules/i18n/index.js';
|
||||||
export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js';
|
export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js';
|
||||||
@@ -26,6 +35,7 @@ export { buildHreflangAlternates, buildMetadata, composeTitle } from './modules/
|
|||||||
export { buildAutoFillMetaHook, buildRobots, buildSitemapEntries, createMetadataGenerator, createPageMetadata, injectAutoFillMeta } from './modules/seo/index.js';
|
export { buildAutoFillMetaHook, buildRobots, buildSitemapEntries, createMetadataGenerator, createPageMetadata, injectAutoFillMeta } from './modules/seo/index.js';
|
||||||
export { createLlmsTxtRoute, createManifestHandler, createSitemapRouteHandler } from './modules/seo/index.js';
|
export { createLlmsTxtRoute, createManifestHandler, createSitemapRouteHandler } from './modules/seo/index.js';
|
||||||
export { buildIconsMetadata, buildOrganizationJsonLd, validateFaviconField } from './modules/seo/index.js';
|
export { buildIconsMetadata, buildOrganizationJsonLd, validateFaviconField } from './modules/seo/index.js';
|
||||||
|
export { buildNoindexField } from './modules/seo/index.js';
|
||||||
export { buildBreadcrumbJsonLd, buildSiteNavigationJsonLd, buildWebSiteJsonLd } from './modules/seo/index.js';
|
export { buildBreadcrumbJsonLd, buildSiteNavigationJsonLd, buildWebSiteJsonLd } from './modules/seo/index.js';
|
||||||
// Local SEO structured data — LocalBusiness (map pack), Service (offering), FAQPage.
|
// Local SEO structured data — LocalBusiness (map pack), Service (offering), FAQPage.
|
||||||
export { buildFaqJsonLd, buildLocalBusinessJsonLd, buildServiceJsonLd } from './modules/seo/index.js';
|
export { buildFaqJsonLd, buildLocalBusinessJsonLd, buildServiceJsonLd } from './modules/seo/index.js';
|
||||||
|
|||||||
Vendored
+1
-1
File diff suppressed because one or more lines are too long
+49
@@ -0,0 +1,49 @@
|
|||||||
|
import type { ConsentCategory } from './categories.js';
|
||||||
|
type ConsentScriptProps = {
|
||||||
|
/** Default true. */
|
||||||
|
async?: boolean;
|
||||||
|
/** Extra attributes on the <script> (e.g. { 'data-domain': 'x.com' }). */
|
||||||
|
attributes?: Record<string, string>;
|
||||||
|
/**
|
||||||
|
* Consent category that must be granted before the script loads. Typically
|
||||||
|
* 'analytics' (GA, Plausible) or 'marketing' (Meta Pixel, ads, chat widgets).
|
||||||
|
*/
|
||||||
|
category: ConsentCategory;
|
||||||
|
/**
|
||||||
|
* Inline JS to run once granted. If `src` is also set, it runs after the
|
||||||
|
* external script loads (so init code can rely on the library). A plain
|
||||||
|
* string of code — NOT user input (you control it), it goes into a <script>.
|
||||||
|
*/
|
||||||
|
code?: string;
|
||||||
|
defer?: boolean;
|
||||||
|
/** Stable id used to dedupe — the script is injected at most once. */
|
||||||
|
id?: string;
|
||||||
|
/** External script URL. Injected only once the category is granted. */
|
||||||
|
src?: string;
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* Loads a third-party script ONLY after the visitor has granted consent for its
|
||||||
|
* category — the GDPR-correct default for anything that isn't strictly
|
||||||
|
* necessary. Renders nothing until then. Reacts live to the consent context, so
|
||||||
|
* a script appears the moment the visitor accepts in the banner, with no reload.
|
||||||
|
*
|
||||||
|
* Use this for third parties that have NO Google Consent Mode of their own (Meta
|
||||||
|
* Pixel, LinkedIn Insight, chat widgets, custom analytics). GA/GTM are better
|
||||||
|
* handled by Consent Mode (the module's updateConsent already does that) — reach
|
||||||
|
* for ConsentScript when a vendor can't be gated that way.
|
||||||
|
*
|
||||||
|
* Must be rendered inside <ConsentProvider>.
|
||||||
|
*
|
||||||
|
* <ConsentScript category="marketing" src="https://connect.facebook.net/en_US/fbevents.js" />
|
||||||
|
* <ConsentScript category="analytics"
|
||||||
|
* src="https://plausible.io/js/script.js"
|
||||||
|
* attributes={{ 'data-domain': 'example.com' }} />
|
||||||
|
* <ConsentScript category="marketing" code={`fbq('init','123');fbq('track','PageView')`} />
|
||||||
|
*
|
||||||
|
* Note on withdrawal: once a script has loaded it keeps running for that page
|
||||||
|
* (a <script> tag can't be truly unloaded) — withdrawing consent stops the NEXT
|
||||||
|
* load. For vendors that support it, prefer Consent Mode so running tags honor
|
||||||
|
* the change immediately; ConsentScript gates the initial load.
|
||||||
|
*/
|
||||||
|
export declare function ConsentScript({ id, async: asyncAttr, attributes, category, code, defer, src, }: ConsentScriptProps): null;
|
||||||
|
export default ConsentScript;
|
||||||
+95
@@ -0,0 +1,95 @@
|
|||||||
|
'use client';
|
||||||
|
import { useEffect, useRef } from 'react';
|
||||||
|
import { useConsentContext } from './ConsentContext.js';
|
||||||
|
/**
|
||||||
|
* Loads a third-party script ONLY after the visitor has granted consent for its
|
||||||
|
* category — the GDPR-correct default for anything that isn't strictly
|
||||||
|
* necessary. Renders nothing until then. Reacts live to the consent context, so
|
||||||
|
* a script appears the moment the visitor accepts in the banner, with no reload.
|
||||||
|
*
|
||||||
|
* Use this for third parties that have NO Google Consent Mode of their own (Meta
|
||||||
|
* Pixel, LinkedIn Insight, chat widgets, custom analytics). GA/GTM are better
|
||||||
|
* handled by Consent Mode (the module's updateConsent already does that) — reach
|
||||||
|
* for ConsentScript when a vendor can't be gated that way.
|
||||||
|
*
|
||||||
|
* Must be rendered inside <ConsentProvider>.
|
||||||
|
*
|
||||||
|
* <ConsentScript category="marketing" src="https://connect.facebook.net/en_US/fbevents.js" />
|
||||||
|
* <ConsentScript category="analytics"
|
||||||
|
* src="https://plausible.io/js/script.js"
|
||||||
|
* attributes={{ 'data-domain': 'example.com' }} />
|
||||||
|
* <ConsentScript category="marketing" code={`fbq('init','123');fbq('track','PageView')`} />
|
||||||
|
*
|
||||||
|
* Note on withdrawal: once a script has loaded it keeps running for that page
|
||||||
|
* (a <script> tag can't be truly unloaded) — withdrawing consent stops the NEXT
|
||||||
|
* load. For vendors that support it, prefer Consent Mode so running tags honor
|
||||||
|
* the change immediately; ConsentScript gates the initial load.
|
||||||
|
*/ export function ConsentScript({ id, async: asyncAttr = true, attributes, category, code, defer, src }) {
|
||||||
|
const { state } = useConsentContext();
|
||||||
|
const granted = state[category] === true;
|
||||||
|
const injectedRef = useRef(false);
|
||||||
|
useEffect(()=>{
|
||||||
|
if (!granted || injectedRef.current) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!src && !code) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const dedupeId = id ?? (src ? `ipal-cs-${src}` : undefined);
|
||||||
|
if (dedupeId && document.getElementById(dedupeId)) {
|
||||||
|
injectedRef.current = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
injectedRef.current = true;
|
||||||
|
const runInline = ()=>{
|
||||||
|
if (!code) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const inline = document.createElement('script');
|
||||||
|
if (dedupeId) {
|
||||||
|
inline.id = `${dedupeId}-inline`;
|
||||||
|
}
|
||||||
|
inline.textContent = code;
|
||||||
|
document.head.appendChild(inline);
|
||||||
|
};
|
||||||
|
if (src) {
|
||||||
|
const el = document.createElement('script');
|
||||||
|
el.src = src;
|
||||||
|
if (dedupeId) {
|
||||||
|
el.id = dedupeId;
|
||||||
|
}
|
||||||
|
if (asyncAttr) {
|
||||||
|
el.async = true;
|
||||||
|
}
|
||||||
|
if (defer) {
|
||||||
|
el.defer = true;
|
||||||
|
}
|
||||||
|
if (attributes) {
|
||||||
|
for (const [k, v] of Object.entries(attributes)){
|
||||||
|
el.setAttribute(k, v);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
el.addEventListener('load', runInline, {
|
||||||
|
once: true
|
||||||
|
});
|
||||||
|
document.head.appendChild(el);
|
||||||
|
} else {
|
||||||
|
runInline();
|
||||||
|
}
|
||||||
|
// Deliberately no removal on cleanup: a loaded third-party script can't be
|
||||||
|
// meaningfully unloaded. Withdrawal is handled by not re-injecting (and, for
|
||||||
|
// vendors that support it, Consent Mode). See the component doc.
|
||||||
|
}, [
|
||||||
|
granted,
|
||||||
|
src,
|
||||||
|
code,
|
||||||
|
id,
|
||||||
|
attributes,
|
||||||
|
asyncAttr,
|
||||||
|
defer
|
||||||
|
]);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
export default ConsentScript;
|
||||||
|
|
||||||
|
//# sourceMappingURL=ConsentScript.js.map
|
||||||
+1
File diff suppressed because one or more lines are too long
Vendored
+1
@@ -1,4 +1,5 @@
|
|||||||
export { ConsentProvider, useConsentContext } from './ConsentContext.js';
|
export { ConsentProvider, useConsentContext } from './ConsentContext.js';
|
||||||
|
export { ConsentScript } from './ConsentScript.js';
|
||||||
export { CookieBanner } from './CookieBanner.js';
|
export { CookieBanner } from './CookieBanner.js';
|
||||||
export type { CookieBannerClassNames } from './CookieBanner.js';
|
export type { CookieBannerClassNames } from './CookieBanner.js';
|
||||||
export { CookieButton } from './CookieButton.js';
|
export { CookieButton } from './CookieButton.js';
|
||||||
|
|||||||
Vendored
+1
@@ -1,5 +1,6 @@
|
|||||||
'use client';
|
'use client';
|
||||||
export { ConsentProvider, useConsentContext } from './ConsentContext.js';
|
export { ConsentProvider, useConsentContext } from './ConsentContext.js';
|
||||||
|
export { ConsentScript } from './ConsentScript.js';
|
||||||
export { CookieBanner } from './CookieBanner.js';
|
export { CookieBanner } from './CookieBanner.js';
|
||||||
export { CookieButton } from './CookieButton.js';
|
export { CookieButton } from './CookieButton.js';
|
||||||
// Client-only consent exports — hook, provider, and UI components.
|
// Client-only consent exports — hook, provider, and UI components.
|
||||||
|
|||||||
Vendored
+1
-1
@@ -1 +1 @@
|
|||||||
{"version":3,"sources":["../../../src/modules/consent/client.ts"],"sourcesContent":["'use client'\nexport { ConsentProvider, useConsentContext } from './ConsentContext.js'\nexport { CookieBanner } from './CookieBanner.js'\nexport type { CookieBannerClassNames } from './CookieBanner.js'\nexport { CookieButton } from './CookieButton.js'\n// Client-only consent exports — hook, provider, and UI components.\nexport { useConsent } from './useConsent.js'\n"],"names":["ConsentProvider","useConsentContext","CookieBanner","CookieButton","useConsent"],"mappings":"AAAA;AACA,SAASA,eAAe,EAAEC,iBAAiB,QAAQ,sBAAqB;AACxE,SAASC,YAAY,QAAQ,oBAAmB;AAEhD,SAASC,YAAY,QAAQ,oBAAmB;AAChD,mEAAmE;AACnE,SAASC,UAAU,QAAQ,kBAAiB"}
|
{"version":3,"sources":["../../../src/modules/consent/client.ts"],"sourcesContent":["'use client'\nexport { ConsentProvider, useConsentContext } from './ConsentContext.js'\nexport { ConsentScript } from './ConsentScript.js'\nexport { CookieBanner } from './CookieBanner.js'\nexport type { CookieBannerClassNames } from './CookieBanner.js'\nexport { CookieButton } from './CookieButton.js'\n// Client-only consent exports — hook, provider, and UI components.\nexport { useConsent } from './useConsent.js'\n"],"names":["ConsentProvider","useConsentContext","ConsentScript","CookieBanner","CookieButton","useConsent"],"mappings":"AAAA;AACA,SAASA,eAAe,EAAEC,iBAAiB,QAAQ,sBAAqB;AACxE,SAASC,aAAa,QAAQ,qBAAoB;AAClD,SAASC,YAAY,QAAQ,oBAAmB;AAEhD,SAASC,YAAY,QAAQ,oBAAmB;AAChD,mEAAmE;AACnE,SAASC,UAAU,QAAQ,kBAAiB"}
|
||||||
Vendored
+1
@@ -2,6 +2,7 @@ export { buildArchiveFields } from './archiveFields.js';
|
|||||||
export { getArchiveEntries } from './getArchiveEntries.js';
|
export { getArchiveEntries } from './getArchiveEntries.js';
|
||||||
export type { ArchiveEntries } from './getArchiveEntries.js';
|
export type { ArchiveEntries } from './getArchiveEntries.js';
|
||||||
export { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js';
|
export { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js';
|
||||||
|
export { resolveRedirect } from './resolveRedirect.js';
|
||||||
export { resolveRoute } from './resolveRoute.js';
|
export { resolveRoute } from './resolveRoute.js';
|
||||||
export type { ResolvedRoute } from './resolveRoute.js';
|
export type { ResolvedRoute } from './resolveRoute.js';
|
||||||
export type { ContentCollectionOption, ContentOption } from './types.js';
|
export type { ContentCollectionOption, ContentOption } from './types.js';
|
||||||
|
|||||||
Vendored
+1
@@ -1,6 +1,7 @@
|
|||||||
export { buildArchiveFields } from './archiveFields.js';
|
export { buildArchiveFields } from './archiveFields.js';
|
||||||
export { getArchiveEntries } from './getArchiveEntries.js';
|
export { getArchiveEntries } from './getArchiveEntries.js';
|
||||||
export { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js';
|
export { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js';
|
||||||
|
export { resolveRedirect } from './resolveRedirect.js';
|
||||||
export { resolveRoute } from './resolveRoute.js';
|
export { resolveRoute } from './resolveRoute.js';
|
||||||
export { archiveFieldName } from './types.js';
|
export { archiveFieldName } from './types.js';
|
||||||
|
|
||||||
|
|||||||
Vendored
+1
-1
@@ -1 +1 @@
|
|||||||
{"version":3,"sources":["../../../src/modules/content/index.ts"],"sourcesContent":["export { buildArchiveFields } from './archiveFields.js'\nexport { getArchiveEntries } from './getArchiveEntries.js'\nexport type { ArchiveEntries } from './getArchiveEntries.js'\nexport { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js'\nexport { resolveRoute } from './resolveRoute.js'\nexport type { ResolvedRoute } from './resolveRoute.js'\nexport type { ContentCollectionOption, ContentOption } from './types.js'\nexport { archiveFieldName } from './types.js'\n"],"names":["buildArchiveFields","getArchiveEntries","buildArchivePath","buildEntryPath","parsePageParam","resolveRoute","archiveFieldName"],"mappings":"AAAA,SAASA,kBAAkB,QAAQ,qBAAoB;AACvD,SAASC,iBAAiB,QAAQ,yBAAwB;AAE1D,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,cAAc,QAAQ,aAAY;AAC7E,SAASC,YAAY,QAAQ,oBAAmB;AAGhD,SAASC,gBAAgB,QAAQ,aAAY"}
|
{"version":3,"sources":["../../../src/modules/content/index.ts"],"sourcesContent":["export { buildArchiveFields } from './archiveFields.js'\nexport { getArchiveEntries } from './getArchiveEntries.js'\nexport type { ArchiveEntries } from './getArchiveEntries.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 type { ContentCollectionOption, ContentOption } from './types.js'\nexport { archiveFieldName } from './types.js'\n"],"names":["buildArchiveFields","getArchiveEntries","buildArchivePath","buildEntryPath","parsePageParam","resolveRedirect","resolveRoute","archiveFieldName"],"mappings":"AAAA,SAASA,kBAAkB,QAAQ,qBAAoB;AACvD,SAASC,iBAAiB,QAAQ,yBAAwB;AAE1D,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,cAAc,QAAQ,aAAY;AAC7E,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,YAAY,QAAQ,oBAAmB;AAGhD,SAASC,gBAAgB,QAAQ,aAAY"}
|
||||||
+59
@@ -0,0 +1,59 @@
|
|||||||
|
import type { BasePayload } from 'payload';
|
||||||
|
import type { I18nConfig } from '../i18n/index.js';
|
||||||
|
type RedirectCollection = {
|
||||||
|
/**
|
||||||
|
* Array field holding past slugs, each row `{ slug }`. Default 'slugHistory'
|
||||||
|
* — the field `trackSlugHistoryHook` writes. The subfield queried is
|
||||||
|
* `<field>.slug`.
|
||||||
|
*/
|
||||||
|
historyField?: string;
|
||||||
|
/** Collection slug to search, e.g. 'pages'. */
|
||||||
|
slug: string;
|
||||||
|
/** Current-slug field on the doc. Default 'slug'. */
|
||||||
|
slugField?: string;
|
||||||
|
};
|
||||||
|
type ResolveRedirectArgs = {
|
||||||
|
/**
|
||||||
|
* Collections to search, in order. Default [{ slug: 'pages' }]. A collection
|
||||||
|
* without a slug-history field is skipped safely (no crash), so passing a
|
||||||
|
* collection that lacks it costs nothing.
|
||||||
|
*/
|
||||||
|
collections?: RedirectCollection[];
|
||||||
|
config: I18nConfig;
|
||||||
|
/** Home slug map/string, so a renamed homepage still collapses to the root. */
|
||||||
|
homeSlug?: Record<string, string> | string;
|
||||||
|
/** Active locale (the request's locale). */
|
||||||
|
locale: string;
|
||||||
|
payload: BasePayload;
|
||||||
|
/** Incoming route segments (what 404'd), e.g. ['uslugi', 'stara-nazwa']. */
|
||||||
|
segments: string[] | undefined;
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* Resolves a 301/308 destination for a URL that no longer matches any current
|
||||||
|
* slug, by looking the old slug up in each collection's slug-history. Returns
|
||||||
|
* the current localized path to redirect to, or null when nothing matches.
|
||||||
|
*
|
||||||
|
* This is the read side of `trackSlugHistoryHook`: that hook records old slugs
|
||||||
|
* on save; this turns them back into a redirect so a renamed page never 404s
|
||||||
|
* (a real SEO loss). The plugin only COMPUTES the destination — the project
|
||||||
|
* issues the redirect, keeping the peer-dep boundary (no next/navigation import
|
||||||
|
* here):
|
||||||
|
*
|
||||||
|
* // app/[locale]/[[...slug]]/page.tsx (or app/[[...slug]] when single-locale)
|
||||||
|
* const route = await resolveRoute({ ... })
|
||||||
|
* if (!route) {
|
||||||
|
* const dest = await resolveRedirect({
|
||||||
|
* payload, locale, segments: slug, config: i18nConfig, homeSlug,
|
||||||
|
* collections: [{ slug: 'pages' }],
|
||||||
|
* })
|
||||||
|
* if (dest) permanentRedirect(dest) // from 'next/navigation' → HTTP 308 (SEO-equivalent to 301)
|
||||||
|
* notFound()
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* Multi-segment slugs (an editor slug like 'uslugi/biznesowe') are matched as
|
||||||
|
* the joined path, so they work unchanged. Archive ENTRY URLs
|
||||||
|
* (/artykuly/<entry>) aren't handled here yet — only flat collections; pass
|
||||||
|
* the collections whose slugs map directly to a path.
|
||||||
|
*/
|
||||||
|
export declare function resolveRedirect({ collections, config, homeSlug, locale, payload, segments, }: ResolveRedirectArgs): Promise<null | string>;
|
||||||
|
export {};
|
||||||
+81
@@ -0,0 +1,81 @@
|
|||||||
|
import { buildLocalizedPath } from '../i18n/index.js';
|
||||||
|
/**
|
||||||
|
* Resolves a 301/308 destination for a URL that no longer matches any current
|
||||||
|
* slug, by looking the old slug up in each collection's slug-history. Returns
|
||||||
|
* the current localized path to redirect to, or null when nothing matches.
|
||||||
|
*
|
||||||
|
* This is the read side of `trackSlugHistoryHook`: that hook records old slugs
|
||||||
|
* on save; this turns them back into a redirect so a renamed page never 404s
|
||||||
|
* (a real SEO loss). The plugin only COMPUTES the destination — the project
|
||||||
|
* issues the redirect, keeping the peer-dep boundary (no next/navigation import
|
||||||
|
* here):
|
||||||
|
*
|
||||||
|
* // app/[locale]/[[...slug]]/page.tsx (or app/[[...slug]] when single-locale)
|
||||||
|
* const route = await resolveRoute({ ... })
|
||||||
|
* if (!route) {
|
||||||
|
* const dest = await resolveRedirect({
|
||||||
|
* payload, locale, segments: slug, config: i18nConfig, homeSlug,
|
||||||
|
* collections: [{ slug: 'pages' }],
|
||||||
|
* })
|
||||||
|
* if (dest) permanentRedirect(dest) // from 'next/navigation' → HTTP 308 (SEO-equivalent to 301)
|
||||||
|
* notFound()
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* Multi-segment slugs (an editor slug like 'uslugi/biznesowe') are matched as
|
||||||
|
* the joined path, so they work unchanged. Archive ENTRY URLs
|
||||||
|
* (/artykuly/<entry>) aren't handled here yet — only flat collections; pass
|
||||||
|
* the collections whose slugs map directly to a path.
|
||||||
|
*/ export async function resolveRedirect({ collections = [
|
||||||
|
{
|
||||||
|
slug: 'pages'
|
||||||
|
}
|
||||||
|
], config, homeSlug, locale, payload, segments }) {
|
||||||
|
const oldSlug = (segments ?? []).filter(Boolean).join('/');
|
||||||
|
// Root never redirects — there's no "old slug" for the locale home.
|
||||||
|
if (!oldSlug) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
for (const col of collections){
|
||||||
|
const historyField = col.historyField ?? 'slugHistory';
|
||||||
|
const slugField = col.slugField ?? 'slug';
|
||||||
|
let currentSlug;
|
||||||
|
try {
|
||||||
|
const res = await payload.find({
|
||||||
|
collection: col.slug,
|
||||||
|
depth: 0,
|
||||||
|
limit: 1,
|
||||||
|
locale: locale,
|
||||||
|
pagination: false,
|
||||||
|
where: {
|
||||||
|
[`${historyField}.slug`]: {
|
||||||
|
equals: oldSlug
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const doc = res?.docs?.[0] ?? null;
|
||||||
|
if (doc && typeof doc[slugField] === 'string') {
|
||||||
|
currentSlug = doc[slugField];
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!currentSlug || currentSlug === oldSlug) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const dest = buildLocalizedPath({
|
||||||
|
config,
|
||||||
|
homeSlug,
|
||||||
|
locale,
|
||||||
|
slugs: {
|
||||||
|
[locale]: currentSlug
|
||||||
|
}
|
||||||
|
});
|
||||||
|
// Never redirect a path to itself (would loop).
|
||||||
|
if (dest && dest !== `/${oldSlug}` && dest !== `/${locale}/${oldSlug}`) {
|
||||||
|
return dest;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
//# sourceMappingURL=resolveRedirect.js.map
|
||||||
+1
File diff suppressed because one or more lines are too long
Vendored
+49
@@ -0,0 +1,49 @@
|
|||||||
|
/**
|
||||||
|
* Zero-dependency environment validation. The plugin deliberately does NOT pull
|
||||||
|
* in zod — forcing a validation library on every project would be a dependency
|
||||||
|
* the project didn't ask for (against the A0 "no imposed deps" rule). This is a
|
||||||
|
* tiny validator that does the one thing we need: check the vars a deploy needs
|
||||||
|
* and FAIL FAST with a readable, all-at-once message instead of a cryptic
|
||||||
|
* runtime crash (e.g. `getaddrinfo ENOTFOUND` halfway through a Docker build).
|
||||||
|
*/
|
||||||
|
export type EnvKind = 'boolean' | 'email' | 'number' | 'port' | 'string' | 'url';
|
||||||
|
export type EnvRule = {
|
||||||
|
/** Shown in the error to tell the deployer what the var is for. */
|
||||||
|
description?: string;
|
||||||
|
/** Shape check applied when a value is present. Default 'string' (non-empty). */
|
||||||
|
kind?: EnvKind;
|
||||||
|
/** Variable name, e.g. 'DATABASE_URI'. */
|
||||||
|
name: string;
|
||||||
|
/** Allowed values (e.g. NODE_ENV). Checked when a value is present. */
|
||||||
|
oneOf?: readonly string[];
|
||||||
|
/** Default true. When false, the var is only validated if present. */
|
||||||
|
required?: boolean;
|
||||||
|
/** Custom check: return true if OK, or an error message string. */
|
||||||
|
validate?: (value: string) => string | true;
|
||||||
|
};
|
||||||
|
export type AssertEnvOptions = {
|
||||||
|
/** Source of values. Default process.env. */
|
||||||
|
env?: Record<string, string | undefined>;
|
||||||
|
/** Error prefix. Default '[ipal]'. */
|
||||||
|
label?: string;
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* Validates the given rules against the environment and THROWS a single,
|
||||||
|
* aggregated error listing every problem at once (not just the first). Call it
|
||||||
|
* once at boot — in payload.config.ts, or Next's instrumentation.ts register().
|
||||||
|
*
|
||||||
|
* import { assertEnv, ipalEnvRules } from '@intecion/ipal-kit'
|
||||||
|
* assertEnv(ipalEnvRules({ storage: true, turnstile: true }))
|
||||||
|
*
|
||||||
|
* or with hand-written rules:
|
||||||
|
*
|
||||||
|
* assertEnv([
|
||||||
|
* { name: 'DATABASE_URI', description: 'MongoDB connection string' },
|
||||||
|
* { name: 'NEXT_PUBLIC_SERVER_URL', kind: 'url' },
|
||||||
|
* { name: 'NODE_ENV', oneOf: ['development', 'production', 'test'] },
|
||||||
|
* ])
|
||||||
|
*
|
||||||
|
* Runs server-side only (reads process.env) — never import it into a client
|
||||||
|
* component.
|
||||||
|
*/
|
||||||
|
export declare function assertEnv(rules: EnvRule[], options?: AssertEnvOptions): void;
|
||||||
Vendored
+101
@@ -0,0 +1,101 @@
|
|||||||
|
/**
|
||||||
|
* Zero-dependency environment validation. The plugin deliberately does NOT pull
|
||||||
|
* in zod — forcing a validation library on every project would be a dependency
|
||||||
|
* the project didn't ask for (against the A0 "no imposed deps" rule). This is a
|
||||||
|
* tiny validator that does the one thing we need: check the vars a deploy needs
|
||||||
|
* and FAIL FAST with a readable, all-at-once message instead of a cryptic
|
||||||
|
* runtime crash (e.g. `getaddrinfo ENOTFOUND` halfway through a Docker build).
|
||||||
|
*/ const EMAIL_RE = /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/;
|
||||||
|
/** Validate one present value against its rule. Returns an error message or null. */ function checkValue(rule, value) {
|
||||||
|
const { name, kind = 'string', oneOf } = rule;
|
||||||
|
if (oneOf && !oneOf.includes(value)) {
|
||||||
|
return `${name} must be one of: ${oneOf.join(', ')} (got "${value}")`;
|
||||||
|
}
|
||||||
|
switch(kind){
|
||||||
|
case 'boolean':
|
||||||
|
if (!/^(true|false|1|0|yes|no)$/i.test(value)) {
|
||||||
|
return `${name} must be a boolean (true/false/1/0/yes/no, got "${value}")`;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case 'email':
|
||||||
|
if (!EMAIL_RE.test(value)) {
|
||||||
|
return `${name} must be an e-mail address (got "${value}")`;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case 'number':
|
||||||
|
if (!Number.isFinite(Number(value))) {
|
||||||
|
return `${name} must be a number (got "${value}")`;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case 'port':
|
||||||
|
{
|
||||||
|
const n = Number(value);
|
||||||
|
if (!Number.isInteger(n) || n < 1 || n > 65535) {
|
||||||
|
return `${name} must be a port 1–65535 (got "${value}")`;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'url':
|
||||||
|
try {
|
||||||
|
new URL(value);
|
||||||
|
} catch {
|
||||||
|
return `${name} must be a valid URL (got "${value}")`;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case 'string':
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (rule.validate) {
|
||||||
|
const res = rule.validate(value);
|
||||||
|
if (res !== true) {
|
||||||
|
return typeof res === 'string' ? res : `${name} is invalid`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Validates the given rules against the environment and THROWS a single,
|
||||||
|
* aggregated error listing every problem at once (not just the first). Call it
|
||||||
|
* once at boot — in payload.config.ts, or Next's instrumentation.ts register().
|
||||||
|
*
|
||||||
|
* import { assertEnv, ipalEnvRules } from '@intecion/ipal-kit'
|
||||||
|
* assertEnv(ipalEnvRules({ storage: true, turnstile: true }))
|
||||||
|
*
|
||||||
|
* or with hand-written rules:
|
||||||
|
*
|
||||||
|
* assertEnv([
|
||||||
|
* { name: 'DATABASE_URI', description: 'MongoDB connection string' },
|
||||||
|
* { name: 'NEXT_PUBLIC_SERVER_URL', kind: 'url' },
|
||||||
|
* { name: 'NODE_ENV', oneOf: ['development', 'production', 'test'] },
|
||||||
|
* ])
|
||||||
|
*
|
||||||
|
* Runs server-side only (reads process.env) — never import it into a client
|
||||||
|
* component.
|
||||||
|
*/ export function assertEnv(rules, options = {}) {
|
||||||
|
const env = options.env ?? process.env;
|
||||||
|
const label = options.label ?? '[ipal]';
|
||||||
|
const problems = [];
|
||||||
|
for (const rule of rules){
|
||||||
|
const raw = env[rule.name];
|
||||||
|
const value = typeof raw === 'string' ? raw.trim() : '';
|
||||||
|
const required = rule.required !== false;
|
||||||
|
if (!value) {
|
||||||
|
if (required) {
|
||||||
|
problems.push(`${rule.name} is required but missing${rule.description ? ` — ${rule.description}` : ''}`);
|
||||||
|
}
|
||||||
|
continue; // optional + absent → nothing to check
|
||||||
|
}
|
||||||
|
const err = checkValue(rule, value);
|
||||||
|
if (err) {
|
||||||
|
problems.push(`${err}${rule.description ? ` — ${rule.description}` : ''}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (problems.length === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const message = `${label} Environment validation failed (${problems.length} ` + `problem${problems.length === 1 ? '' : 's'}):\n` + problems.map((p)=>` • ${p}`).join('\n') + `\nSet these in your environment (Coolify → Environment, or .env) and redeploy.`;
|
||||||
|
throw new Error(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
//# sourceMappingURL=assertEnv.js.map
|
||||||
Vendored
+1
File diff suppressed because one or more lines are too long
Vendored
+4
@@ -0,0 +1,4 @@
|
|||||||
|
export { assertEnv } from './assertEnv.js';
|
||||||
|
export type { EnvRule, EnvKind, AssertEnvOptions } from './assertEnv.js';
|
||||||
|
export { ipalEnvRules } from './ipalEnvRules.js';
|
||||||
|
export type { IpalEnvFeatures } from './ipalEnvRules.js';
|
||||||
Vendored
+4
@@ -0,0 +1,4 @@
|
|||||||
|
export { assertEnv } from './assertEnv.js';
|
||||||
|
export { ipalEnvRules } from './ipalEnvRules.js';
|
||||||
|
|
||||||
|
//# sourceMappingURL=index.js.map
|
||||||
Vendored
+1
@@ -0,0 +1 @@
|
|||||||
|
{"version":3,"sources":["../../../src/modules/env/index.ts"],"sourcesContent":["export { assertEnv } from './assertEnv.js'\nexport type { EnvRule, EnvKind, AssertEnvOptions } from './assertEnv.js'\nexport { ipalEnvRules } from './ipalEnvRules.js'\nexport type { IpalEnvFeatures } from './ipalEnvRules.js'\n"],"names":["assertEnv","ipalEnvRules"],"mappings":"AAAA,SAASA,SAAS,QAAQ,iBAAgB;AAE1C,SAASC,YAAY,QAAQ,oBAAmB"}
|
||||||
Vendored
+44
@@ -0,0 +1,44 @@
|
|||||||
|
import type { EnvRule } from './assertEnv.js';
|
||||||
|
type TurnstileNames = {
|
||||||
|
secretVar?: string;
|
||||||
|
siteKeyVar?: string;
|
||||||
|
};
|
||||||
|
export type IpalEnvFeatures = {
|
||||||
|
/** Override the database var. Default 'DATABASE_URI'. */
|
||||||
|
databaseVar?: string;
|
||||||
|
/** Microsoft Graph e-mail (graphAdapter). Adds the GRAPH_* vars. */
|
||||||
|
emailGraph?: boolean;
|
||||||
|
/** Override the Payload secret var. Default 'PAYLOAD_SECRET'. */
|
||||||
|
secretVar?: string;
|
||||||
|
/** Override the site-URL var. Default 'NEXT_PUBLIC_SERVER_URL'. */
|
||||||
|
serverUrlVar?: string;
|
||||||
|
/** R2 object storage (buildR2Storage). Adds the R2_* vars. */
|
||||||
|
storage?: boolean;
|
||||||
|
/**
|
||||||
|
* Cloudflare Turnstile. true uses the common var names
|
||||||
|
* (NEXT_PUBLIC_TURNSTILE_SITE_KEY + TURNSTILE_SECRET_KEY); pass an object to
|
||||||
|
* override either name if your project differs.
|
||||||
|
*/
|
||||||
|
turnstile?: boolean | TurnstileNames;
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* The env schema for a standard ipal-kit deploy, assembled from the features the
|
||||||
|
* project actually uses — so a site on local-disk storage isn't forced to set
|
||||||
|
* R2_*, and a site with no forms isn't forced to set Turnstile. Opt-in, not a
|
||||||
|
* fixed required set (A0: the plugin never demands config a project doesn't use).
|
||||||
|
*
|
||||||
|
* Variable names match what the plugin's own modules read (R2_*, GRAPH_*,
|
||||||
|
* NEXT_PUBLIC_SERVER_URL). DATABASE_URI and PAYLOAD_SECRET are Payload-core.
|
||||||
|
* Override any name via the options if your project names them differently.
|
||||||
|
*
|
||||||
|
* assertEnv(ipalEnvRules({ storage: true, emailGraph: true, turnstile: true }))
|
||||||
|
*
|
||||||
|
* Extend with project-specific vars by spreading:
|
||||||
|
*
|
||||||
|
* assertEnv([
|
||||||
|
* ...ipalEnvRules({ storage: true }),
|
||||||
|
* { name: 'MY_API_KEY', description: 'Third-party integration key' },
|
||||||
|
* ])
|
||||||
|
*/
|
||||||
|
export declare function ipalEnvRules(features?: IpalEnvFeatures): EnvRule[];
|
||||||
|
export {};
|
||||||
Vendored
+95
@@ -0,0 +1,95 @@
|
|||||||
|
/**
|
||||||
|
* The env schema for a standard ipal-kit deploy, assembled from the features the
|
||||||
|
* project actually uses — so a site on local-disk storage isn't forced to set
|
||||||
|
* R2_*, and a site with no forms isn't forced to set Turnstile. Opt-in, not a
|
||||||
|
* fixed required set (A0: the plugin never demands config a project doesn't use).
|
||||||
|
*
|
||||||
|
* Variable names match what the plugin's own modules read (R2_*, GRAPH_*,
|
||||||
|
* NEXT_PUBLIC_SERVER_URL). DATABASE_URI and PAYLOAD_SECRET are Payload-core.
|
||||||
|
* Override any name via the options if your project names them differently.
|
||||||
|
*
|
||||||
|
* assertEnv(ipalEnvRules({ storage: true, emailGraph: true, turnstile: true }))
|
||||||
|
*
|
||||||
|
* Extend with project-specific vars by spreading:
|
||||||
|
*
|
||||||
|
* assertEnv([
|
||||||
|
* ...ipalEnvRules({ storage: true }),
|
||||||
|
* { name: 'MY_API_KEY', description: 'Third-party integration key' },
|
||||||
|
* ])
|
||||||
|
*/ export function ipalEnvRules(features = {}) {
|
||||||
|
const { databaseVar = 'DATABASE_URI', emailGraph = false, secretVar = 'PAYLOAD_SECRET', serverUrlVar = 'NEXT_PUBLIC_SERVER_URL', storage = false, turnstile = false } = features;
|
||||||
|
const rules = [
|
||||||
|
{
|
||||||
|
name: databaseVar,
|
||||||
|
description: 'Database connection string (e.g. MongoDB URI)'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: secretVar,
|
||||||
|
description: 'Payload secret used to sign tokens'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: serverUrlVar,
|
||||||
|
description: 'Public site origin, e.g. https://example.com',
|
||||||
|
kind: 'url'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'NODE_ENV',
|
||||||
|
description: 'Node environment',
|
||||||
|
oneOf: [
|
||||||
|
'development',
|
||||||
|
'production',
|
||||||
|
'test'
|
||||||
|
],
|
||||||
|
required: false
|
||||||
|
}
|
||||||
|
];
|
||||||
|
if (storage) {
|
||||||
|
rules.push({
|
||||||
|
name: 'R2_BUCKET',
|
||||||
|
description: 'R2 bucket name'
|
||||||
|
}, {
|
||||||
|
name: 'R2_ACCESS_KEY_ID',
|
||||||
|
description: 'R2 access key id'
|
||||||
|
}, {
|
||||||
|
name: 'R2_SECRET_ACCESS_KEY',
|
||||||
|
description: 'R2 secret access key'
|
||||||
|
}, {
|
||||||
|
name: 'R2_ENDPOINT',
|
||||||
|
description: 'R2 S3 API endpoint URL',
|
||||||
|
kind: 'url'
|
||||||
|
}, {
|
||||||
|
name: 'R2_PUBLIC_URL',
|
||||||
|
description: 'Public base URL media is served from',
|
||||||
|
kind: 'url'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (emailGraph) {
|
||||||
|
rules.push({
|
||||||
|
name: 'GRAPH_TENANT_ID',
|
||||||
|
description: 'Microsoft Graph tenant id'
|
||||||
|
}, {
|
||||||
|
name: 'GRAPH_CLIENT_ID',
|
||||||
|
description: 'Microsoft Graph client id'
|
||||||
|
}, {
|
||||||
|
name: 'GRAPH_CLIENT_SECRET',
|
||||||
|
description: 'Microsoft Graph client secret'
|
||||||
|
}, {
|
||||||
|
name: 'GRAPH_SENDER',
|
||||||
|
description: 'From-address mail is sent as',
|
||||||
|
kind: 'email'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (turnstile) {
|
||||||
|
const names = typeof turnstile === 'object' ? turnstile : {};
|
||||||
|
rules.push({
|
||||||
|
name: names.siteKeyVar ?? 'NEXT_PUBLIC_TURNSTILE_SITE_KEY',
|
||||||
|
description: 'Cloudflare Turnstile public site key'
|
||||||
|
}, {
|
||||||
|
name: names.secretVar ?? 'TURNSTILE_SECRET_KEY',
|
||||||
|
description: 'Cloudflare Turnstile secret key'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return rules;
|
||||||
|
}
|
||||||
|
|
||||||
|
//# sourceMappingURL=ipalEnvRules.js.map
|
||||||
Vendored
+1
File diff suppressed because one or more lines are too long
Vendored
+46
@@ -0,0 +1,46 @@
|
|||||||
|
/**
|
||||||
|
* A honeypot: a hidden field real users never see or fill, but naive bots do.
|
||||||
|
* A cheap, zero-friction second layer alongside Turnstile — no network call, no
|
||||||
|
* user interaction. Pure functions, usable on client (render the input) and
|
||||||
|
* server (check it in the action).
|
||||||
|
*/
|
||||||
|
/**
|
||||||
|
* Default field name. Looks like a real field a bot would want to fill, but is
|
||||||
|
* not one your form uses. Override per project if you like — just keep the
|
||||||
|
* client and server in sync.
|
||||||
|
*/
|
||||||
|
export declare const HONEYPOT_FIELD = "company_url";
|
||||||
|
/**
|
||||||
|
* Props for the hidden input. Hidden from sight AND from assistive tech and tab
|
||||||
|
* order, so no real user (sighted, screen-reader, or keyboard) ever fills it —
|
||||||
|
* only a bot auto-filling every field.
|
||||||
|
*
|
||||||
|
* <input {...honeypotInputProps()} />
|
||||||
|
* // or with your own name:
|
||||||
|
* <input {...honeypotInputProps('website_2')} />
|
||||||
|
*/
|
||||||
|
export declare function honeypotInputProps(name?: string): {
|
||||||
|
name: string;
|
||||||
|
type: "text";
|
||||||
|
'aria-hidden': boolean;
|
||||||
|
autoComplete: "off";
|
||||||
|
tabIndex: number;
|
||||||
|
style: {
|
||||||
|
height: string;
|
||||||
|
left: string;
|
||||||
|
overflow: "hidden";
|
||||||
|
position: "absolute";
|
||||||
|
width: string;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* True when the honeypot was filled → treat the submission as spam and drop it
|
||||||
|
* (silently return success so the bot gets no signal). Call it FIRST in your
|
||||||
|
* server action, before submitForm:
|
||||||
|
*
|
||||||
|
* if (isHoneypotTripped(values)) return { success: true } // pretend-accept
|
||||||
|
* // strip it so submitForm doesn't see an unknown field:
|
||||||
|
* const { [HONEYPOT_FIELD]: _hp, ...clean } = values
|
||||||
|
* return submitForm({ ...clean })
|
||||||
|
*/
|
||||||
|
export declare function isHoneypotTripped(values: Record<string, unknown>, name?: string): boolean;
|
||||||
Vendored
+50
@@ -0,0 +1,50 @@
|
|||||||
|
/**
|
||||||
|
* A honeypot: a hidden field real users never see or fill, but naive bots do.
|
||||||
|
* A cheap, zero-friction second layer alongside Turnstile — no network call, no
|
||||||
|
* user interaction. Pure functions, usable on client (render the input) and
|
||||||
|
* server (check it in the action).
|
||||||
|
*/ /**
|
||||||
|
* Default field name. Looks like a real field a bot would want to fill, but is
|
||||||
|
* not one your form uses. Override per project if you like — just keep the
|
||||||
|
* client and server in sync.
|
||||||
|
*/ export const HONEYPOT_FIELD = 'company_url';
|
||||||
|
/**
|
||||||
|
* Props for the hidden input. Hidden from sight AND from assistive tech and tab
|
||||||
|
* order, so no real user (sighted, screen-reader, or keyboard) ever fills it —
|
||||||
|
* only a bot auto-filling every field.
|
||||||
|
*
|
||||||
|
* <input {...honeypotInputProps()} />
|
||||||
|
* // or with your own name:
|
||||||
|
* <input {...honeypotInputProps('website_2')} />
|
||||||
|
*/ export function honeypotInputProps(name = HONEYPOT_FIELD) {
|
||||||
|
return {
|
||||||
|
name,
|
||||||
|
type: 'text',
|
||||||
|
'aria-hidden': true,
|
||||||
|
autoComplete: 'off',
|
||||||
|
tabIndex: -1,
|
||||||
|
// Off-screen rather than display:none — some bots skip display:none fields.
|
||||||
|
style: {
|
||||||
|
height: '1px',
|
||||||
|
left: '-9999px',
|
||||||
|
overflow: 'hidden',
|
||||||
|
position: 'absolute',
|
||||||
|
width: '1px'
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* True when the honeypot was filled → treat the submission as spam and drop it
|
||||||
|
* (silently return success so the bot gets no signal). Call it FIRST in your
|
||||||
|
* server action, before submitForm:
|
||||||
|
*
|
||||||
|
* if (isHoneypotTripped(values)) return { success: true } // pretend-accept
|
||||||
|
* // strip it so submitForm doesn't see an unknown field:
|
||||||
|
* const { [HONEYPOT_FIELD]: _hp, ...clean } = values
|
||||||
|
* return submitForm({ ...clean })
|
||||||
|
*/ export function isHoneypotTripped(values, name = HONEYPOT_FIELD) {
|
||||||
|
const v = values[name];
|
||||||
|
return typeof v === 'string' ? v.trim().length > 0 : v != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
//# sourceMappingURL=honeypot.js.map
|
||||||
Vendored
+1
@@ -0,0 +1 @@
|
|||||||
|
{"version":3,"sources":["../../../src/modules/forms/honeypot.ts"],"sourcesContent":["/**\n * A honeypot: a hidden field real users never see or fill, but naive bots do.\n * A cheap, zero-friction second layer alongside Turnstile — no network call, no\n * user interaction. Pure functions, usable on client (render the input) and\n * server (check it in the action).\n */\n\n/**\n * Default field name. Looks like a real field a bot would want to fill, but is\n * not one your form uses. Override per project if you like — just keep the\n * client and server in sync.\n */\nexport const HONEYPOT_FIELD = 'company_url'\n\n/**\n * Props for the hidden input. Hidden from sight AND from assistive tech and tab\n * order, so no real user (sighted, screen-reader, or keyboard) ever fills it —\n * only a bot auto-filling every field.\n *\n * <input {...honeypotInputProps()} />\n * // or with your own name:\n * <input {...honeypotInputProps('website_2')} />\n */\nexport function honeypotInputProps(name: string = HONEYPOT_FIELD) {\n return {\n name,\n type: 'text' as const,\n 'aria-hidden': true,\n autoComplete: 'off' as const,\n tabIndex: -1,\n // Off-screen rather than display:none — some bots skip display:none fields.\n style: {\n height: '1px',\n left: '-9999px',\n overflow: 'hidden' as const,\n position: 'absolute' as const,\n width: '1px',\n },\n }\n}\n\n/**\n * True when the honeypot was filled → treat the submission as spam and drop it\n * (silently return success so the bot gets no signal). Call it FIRST in your\n * server action, before submitForm:\n *\n * if (isHoneypotTripped(values)) return { success: true } // pretend-accept\n * // strip it so submitForm doesn't see an unknown field:\n * const { [HONEYPOT_FIELD]: _hp, ...clean } = values\n * return submitForm({ ...clean })\n */\nexport function isHoneypotTripped(\n values: Record<string, unknown>,\n name: string = HONEYPOT_FIELD,\n): boolean {\n const v = values[name]\n return typeof v === 'string' ? v.trim().length > 0 : v != null\n}\n"],"names":["HONEYPOT_FIELD","honeypotInputProps","name","type","autoComplete","tabIndex","style","height","left","overflow","position","width","isHoneypotTripped","values","v","trim","length"],"mappings":"AAAA;;;;;CAKC,GAED;;;;CAIC,GACD,OAAO,MAAMA,iBAAiB,cAAa;AAE3C;;;;;;;;CAQC,GACD,OAAO,SAASC,mBAAmBC,OAAeF,cAAc;IAC9D,OAAO;QACLE;QACAC,MAAM;QACN,eAAe;QACfC,cAAc;QACdC,UAAU,CAAC;QACX,4EAA4E;QAC5EC,OAAO;YACLC,QAAQ;YACRC,MAAM;YACNC,UAAU;YACVC,UAAU;YACVC,OAAO;QACT;IACF;AACF;AAEA;;;;;;;;;CASC,GACD,OAAO,SAASC,kBACdC,MAA+B,EAC/BX,OAAeF,cAAc;IAE7B,MAAMc,IAAID,MAAM,CAACX,KAAK;IACtB,OAAO,OAAOY,MAAM,WAAWA,EAAEC,IAAI,GAAGC,MAAM,GAAG,IAAIF,KAAK;AAC5D"}
|
||||||
Vendored
+5
@@ -1,4 +1,5 @@
|
|||||||
export { buildFormsPlugin } from './formsPluginConfig.js';
|
export { buildFormsPlugin } from './formsPluginConfig.js';
|
||||||
|
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './honeypot.js';
|
||||||
export { checkRateLimit } from './rateLimit.js';
|
export { checkRateLimit } from './rateLimit.js';
|
||||||
export type { RateLimitArgs } from './rateLimit.js';
|
export type { RateLimitArgs } from './rateLimit.js';
|
||||||
export { submitForm } from './submitForm.js';
|
export { submitForm } from './submitForm.js';
|
||||||
@@ -6,5 +7,9 @@ export type { SubmitFormArgs, SubmitFormResult } from './submitForm.js';
|
|||||||
export type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption } from './types.js';
|
export type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption } from './types.js';
|
||||||
export { useContactForm } from './useContactForm.js';
|
export { useContactForm } from './useContactForm.js';
|
||||||
export type { ContactFormErrors, ContactFormValues, SubmitAction } from './useContactForm.js';
|
export type { ContactFormErrors, ContactFormValues, SubmitAction } from './useContactForm.js';
|
||||||
|
export { useForm } from './useForm.js';
|
||||||
|
export type { FormErrors, FormSubmitAction, Validator } from './useForm.js';
|
||||||
export { validateSubmission } from './validateSubmission.js';
|
export { validateSubmission } from './validateSubmission.js';
|
||||||
export type { FormValidationResult } from './validateSubmission.js';
|
export type { FormValidationResult } from './validateSubmission.js';
|
||||||
|
export { buildValidator, checked, custom, email, isEmail, maxLength, minLength, pattern, required, } from './validators.js';
|
||||||
|
export type { Rule } from './validators.js';
|
||||||
|
|||||||
Vendored
+6
@@ -1,9 +1,15 @@
|
|||||||
// buildFormsPlugin is config-time (safe anywhere). submitForm is server-only
|
// buildFormsPlugin is config-time (safe anywhere). submitForm is server-only
|
||||||
// (Turnstile secret) — never import it from a client component.
|
// (Turnstile secret) — never import it from a client component.
|
||||||
export { buildFormsPlugin } from './formsPluginConfig.js';
|
export { buildFormsPlugin } from './formsPluginConfig.js';
|
||||||
|
// Honeypot anti-spam (pure — client renders the input, server checks it).
|
||||||
|
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './honeypot.js';
|
||||||
export { checkRateLimit } from './rateLimit.js';
|
export { checkRateLimit } from './rateLimit.js';
|
||||||
export { submitForm } from './submitForm.js';
|
export { submitForm } from './submitForm.js';
|
||||||
export { useContactForm } from './useContactForm.js';
|
export { useContactForm } from './useContactForm.js';
|
||||||
|
// Generic form engine (any field set) + the standard contact-form preset.
|
||||||
|
export { useForm } from './useForm.js';
|
||||||
export { validateSubmission } from './validateSubmission.js';
|
export { validateSubmission } from './validateSubmission.js';
|
||||||
|
// Composable validation rules (pure — safe on server or client).
|
||||||
|
export { buildValidator, checked, custom, email, isEmail, maxLength, minLength, pattern, required } from './validators.js';
|
||||||
|
|
||||||
//# sourceMappingURL=index.js.map
|
//# sourceMappingURL=index.js.map
|
||||||
Vendored
+1
-1
@@ -1 +1 @@
|
|||||||
{"version":3,"sources":["../../../src/modules/forms/index.ts"],"sourcesContent":["// buildFormsPlugin is config-time (safe anywhere). submitForm is server-only\n// (Turnstile secret) — never import it from a client component.\nexport { buildFormsPlugin } from './formsPluginConfig.js'\nexport { checkRateLimit } from './rateLimit.js'\nexport type { RateLimitArgs } from './rateLimit.js'\nexport { submitForm } from './submitForm.js'\nexport type { SubmitFormArgs, SubmitFormResult } from './submitForm.js'\nexport type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption } from './types.js'\nexport { useContactForm } from './useContactForm.js'\nexport type { ContactFormErrors, ContactFormValues, SubmitAction } from './useContactForm.js'\nexport { validateSubmission } from './validateSubmission.js'\nexport type { FormValidationResult } from './validateSubmission.js'\n"],"names":["buildFormsPlugin","checkRateLimit","submitForm","useContactForm","validateSubmission"],"mappings":"AAAA,6EAA6E;AAC7E,gEAAgE;AAChE,SAASA,gBAAgB,QAAQ,yBAAwB;AACzD,SAASC,cAAc,QAAQ,iBAAgB;AAE/C,SAASC,UAAU,QAAQ,kBAAiB;AAG5C,SAASC,cAAc,QAAQ,sBAAqB;AAEpD,SAASC,kBAAkB,QAAQ,0BAAyB"}
|
{"version":3,"sources":["../../../src/modules/forms/index.ts"],"sourcesContent":["// buildFormsPlugin is config-time (safe anywhere). submitForm is server-only\n// (Turnstile secret) — never import it from a client component.\nexport { buildFormsPlugin } from './formsPluginConfig.js'\n// Honeypot anti-spam (pure — client renders the input, server checks it).\nexport { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './honeypot.js'\nexport { checkRateLimit } from './rateLimit.js'\nexport type { RateLimitArgs } from './rateLimit.js'\nexport { submitForm } from './submitForm.js'\nexport type { SubmitFormArgs, SubmitFormResult } from './submitForm.js'\nexport type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption } from './types.js'\nexport { useContactForm } from './useContactForm.js'\nexport type { ContactFormErrors, ContactFormValues, SubmitAction } from './useContactForm.js'\n// Generic form engine (any field set) + the standard contact-form preset.\nexport { useForm } from './useForm.js'\nexport type { FormErrors, FormSubmitAction, Validator } from './useForm.js'\nexport { validateSubmission } from './validateSubmission.js'\nexport type { FormValidationResult } from './validateSubmission.js'\n// Composable validation rules (pure — safe on server or client).\nexport {\n buildValidator,\n checked,\n custom,\n email,\n isEmail,\n maxLength,\n minLength,\n pattern,\n required,\n} from './validators.js'\nexport type { Rule } from './validators.js'\n"],"names":["buildFormsPlugin","HONEYPOT_FIELD","honeypotInputProps","isHoneypotTripped","checkRateLimit","submitForm","useContactForm","useForm","validateSubmission","buildValidator","checked","custom","email","isEmail","maxLength","minLength","pattern","required"],"mappings":"AAAA,6EAA6E;AAC7E,gEAAgE;AAChE,SAASA,gBAAgB,QAAQ,yBAAwB;AACzD,0EAA0E;AAC1E,SAASC,cAAc,EAAEC,kBAAkB,EAAEC,iBAAiB,QAAQ,gBAAe;AACrF,SAASC,cAAc,QAAQ,iBAAgB;AAE/C,SAASC,UAAU,QAAQ,kBAAiB;AAG5C,SAASC,cAAc,QAAQ,sBAAqB;AAEpD,0EAA0E;AAC1E,SAASC,OAAO,QAAQ,eAAc;AAEtC,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,iEAAiE;AACjE,SACEC,cAAc,EACdC,OAAO,EACPC,MAAM,EACNC,KAAK,EACLC,OAAO,EACPC,SAAS,EACTC,SAAS,EACTC,OAAO,EACPC,QAAQ,QACH,kBAAiB"}
|
||||||
+28
-32
@@ -1,5 +1,9 @@
|
|||||||
import type { SubmitFormResult } from './submitForm.js';
|
import { type FormSubmitAction } from './useForm.js';
|
||||||
/** Field values the form tracks. Projects add/remove keys freely. */
|
/**
|
||||||
|
* Field values of the STANDARD contact form. This is a preset shape — projects
|
||||||
|
* that need a different field set (or dynamic builder fields) should use
|
||||||
|
* `useForm` directly instead, where the shape is fully open.
|
||||||
|
*/
|
||||||
export type ContactFormValues = {
|
export type ContactFormValues = {
|
||||||
consent: boolean;
|
consent: boolean;
|
||||||
email: string;
|
email: string;
|
||||||
@@ -8,20 +12,14 @@ export type ContactFormValues = {
|
|||||||
phone: string;
|
phone: string;
|
||||||
topic: string;
|
topic: string;
|
||||||
};
|
};
|
||||||
export type ContactFormErrors = Partial<Record<keyof ContactFormValues, boolean>>;
|
export type ContactFormErrors = Partial<Record<keyof ContactFormValues, string>>;
|
||||||
/**
|
export type SubmitAction = FormSubmitAction<ContactFormValues>;
|
||||||
* The project's server action that calls submitForm (server-only, holds the
|
|
||||||
* Turnstile secret). The hook is a client hook, so it can't call submitForm
|
|
||||||
* directly — the project injects its action.
|
|
||||||
*/
|
|
||||||
export type SubmitAction = (values: ContactFormValues, turnstileToken?: string) => Promise<{
|
|
||||||
message?: string;
|
|
||||||
success: boolean;
|
|
||||||
} | SubmitFormResult>;
|
|
||||||
type UseContactFormOptions = {
|
type UseContactFormOptions = {
|
||||||
/** Generic error message shown when the action throws. */
|
/** Generic error message shown when the action fails/throws. */
|
||||||
errorFallback?: string;
|
errorFallback?: string;
|
||||||
initialTopic?: string;
|
initialTopic?: string;
|
||||||
|
/** Override the per-field error message (shown via `errors.<field>`). */
|
||||||
|
messages?: Partial<Record<keyof ContactFormValues, string>>;
|
||||||
/** Minimum message length. Default 10. */
|
/** Minimum message length. Default 10. */
|
||||||
minMessageLength?: number;
|
minMessageLength?: number;
|
||||||
/** Whether consent is required (project passes true when consentText shown). */
|
/** Whether consent is required (project passes true when consentText shown). */
|
||||||
@@ -33,32 +31,30 @@ type UseContactFormOptions = {
|
|||||||
submitAction: SubmitAction;
|
submitAction: SubmitAction;
|
||||||
};
|
};
|
||||||
/**
|
/**
|
||||||
* All contact-form logic (state, validation, Turnstile token, submit, success)
|
* Zero-config preset over `useForm` for the everyday contact form: standard
|
||||||
* WITHOUT any markup — the project owns 100% of the look. Replaces the ~150
|
* fields (name/email/phone/topic/message/consent) and standard rules, wired
|
||||||
* lines of identical logic copied into every project's ContactForm, while the
|
* for you. Markup and styling stay 100% in the project — this only removes the
|
||||||
* project keeps full control over field layout and styling.
|
* duplicated logic.
|
||||||
*
|
*
|
||||||
* const f = useContactForm({ submitAction, requireTurnstile: Boolean(siteKey),
|
* const f = useContactForm({ submitAction, requireTurnstile: Boolean(siteKey),
|
||||||
* requireTopic: topics.length > 0, requireConsent: Boolean(consentText) })
|
* requireTopic: topics.length > 0, requireConsent: Boolean(consentText) })
|
||||||
* // in JSX — your own fields/classes:
|
*
|
||||||
* <input value={f.values.name} onChange={(e) => f.setField('name', e.target.value)}
|
* Need custom or dynamic fields? Drop the preset and call `useForm` + validators.
|
||||||
* className={f.errors.name ? 'border-red-500' : '…'} />
|
|
||||||
* <Turnstile siteKey={siteKey} onToken={f.setTurnstileToken} />
|
|
||||||
* <form onSubmit={f.handleSubmit}>…</form>
|
|
||||||
* {f.isSuccess && <YourSuccessPanel onReset={f.reset} />}
|
|
||||||
*/
|
*/
|
||||||
export declare function useContactForm(options: UseContactFormOptions): {
|
export declare function useContactForm(options: UseContactFormOptions): {
|
||||||
errorMessage: string | null;
|
values: ContactFormValues;
|
||||||
errors: Partial<Record<keyof ContactFormValues, boolean>>;
|
errors: Partial<Record<keyof ContactFormValues, string>>;
|
||||||
handleSubmit: (e: {
|
|
||||||
preventDefault: () => void;
|
|
||||||
}) => Promise<void>;
|
|
||||||
isSubmitting: boolean;
|
isSubmitting: boolean;
|
||||||
isSuccess: boolean;
|
isSuccess: boolean;
|
||||||
reset: () => void;
|
errorMessage: string | null;
|
||||||
setField: <K extends keyof ContactFormValues>(key: K, value: ContactFormValues[K]) => void;
|
|
||||||
setTurnstileToken: import("react").Dispatch<import("react").SetStateAction<string | null>>;
|
|
||||||
turnstileToken: string | null;
|
turnstileToken: string | null;
|
||||||
values: ContactFormValues;
|
setField: <K extends keyof ContactFormValues>(key: K, value: ContactFormValues[K]) => void;
|
||||||
|
setValues: import("react").Dispatch<import("react").SetStateAction<ContactFormValues>>;
|
||||||
|
setErrors: import("react").Dispatch<import("react").SetStateAction<Partial<Record<keyof ContactFormValues, string>>>>;
|
||||||
|
setTurnstileToken: import("react").Dispatch<import("react").SetStateAction<string | null>>;
|
||||||
|
handleSubmit: (e?: {
|
||||||
|
preventDefault?: (() => void) | undefined;
|
||||||
|
} | undefined) => Promise<void>;
|
||||||
|
reset: () => void;
|
||||||
};
|
};
|
||||||
export {};
|
export {};
|
||||||
|
|||||||
Vendored
+48
-113
@@ -1,126 +1,61 @@
|
|||||||
'use client';
|
'use client';
|
||||||
import { useCallback, useState } from 'react';
|
import { useMemo } from 'react';
|
||||||
const EMAIL_RE = /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/;
|
import { useForm } from './useForm.js';
|
||||||
const EMPTY = {
|
import { buildValidator, checked, email, minLength, required } from './validators.js';
|
||||||
name: '',
|
|
||||||
consent: false,
|
|
||||||
email: '',
|
|
||||||
message: '',
|
|
||||||
phone: '',
|
|
||||||
topic: ''
|
|
||||||
};
|
|
||||||
/**
|
/**
|
||||||
* All contact-form logic (state, validation, Turnstile token, submit, success)
|
* Zero-config preset over `useForm` for the everyday contact form: standard
|
||||||
* WITHOUT any markup — the project owns 100% of the look. Replaces the ~150
|
* fields (name/email/phone/topic/message/consent) and standard rules, wired
|
||||||
* lines of identical logic copied into every project's ContactForm, while the
|
* for you. Markup and styling stay 100% in the project — this only removes the
|
||||||
* project keeps full control over field layout and styling.
|
* duplicated logic.
|
||||||
*
|
*
|
||||||
* const f = useContactForm({ submitAction, requireTurnstile: Boolean(siteKey),
|
* const f = useContactForm({ submitAction, requireTurnstile: Boolean(siteKey),
|
||||||
* requireTopic: topics.length > 0, requireConsent: Boolean(consentText) })
|
* requireTopic: topics.length > 0, requireConsent: Boolean(consentText) })
|
||||||
* // in JSX — your own fields/classes:
|
*
|
||||||
* <input value={f.values.name} onChange={(e) => f.setField('name', e.target.value)}
|
* Need custom or dynamic fields? Drop the preset and call `useForm` + validators.
|
||||||
* className={f.errors.name ? 'border-red-500' : '…'} />
|
|
||||||
* <Turnstile siteKey={siteKey} onToken={f.setTurnstileToken} />
|
|
||||||
* <form onSubmit={f.handleSubmit}>…</form>
|
|
||||||
* {f.isSuccess && <YourSuccessPanel onReset={f.reset} />}
|
|
||||||
*/ export function useContactForm(options) {
|
*/ export function useContactForm(options) {
|
||||||
const { errorFallback = 'Something went wrong. Please try again.', initialTopic = '', minMessageLength = 10, requireConsent = false, requireTopic = false, requireTurnstile = false, submitAction } = options;
|
const { errorFallback, initialTopic = '', messages, minMessageLength = 10, requireConsent = false, requireTopic = false, requireTurnstile = false, submitAction } = options;
|
||||||
const [values, setValues] = useState({
|
const validate = useMemo(()=>buildValidator({
|
||||||
...EMPTY,
|
name: [
|
||||||
topic: initialTopic
|
required(messages?.name)
|
||||||
});
|
],
|
||||||
const [errors, setErrors] = useState({});
|
email: [
|
||||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
required(messages?.email),
|
||||||
const [isSuccess, setIsSuccess] = useState(false);
|
email(messages?.email)
|
||||||
const [errorMessage, setErrorMessage] = useState(null);
|
],
|
||||||
const [turnstileToken, setTurnstileToken] = useState(null);
|
...requireTopic ? {
|
||||||
const setField = useCallback((key, value)=>{
|
topic: [
|
||||||
setValues((prev)=>({
|
required(messages?.topic)
|
||||||
...prev,
|
]
|
||||||
[key]: value
|
} : {},
|
||||||
}));
|
message: [
|
||||||
}, []);
|
required(messages?.message),
|
||||||
const validate = useCallback(()=>{
|
minLength(minMessageLength, messages?.message)
|
||||||
const errs = {};
|
],
|
||||||
if (!values.name.trim()) {
|
...requireConsent ? {
|
||||||
errs.name = true;
|
consent: [
|
||||||
}
|
checked(messages?.consent)
|
||||||
if (!values.email.trim() || !EMAIL_RE.test(values.email)) {
|
]
|
||||||
errs.email = true;
|
} : {}
|
||||||
}
|
}), [
|
||||||
if (requireTopic && !values.topic) {
|
|
||||||
errs.topic = true;
|
|
||||||
}
|
|
||||||
if (!values.message.trim() || values.message.length < minMessageLength) {
|
|
||||||
errs.message = true;
|
|
||||||
}
|
|
||||||
if (requireConsent && !values.consent) {
|
|
||||||
errs.consent = true;
|
|
||||||
}
|
|
||||||
setErrors(errs);
|
|
||||||
return Object.keys(errs).length === 0;
|
|
||||||
}, [
|
|
||||||
values,
|
|
||||||
requireTopic,
|
requireTopic,
|
||||||
requireConsent,
|
requireConsent,
|
||||||
minMessageLength
|
minMessageLength,
|
||||||
|
messages
|
||||||
]);
|
]);
|
||||||
const handleSubmit = useCallback(async (e)=>{
|
return useForm({
|
||||||
e.preventDefault();
|
errorFallback,
|
||||||
setErrorMessage(null);
|
initialValues: {
|
||||||
if (!validate()) {
|
name: '',
|
||||||
return;
|
consent: false,
|
||||||
}
|
email: '',
|
||||||
if (requireTurnstile && !turnstileToken) {
|
message: '',
|
||||||
setErrorMessage(errorFallback);
|
phone: '',
|
||||||
return;
|
|
||||||
}
|
|
||||||
setIsSubmitting(true);
|
|
||||||
try {
|
|
||||||
const result = await submitAction(values, turnstileToken ?? undefined);
|
|
||||||
if (result.success) {
|
|
||||||
setIsSuccess(true);
|
|
||||||
setTurnstileToken(null);
|
|
||||||
} else {
|
|
||||||
setErrorMessage('message' in result && result.message || errorFallback);
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
setErrorMessage(err instanceof Error ? err.message : errorFallback);
|
|
||||||
} finally{
|
|
||||||
setIsSubmitting(false);
|
|
||||||
}
|
|
||||||
}, [
|
|
||||||
validate,
|
|
||||||
requireTurnstile,
|
|
||||||
turnstileToken,
|
|
||||||
submitAction,
|
|
||||||
values,
|
|
||||||
errorFallback
|
|
||||||
]);
|
|
||||||
const reset = useCallback(()=>{
|
|
||||||
setValues({
|
|
||||||
...EMPTY,
|
|
||||||
topic: initialTopic
|
topic: initialTopic
|
||||||
});
|
},
|
||||||
setErrors({});
|
requireTurnstile,
|
||||||
setIsSuccess(false);
|
submitAction,
|
||||||
setErrorMessage(null);
|
validate
|
||||||
setTurnstileToken(null);
|
});
|
||||||
}, [
|
|
||||||
initialTopic
|
|
||||||
]);
|
|
||||||
return {
|
|
||||||
errorMessage,
|
|
||||||
errors,
|
|
||||||
handleSubmit,
|
|
||||||
isSubmitting,
|
|
||||||
isSuccess,
|
|
||||||
reset,
|
|
||||||
setField,
|
|
||||||
setTurnstileToken,
|
|
||||||
turnstileToken,
|
|
||||||
values
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//# sourceMappingURL=useContactForm.js.map
|
//# sourceMappingURL=useContactForm.js.map
|
||||||
+1
-1
File diff suppressed because one or more lines are too long
Vendored
+70
@@ -0,0 +1,70 @@
|
|||||||
|
/**
|
||||||
|
* Error map: a field key → its error message. A field is "in error" iff it has
|
||||||
|
* a key here, so `errors.email` is both the truthy flag (for a red border) AND
|
||||||
|
* the message (to display). Empty object = valid.
|
||||||
|
*/
|
||||||
|
export type FormErrors<T> = Partial<Record<keyof T, string>>;
|
||||||
|
/**
|
||||||
|
* The project's server action that calls submitForm (server-only, holds the
|
||||||
|
* Turnstile secret). This hook is a client hook, so it can't call submitForm
|
||||||
|
* directly — the project injects its action. The result only needs `success`
|
||||||
|
* plus an optional `message`; richer shapes (SubmitFormResult) satisfy it.
|
||||||
|
*/
|
||||||
|
export type FormSubmitAction<T> = (values: T, turnstileToken?: string) => Promise<{
|
||||||
|
success: boolean;
|
||||||
|
message?: string;
|
||||||
|
}>;
|
||||||
|
/** Turns the current values into an error map. Empty map = valid. */
|
||||||
|
export type Validator<T> = (values: T) => FormErrors<T>;
|
||||||
|
type UseFormOptions<T extends Record<string, unknown>> = {
|
||||||
|
/** Defines the field set AND the reset state. Any shape you like. */
|
||||||
|
initialValues: T;
|
||||||
|
submitAction: FormSubmitAction<T>;
|
||||||
|
/** Project-owned validation. Compose one with `buildValidator` + rules, or write your own. */
|
||||||
|
validate?: Validator<T>;
|
||||||
|
/** Require a Turnstile token before submit (when the widget is shown). */
|
||||||
|
requireTurnstile?: boolean;
|
||||||
|
/** Generic error message shown when the action fails/throws with no message. */
|
||||||
|
errorFallback?: string;
|
||||||
|
/** Clear a field's error as soon as the user edits it. Default true. */
|
||||||
|
clearErrorOnChange?: boolean;
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* Fully generic form engine: state, validation, Turnstile token, submit,
|
||||||
|
* success/error — WITHOUT any markup. The project owns 100% of the look AND
|
||||||
|
* the field set: there is no baked-in shape here. Replaces the identical
|
||||||
|
* ~150 lines of form plumbing copied into every project.
|
||||||
|
*
|
||||||
|
* The field set comes from `initialValues`; the rules come from `validate`
|
||||||
|
* (so dynamic/builder-driven forms just build both at runtime). For the
|
||||||
|
* everyday contact form use the `useContactForm` preset instead — it wires
|
||||||
|
* the standard fields and rules for you.
|
||||||
|
*
|
||||||
|
* const f = useForm({
|
||||||
|
* initialValues: { email: '', message: '' },
|
||||||
|
* submitAction, // your server action
|
||||||
|
* validate: buildValidator({ email: [required(), email()], message: [required()] }),
|
||||||
|
* requireTurnstile: Boolean(siteKey),
|
||||||
|
* })
|
||||||
|
* <input value={f.values.email}
|
||||||
|
* onChange={(e) => f.setField('email', e.target.value)}
|
||||||
|
* className={f.errors.email ? 'border-red-500' : '…'} />
|
||||||
|
* <form onSubmit={f.handleSubmit}>…</form>
|
||||||
|
*/
|
||||||
|
export declare function useForm<T extends Record<string, unknown>>(options: UseFormOptions<T>): {
|
||||||
|
values: T;
|
||||||
|
errors: Partial<Record<keyof T, string>>;
|
||||||
|
isSubmitting: boolean;
|
||||||
|
isSuccess: boolean;
|
||||||
|
errorMessage: string | null;
|
||||||
|
turnstileToken: string | null;
|
||||||
|
setField: <K extends keyof T>(key: K, value: T[K]) => void;
|
||||||
|
setValues: import("react").Dispatch<import("react").SetStateAction<T>>;
|
||||||
|
setErrors: import("react").Dispatch<import("react").SetStateAction<Partial<Record<keyof T, string>>>>;
|
||||||
|
setTurnstileToken: import("react").Dispatch<import("react").SetStateAction<string | null>>;
|
||||||
|
handleSubmit: (e?: {
|
||||||
|
preventDefault?: () => void;
|
||||||
|
}) => Promise<void>;
|
||||||
|
reset: () => void;
|
||||||
|
};
|
||||||
|
export {};
|
||||||
Vendored
+122
@@ -0,0 +1,122 @@
|
|||||||
|
'use client';
|
||||||
|
import { useState, useCallback, useRef, useMemo } from 'react';
|
||||||
|
/**
|
||||||
|
* Fully generic form engine: state, validation, Turnstile token, submit,
|
||||||
|
* success/error — WITHOUT any markup. The project owns 100% of the look AND
|
||||||
|
* the field set: there is no baked-in shape here. Replaces the identical
|
||||||
|
* ~150 lines of form plumbing copied into every project.
|
||||||
|
*
|
||||||
|
* The field set comes from `initialValues`; the rules come from `validate`
|
||||||
|
* (so dynamic/builder-driven forms just build both at runtime). For the
|
||||||
|
* everyday contact form use the `useContactForm` preset instead — it wires
|
||||||
|
* the standard fields and rules for you.
|
||||||
|
*
|
||||||
|
* const f = useForm({
|
||||||
|
* initialValues: { email: '', message: '' },
|
||||||
|
* submitAction, // your server action
|
||||||
|
* validate: buildValidator({ email: [required(), email()], message: [required()] }),
|
||||||
|
* requireTurnstile: Boolean(siteKey),
|
||||||
|
* })
|
||||||
|
* <input value={f.values.email}
|
||||||
|
* onChange={(e) => f.setField('email', e.target.value)}
|
||||||
|
* className={f.errors.email ? 'border-red-500' : '…'} />
|
||||||
|
* <form onSubmit={f.handleSubmit}>…</form>
|
||||||
|
*/ export function useForm(options) {
|
||||||
|
const { initialValues, submitAction, validate, requireTurnstile = false, errorFallback = 'Something went wrong. Please try again.', clearErrorOnChange = true } = options;
|
||||||
|
// Freeze the initial snapshot so `reset` is stable even though callers pass a
|
||||||
|
// fresh object literal every render.
|
||||||
|
const initialRef = useRef(initialValues);
|
||||||
|
const [values, setValues] = useState(initialRef.current);
|
||||||
|
const [errors, setErrors] = useState({});
|
||||||
|
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||||
|
const [isSuccess, setIsSuccess] = useState(false);
|
||||||
|
const [errorMessage, setErrorMessage] = useState(null);
|
||||||
|
const [turnstileToken, setTurnstileToken] = useState(null);
|
||||||
|
const setField = useCallback((key, value)=>{
|
||||||
|
setValues((prev)=>({
|
||||||
|
...prev,
|
||||||
|
[key]: value
|
||||||
|
}));
|
||||||
|
if (clearErrorOnChange) {
|
||||||
|
setErrors((prev)=>{
|
||||||
|
if (!prev[key]) return prev;
|
||||||
|
const next = {
|
||||||
|
...prev
|
||||||
|
};
|
||||||
|
delete next[key];
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, [
|
||||||
|
clearErrorOnChange
|
||||||
|
]);
|
||||||
|
// Validate against the LATEST values via a ref, so handleSubmit stays stable
|
||||||
|
// and never reads a stale snapshot.
|
||||||
|
const valuesRef = useRef(values);
|
||||||
|
valuesRef.current = values;
|
||||||
|
const validateRef = useRef(validate);
|
||||||
|
validateRef.current = validate;
|
||||||
|
const handleSubmit = useCallback(async (e)=>{
|
||||||
|
e?.preventDefault?.();
|
||||||
|
setErrorMessage(null);
|
||||||
|
const errs = validateRef.current ? validateRef.current(valuesRef.current) : {};
|
||||||
|
setErrors(errs);
|
||||||
|
if (Object.keys(errs).length > 0) return;
|
||||||
|
if (requireTurnstile && !turnstileToken) {
|
||||||
|
setErrorMessage(errorFallback);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setIsSubmitting(true);
|
||||||
|
try {
|
||||||
|
const result = await submitAction(valuesRef.current, turnstileToken ?? undefined);
|
||||||
|
if (result.success) {
|
||||||
|
setIsSuccess(true);
|
||||||
|
setTurnstileToken(null);
|
||||||
|
} else {
|
||||||
|
setErrorMessage(result.message || errorFallback);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
setErrorMessage(err instanceof Error ? err.message : errorFallback);
|
||||||
|
} finally{
|
||||||
|
setIsSubmitting(false);
|
||||||
|
}
|
||||||
|
}, [
|
||||||
|
requireTurnstile,
|
||||||
|
turnstileToken,
|
||||||
|
submitAction,
|
||||||
|
errorFallback
|
||||||
|
]);
|
||||||
|
const reset = useCallback(()=>{
|
||||||
|
setValues(initialRef.current);
|
||||||
|
setErrors({});
|
||||||
|
setIsSuccess(false);
|
||||||
|
setErrorMessage(null);
|
||||||
|
setTurnstileToken(null);
|
||||||
|
}, []);
|
||||||
|
return useMemo(()=>({
|
||||||
|
values,
|
||||||
|
errors,
|
||||||
|
isSubmitting,
|
||||||
|
isSuccess,
|
||||||
|
errorMessage,
|
||||||
|
turnstileToken,
|
||||||
|
setField,
|
||||||
|
setValues,
|
||||||
|
setErrors,
|
||||||
|
setTurnstileToken,
|
||||||
|
handleSubmit,
|
||||||
|
reset
|
||||||
|
}), [
|
||||||
|
values,
|
||||||
|
errors,
|
||||||
|
isSubmitting,
|
||||||
|
isSuccess,
|
||||||
|
errorMessage,
|
||||||
|
turnstileToken,
|
||||||
|
setField,
|
||||||
|
handleSubmit,
|
||||||
|
reset
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
//# sourceMappingURL=useForm.js.map
|
||||||
Vendored
+1
File diff suppressed because one or more lines are too long
Vendored
+43
@@ -0,0 +1,43 @@
|
|||||||
|
import type { Validator } from './useForm.js';
|
||||||
|
/**
|
||||||
|
* Composable validation rules + a builder that turns a per-field schema into a
|
||||||
|
* `Validator<T>`. These are the bits that actually repeat across projects
|
||||||
|
* (required / email / min-length / checkbox-must-be-true); the field SET and
|
||||||
|
* the MARKUP stay in the project.
|
||||||
|
*
|
||||||
|
* Pure functions, no 'use client' — usable both in the client `useForm` hook
|
||||||
|
* and server-side (e.g. re-validating inside a server action).
|
||||||
|
*
|
||||||
|
* const validate = buildValidator<MyValues>({
|
||||||
|
* email: [required(), email()],
|
||||||
|
* message: [required(), minLength(10)],
|
||||||
|
* consent: [checked()],
|
||||||
|
* })
|
||||||
|
*
|
||||||
|
* Dynamic / builder-driven forms build the schema at runtime:
|
||||||
|
*
|
||||||
|
* const schema = Object.fromEntries(
|
||||||
|
* fields.map((f) => [f.name, f.required ? [required()] : []]),
|
||||||
|
* )
|
||||||
|
* const validate = buildValidator(schema)
|
||||||
|
*/
|
||||||
|
/** A rule returns `true` when the value is OK, or an error message string. */
|
||||||
|
export type Rule = (value: unknown, values: Record<string, unknown>) => true | string;
|
||||||
|
/** Standalone e-mail check, handy outside the rule system too. */
|
||||||
|
export declare const isEmail: (v: unknown) => boolean;
|
||||||
|
/** Non-empty string, non-null, and (for checkboxes) not `false`. */
|
||||||
|
export declare const required: (msg?: string) => Rule;
|
||||||
|
export declare const email: (msg?: string) => Rule;
|
||||||
|
export declare const minLength: (n: number, msg?: string) => Rule;
|
||||||
|
export declare const maxLength: (n: number, msg?: string) => Rule;
|
||||||
|
/** Checkbox must be ticked (true). */
|
||||||
|
export declare const checked: (msg?: string) => Rule;
|
||||||
|
/** Value must match a regex (ignored when empty — pair with `required` to force). */
|
||||||
|
export declare const pattern: (re: RegExp, msg?: string) => Rule;
|
||||||
|
/** Escape hatch: any predicate → rule. */
|
||||||
|
export declare const custom: (test: (value: unknown, values: Record<string, unknown>) => boolean, msg: string) => Rule;
|
||||||
|
/**
|
||||||
|
* Compose a `Validator<T>` from per-field rule lists. First failing rule for a
|
||||||
|
* field wins. Fields with no rules (or an empty list) are skipped.
|
||||||
|
*/
|
||||||
|
export declare function buildValidator<T extends Record<string, unknown>>(schema: Partial<Record<keyof T, Rule[]>>): Validator<T>;
|
||||||
Vendored
+37
@@ -0,0 +1,37 @@
|
|||||||
|
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||||
|
/** Standalone e-mail check, handy outside the rule system too. */ export const isEmail = (v)=>typeof v === 'string' && EMAIL_RE.test(v.trim());
|
||||||
|
/** Non-empty string, non-null, and (for checkboxes) not `false`. */ export const required = (msg = 'required')=>(v)=>{
|
||||||
|
if (v == null) return msg;
|
||||||
|
if (typeof v === 'string' && !v.trim()) return msg;
|
||||||
|
if (v === false) return msg;
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
export const email = (msg = 'invalid email')=>(v)=>isEmail(v) ? true : msg;
|
||||||
|
export const minLength = (n, msg)=>(v)=>typeof v === 'string' && v.trim().length >= n ? true : msg ?? `min ${n} chars`;
|
||||||
|
export const maxLength = (n, msg)=>(v)=>typeof v === 'string' && v.trim().length <= n ? true : msg ?? `max ${n} chars`;
|
||||||
|
/** Checkbox must be ticked (true). */ export const checked = (msg = 'required')=>(v)=>v === true ? true : msg;
|
||||||
|
/** Value must match a regex (ignored when empty — pair with `required` to force). */ export const pattern = (re, msg = 'invalid format')=>(v)=>typeof v !== 'string' || v.trim() === '' || re.test(v.trim()) ? true : msg;
|
||||||
|
/** Escape hatch: any predicate → rule. */ export const custom = (test, msg)=>(v, values)=>test(v, values) ? true : msg;
|
||||||
|
/**
|
||||||
|
* Compose a `Validator<T>` from per-field rule lists. First failing rule for a
|
||||||
|
* field wins. Fields with no rules (or an empty list) are skipped.
|
||||||
|
*/ export function buildValidator(schema) {
|
||||||
|
return (values)=>{
|
||||||
|
const errs = {};
|
||||||
|
const all = values;
|
||||||
|
for(const key in schema){
|
||||||
|
const rules = schema[key];
|
||||||
|
if (!rules || rules.length === 0) continue;
|
||||||
|
for (const rule of rules){
|
||||||
|
const res = rule(all[key], all);
|
||||||
|
if (res !== true) {
|
||||||
|
errs[key] = res;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return errs;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
//# sourceMappingURL=validators.js.map
|
||||||
Vendored
+1
File diff suppressed because one or more lines are too long
+32
@@ -0,0 +1,32 @@
|
|||||||
|
import type { BasePayload } from 'payload';
|
||||||
|
type CreateHealthRouteArgs = {
|
||||||
|
/**
|
||||||
|
* Collection to ping for a real DB round-trip. Default 'pages'. Pick any
|
||||||
|
* collection that always exists in the project.
|
||||||
|
*/
|
||||||
|
collection?: string;
|
||||||
|
/**
|
||||||
|
* Optional extra checks merged into the body (e.g. a cache or queue ping).
|
||||||
|
* Throwing marks the whole healthcheck unhealthy.
|
||||||
|
*/
|
||||||
|
extra?: () => Promise<Record<string, unknown>>;
|
||||||
|
/** Same cached accessor the rest of the app uses. */
|
||||||
|
getCachedPayload: () => Promise<BasePayload>;
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* A liveness/readiness route for Coolify/Docker healthchecks and uptime
|
||||||
|
* monitors. Does a real DB round-trip (not just "process is up") and returns
|
||||||
|
* 200 when reachable, 503 when not — so an orchestrator can restart or hold
|
||||||
|
* traffic off a container whose database is down.
|
||||||
|
*
|
||||||
|
* // app/api/health/route.ts
|
||||||
|
* import { createHealthRoute } from '@intecion/ipal-kit'
|
||||||
|
* import { getCachedPayload } from '@/lib/content'
|
||||||
|
* export const dynamic = 'force-dynamic' // never prerender/cache a healthcheck
|
||||||
|
* export const GET = createHealthRoute({ getCachedPayload })
|
||||||
|
*
|
||||||
|
* Point Coolify's healthcheck at /api/health. Uses the global `Response`
|
||||||
|
* (standard in Next route handlers) — no next/server import, peer-dep clean.
|
||||||
|
*/
|
||||||
|
export declare function createHealthRoute(args: CreateHealthRouteArgs): () => Promise<Response>;
|
||||||
|
export {};
|
||||||
+62
@@ -0,0 +1,62 @@
|
|||||||
|
/**
|
||||||
|
* A liveness/readiness route for Coolify/Docker healthchecks and uptime
|
||||||
|
* monitors. Does a real DB round-trip (not just "process is up") and returns
|
||||||
|
* 200 when reachable, 503 when not — so an orchestrator can restart or hold
|
||||||
|
* traffic off a container whose database is down.
|
||||||
|
*
|
||||||
|
* // app/api/health/route.ts
|
||||||
|
* import { createHealthRoute } from '@intecion/ipal-kit'
|
||||||
|
* import { getCachedPayload } from '@/lib/content'
|
||||||
|
* export const dynamic = 'force-dynamic' // never prerender/cache a healthcheck
|
||||||
|
* export const GET = createHealthRoute({ getCachedPayload })
|
||||||
|
*
|
||||||
|
* Point Coolify's healthcheck at /api/health. Uses the global `Response`
|
||||||
|
* (standard in Next route handlers) — no next/server import, peer-dep clean.
|
||||||
|
*/ export function createHealthRoute(args) {
|
||||||
|
const { collection = 'pages', extra, getCachedPayload } = args;
|
||||||
|
return async ()=>{
|
||||||
|
const startedAt = Date.now();
|
||||||
|
try {
|
||||||
|
const payload = await getCachedPayload();
|
||||||
|
// Cheapest real round-trip: ask for at most one row, no population.
|
||||||
|
await payload.find({
|
||||||
|
collection: collection,
|
||||||
|
depth: 0,
|
||||||
|
limit: 1,
|
||||||
|
pagination: false
|
||||||
|
});
|
||||||
|
const extraData = extra ? await extra() : {};
|
||||||
|
const body = {
|
||||||
|
db: 'up',
|
||||||
|
status: 'ok',
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
tookMs: Date.now() - startedAt,
|
||||||
|
...extraData
|
||||||
|
};
|
||||||
|
return new Response(JSON.stringify(body), {
|
||||||
|
headers: {
|
||||||
|
'cache-control': 'no-store',
|
||||||
|
'content-type': 'application/json'
|
||||||
|
},
|
||||||
|
status: 200
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
const body = {
|
||||||
|
db: 'down',
|
||||||
|
error: err instanceof Error ? err.message : 'unknown',
|
||||||
|
status: 'error',
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
tookMs: Date.now() - startedAt
|
||||||
|
};
|
||||||
|
return new Response(JSON.stringify(body), {
|
||||||
|
headers: {
|
||||||
|
'cache-control': 'no-store',
|
||||||
|
'content-type': 'application/json'
|
||||||
|
},
|
||||||
|
status: 503
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
//# sourceMappingURL=createHealthRoute.js.map
|
||||||
@@ -0,0 +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"}
|
||||||
Vendored
+1
@@ -0,0 +1 @@
|
|||||||
|
export { createHealthRoute } from './createHealthRoute.js';
|
||||||
Vendored
+3
@@ -0,0 +1,3 @@
|
|||||||
|
export { createHealthRoute } from './createHealthRoute.js';
|
||||||
|
|
||||||
|
//# sourceMappingURL=index.js.map
|
||||||
Vendored
+1
@@ -0,0 +1 @@
|
|||||||
|
{"version":3,"sources":["../../../src/modules/health/index.ts"],"sourcesContent":["export { createHealthRoute } from './createHealthRoute.js'\n"],"names":["createHealthRoute"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,yBAAwB"}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
import type { CollectionAfterChangeHook } from 'payload';
|
||||||
|
import type { I18nConfig } from '../i18n/index.js';
|
||||||
|
type BuildCrossLocaleFieldSyncArgs = {
|
||||||
|
/**
|
||||||
|
* The localized `blocks`/`array` field whose rows hold the shared fields.
|
||||||
|
* Default 'layout'.
|
||||||
|
*/
|
||||||
|
arrayField?: string;
|
||||||
|
/**
|
||||||
|
* Slug of the collection this hook is attached to — needed to re-read and
|
||||||
|
* update the other locales. (A hook can't discover its own collection.)
|
||||||
|
*/
|
||||||
|
collection: string;
|
||||||
|
config: I18nConfig;
|
||||||
|
/**
|
||||||
|
* Fields WITHIN each row that are conceptually language-independent (a shared
|
||||||
|
* media reference, an icon, a color) and should be propagated from the edited
|
||||||
|
* locale to every other locale — e.g. ['image'] or ['image', 'backgroundImage'].
|
||||||
|
*
|
||||||
|
* Only fields with a value in the source are copied: clearing a field in one
|
||||||
|
* language does NOT wipe it in the others (conservative, matches the hand-
|
||||||
|
* rolled hooks this replaces). Text and other truly-localized fields are never
|
||||||
|
* touched.
|
||||||
|
*/
|
||||||
|
fields: string[];
|
||||||
|
/**
|
||||||
|
* Flag name set on `req` to break the update→afterChange→update loop.
|
||||||
|
* Default '_ipalSyncingCrossLocale'. Override only if two syncs run on one
|
||||||
|
* collection and must not share a guard.
|
||||||
|
*/
|
||||||
|
guardFlag?: string;
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* Propagates language-independent fields (images, icons…) that live INSIDE a
|
||||||
|
* localized `blocks`/`array` field from the just-edited locale to every other
|
||||||
|
* configured locale.
|
||||||
|
*
|
||||||
|
* Why this exists: Payload localizes an array/blocks field as a whole, so there
|
||||||
|
* is no way to mark a single sub-field (the image) as non-localized — each
|
||||||
|
* locale keeps its own copy of every row, image included. Without this, an
|
||||||
|
* editor who picks images in Polish has to re-pick the SAME images in English,
|
||||||
|
* German, … This hook does that copy automatically.
|
||||||
|
*
|
||||||
|
* A0-safe: the locale list comes from `config`, never a hard-coded array — add
|
||||||
|
* a language in the panel and it's covered with no code change. (The hand-rolled
|
||||||
|
* versions this replaces carried a literal `['pl','en',...]` that silently
|
||||||
|
* dropped any locale not listed.)
|
||||||
|
*
|
||||||
|
* Row matching: by Payload row `id` when the same id exists in both locales
|
||||||
|
* (robust to reordering and to several blocks of the same type); otherwise it
|
||||||
|
* falls back to the positional index, but only when the block types at that
|
||||||
|
* index match — so it never writes an image into a block of a different type.
|
||||||
|
*
|
||||||
|
* // collections/Pages.ts
|
||||||
|
* import { buildCrossLocaleFieldSync } from '@intecion/ipal-kit'
|
||||||
|
* hooks: {
|
||||||
|
* afterChange: [
|
||||||
|
* buildCrossLocaleFieldSync({ config: i18nConfig, collection: 'pages', fields: ['image'] }),
|
||||||
|
* ],
|
||||||
|
* }
|
||||||
|
*/
|
||||||
|
export declare function buildCrossLocaleFieldSync(args: BuildCrossLocaleFieldSyncArgs): CollectionAfterChangeHook;
|
||||||
|
export {};
|
||||||
+141
@@ -0,0 +1,141 @@
|
|||||||
|
import { getLocaleCodes } from '../i18n/index.js';
|
||||||
|
/** Relationship/upload values arrive as an id or a populated object — normalize to the id. */ function toId(value) {
|
||||||
|
if (value == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (typeof value === 'string' || typeof value === 'number') {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
if (typeof value === 'object' && 'id' in value) {
|
||||||
|
const id = value.id;
|
||||||
|
return typeof id === 'string' || typeof id === 'number' ? id : null;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Propagates language-independent fields (images, icons…) that live INSIDE a
|
||||||
|
* localized `blocks`/`array` field from the just-edited locale to every other
|
||||||
|
* configured locale.
|
||||||
|
*
|
||||||
|
* Why this exists: Payload localizes an array/blocks field as a whole, so there
|
||||||
|
* is no way to mark a single sub-field (the image) as non-localized — each
|
||||||
|
* locale keeps its own copy of every row, image included. Without this, an
|
||||||
|
* editor who picks images in Polish has to re-pick the SAME images in English,
|
||||||
|
* German, … This hook does that copy automatically.
|
||||||
|
*
|
||||||
|
* A0-safe: the locale list comes from `config`, never a hard-coded array — add
|
||||||
|
* a language in the panel and it's covered with no code change. (The hand-rolled
|
||||||
|
* versions this replaces carried a literal `['pl','en',...]` that silently
|
||||||
|
* dropped any locale not listed.)
|
||||||
|
*
|
||||||
|
* Row matching: by Payload row `id` when the same id exists in both locales
|
||||||
|
* (robust to reordering and to several blocks of the same type); otherwise it
|
||||||
|
* falls back to the positional index, but only when the block types at that
|
||||||
|
* index match — so it never writes an image into a block of a different type.
|
||||||
|
*
|
||||||
|
* // collections/Pages.ts
|
||||||
|
* import { buildCrossLocaleFieldSync } from '@intecion/ipal-kit'
|
||||||
|
* hooks: {
|
||||||
|
* afterChange: [
|
||||||
|
* buildCrossLocaleFieldSync({ config: i18nConfig, collection: 'pages', fields: ['image'] }),
|
||||||
|
* ],
|
||||||
|
* }
|
||||||
|
*/ export function buildCrossLocaleFieldSync(args) {
|
||||||
|
const { arrayField = 'layout', collection, config, fields, guardFlag = '_ipalSyncingCrossLocale' } = args;
|
||||||
|
return async ({ doc, req })=>{
|
||||||
|
const reqAny = req;
|
||||||
|
// Re-entry guard: our own payload.update() below re-fires afterChange.
|
||||||
|
if (reqAny[guardFlag] || !doc?.id) {
|
||||||
|
return doc;
|
||||||
|
}
|
||||||
|
const sourceRows = doc[arrayField];
|
||||||
|
if (!Array.isArray(sourceRows) || sourceRows.length === 0) {
|
||||||
|
return doc;
|
||||||
|
}
|
||||||
|
// Source locale = the locale being written. Fall back to the configured
|
||||||
|
// default rather than a hard-coded 'pl' when req.locale is absent.
|
||||||
|
const sourceLocale = typeof req.locale === 'string' ? req.locale : config.defaultLocale;
|
||||||
|
const otherLocales = getLocaleCodes(config).filter((l)=>l !== sourceLocale);
|
||||||
|
if (otherLocales.length === 0) {
|
||||||
|
return doc;
|
||||||
|
} // single-locale site: nothing to sync
|
||||||
|
const payload = req.payload;
|
||||||
|
reqAny[guardFlag] = true;
|
||||||
|
try {
|
||||||
|
for (const locale of otherLocales){
|
||||||
|
let targetDoc;
|
||||||
|
try {
|
||||||
|
targetDoc = await payload.findByID({
|
||||||
|
id: doc.id,
|
||||||
|
collection: collection,
|
||||||
|
depth: 0,
|
||||||
|
locale: locale
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
continue; // locale not yet created for this doc — nothing to sync into
|
||||||
|
}
|
||||||
|
const targetRows = targetDoc[arrayField];
|
||||||
|
if (!Array.isArray(targetRows) || targetRows.length === 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// id → row index, for robust matching across locales.
|
||||||
|
const byId = new Map();
|
||||||
|
targetRows.forEach((row, i)=>{
|
||||||
|
if (row?.id != null) {
|
||||||
|
byId.set(row.id, i);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let changed = false;
|
||||||
|
sourceRows.forEach((sourceRow, idx)=>{
|
||||||
|
if (!sourceRow) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Match by id first; else positional index, but only if block types agree.
|
||||||
|
let targetRow;
|
||||||
|
if (sourceRow.id != null && byId.has(sourceRow.id)) {
|
||||||
|
targetRow = targetRows[byId.get(sourceRow.id)];
|
||||||
|
} else {
|
||||||
|
const candidate = targetRows[idx];
|
||||||
|
if (candidate && candidate.blockType === sourceRow.blockType) {
|
||||||
|
targetRow = candidate;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!targetRow) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (const field of fields){
|
||||||
|
const sourceId = toId(sourceRow[field]);
|
||||||
|
if (sourceId == null) {
|
||||||
|
continue;
|
||||||
|
} // don't propagate a cleared field
|
||||||
|
if (toId(targetRow[field]) !== sourceId) {
|
||||||
|
targetRow[field] = sourceId;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if (changed) {
|
||||||
|
await payload.update({
|
||||||
|
id: doc.id,
|
||||||
|
collection: collection,
|
||||||
|
data: {
|
||||||
|
[arrayField]: targetRows
|
||||||
|
},
|
||||||
|
locale: locale,
|
||||||
|
req
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
payload.logger?.error?.({
|
||||||
|
err,
|
||||||
|
msg: `[ipal] cross-locale ${arrayField} sync failed`
|
||||||
|
});
|
||||||
|
} finally{
|
||||||
|
reqAny[guardFlag] = false;
|
||||||
|
}
|
||||||
|
return doc;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
//# sourceMappingURL=buildCrossLocaleFieldSync.js.map
|
||||||
File diff suppressed because one or more lines are too long
Vendored
+1
@@ -1,5 +1,6 @@
|
|||||||
export { normalizeFilenameHook } from '../media/index.js';
|
export { normalizeFilenameHook } from '../media/index.js';
|
||||||
export { buildAutoFillMetaHook, validateFaviconField } from '../seo/index.js';
|
export { buildAutoFillMetaHook, validateFaviconField } from '../seo/index.js';
|
||||||
|
export { buildCrossLocaleFieldSync } from './buildCrossLocaleFieldSync.js';
|
||||||
export { buildRevalidateHook } from './buildRevalidateHook.js';
|
export { buildRevalidateHook } from './buildRevalidateHook.js';
|
||||||
export { buildPreventDeleteSystemPage } from './preventDeleteSystemPage.js';
|
export { buildPreventDeleteSystemPage } from './preventDeleteSystemPage.js';
|
||||||
export { setPublishedAtHook } from './setPublishedAt.js';
|
export { setPublishedAtHook } from './setPublishedAt.js';
|
||||||
|
|||||||
Vendored
+1
@@ -2,6 +2,7 @@
|
|||||||
// żeby był jeden katalog "wszystkie hooki pluginu"). Źródło prawdy to ich moduły.
|
// żeby był jeden katalog "wszystkie hooki pluginu"). Źródło prawdy to ich moduły.
|
||||||
export { normalizeFilenameHook } from '../media/index.js';
|
export { normalizeFilenameHook } from '../media/index.js';
|
||||||
export { buildAutoFillMetaHook, validateFaviconField } from '../seo/index.js';
|
export { buildAutoFillMetaHook, validateFaviconField } from '../seo/index.js';
|
||||||
|
export { buildCrossLocaleFieldSync } from './buildCrossLocaleFieldSync.js';
|
||||||
export { buildRevalidateHook } from './buildRevalidateHook.js';
|
export { buildRevalidateHook } from './buildRevalidateHook.js';
|
||||||
export { buildPreventDeleteSystemPage } from './preventDeleteSystemPage.js';
|
export { buildPreventDeleteSystemPage } from './preventDeleteSystemPage.js';
|
||||||
export { setPublishedAtHook } from './setPublishedAt.js';
|
export { setPublishedAtHook } from './setPublishedAt.js';
|
||||||
|
|||||||
Vendored
+1
-1
@@ -1 +1 @@
|
|||||||
{"version":3,"sources":["../../../src/modules/hooks/index.ts"],"sourcesContent":["// Re-eksport hooków domenowych (mieszkają w swoich modułach, tu dla przeglądu —\n// żeby był jeden katalog \"wszystkie hooki pluginu\"). Źródło prawdy to ich moduły.\nexport { normalizeFilenameHook } from '../media/index.js'\nexport { buildAutoFillMetaHook, validateFaviconField } from '../seo/index.js'\nexport { buildRevalidateHook } from './buildRevalidateHook.js'\nexport { buildPreventDeleteSystemPage } from './preventDeleteSystemPage.js'\nexport { setPublishedAtHook } from './setPublishedAt.js'\n\nexport { trackSlugHistoryHook } from './trackSlugHistory.js'\nexport { buildValidateUniqueRole } from './validateUniqueRole.js'\n"],"names":["normalizeFilenameHook","buildAutoFillMetaHook","validateFaviconField","buildRevalidateHook","buildPreventDeleteSystemPage","setPublishedAtHook","trackSlugHistoryHook","buildValidateUniqueRole"],"mappings":"AAAA,gFAAgF;AAChF,kFAAkF;AAClF,SAASA,qBAAqB,QAAQ,oBAAmB;AACzD,SAASC,qBAAqB,EAAEC,oBAAoB,QAAQ,kBAAiB;AAC7E,SAASC,mBAAmB,QAAQ,2BAA0B;AAC9D,SAASC,4BAA4B,QAAQ,+BAA8B;AAC3E,SAASC,kBAAkB,QAAQ,sBAAqB;AAExD,SAASC,oBAAoB,QAAQ,wBAAuB;AAC5D,SAASC,uBAAuB,QAAQ,0BAAyB"}
|
{"version":3,"sources":["../../../src/modules/hooks/index.ts"],"sourcesContent":["// Re-eksport hooków domenowych (mieszkają w swoich modułach, tu dla przeglądu —\n// żeby był jeden katalog \"wszystkie hooki pluginu\"). Źródło prawdy to ich moduły.\nexport { normalizeFilenameHook } from '../media/index.js'\nexport { buildAutoFillMetaHook, validateFaviconField } from '../seo/index.js'\nexport { buildCrossLocaleFieldSync } from './buildCrossLocaleFieldSync.js'\nexport { buildRevalidateHook } from './buildRevalidateHook.js'\nexport { buildPreventDeleteSystemPage } from './preventDeleteSystemPage.js'\nexport { setPublishedAtHook } from './setPublishedAt.js'\n\nexport { trackSlugHistoryHook } from './trackSlugHistory.js'\nexport { buildValidateUniqueRole } from './validateUniqueRole.js'\n"],"names":["normalizeFilenameHook","buildAutoFillMetaHook","validateFaviconField","buildCrossLocaleFieldSync","buildRevalidateHook","buildPreventDeleteSystemPage","setPublishedAtHook","trackSlugHistoryHook","buildValidateUniqueRole"],"mappings":"AAAA,gFAAgF;AAChF,kFAAkF;AAClF,SAASA,qBAAqB,QAAQ,oBAAmB;AACzD,SAASC,qBAAqB,EAAEC,oBAAoB,QAAQ,kBAAiB;AAC7E,SAASC,yBAAyB,QAAQ,iCAAgC;AAC1E,SAASC,mBAAmB,QAAQ,2BAA0B;AAC9D,SAASC,4BAA4B,QAAQ,+BAA8B;AAC3E,SAASC,kBAAkB,QAAQ,sBAAqB;AAExD,SAASC,oBAAoB,QAAQ,wBAAuB;AAC5D,SAASC,uBAAuB,QAAQ,0BAAyB"}
|
||||||
Vendored
+9
@@ -24,6 +24,15 @@ type Manifest = {
|
|||||||
* import { getCachedPayload } from '@/lib/content'
|
* import { getCachedPayload } from '@/lib/content'
|
||||||
* import { i18nConfig } from '@/i18n.config'
|
* import { i18nConfig } from '@/i18n.config'
|
||||||
* export default createManifestHandler({ getCachedPayload, config: i18nConfig })
|
* export default createManifestHandler({ getCachedPayload, config: i18nConfig })
|
||||||
|
*
|
||||||
|
* NOTE on Docker/CI builds: the whole DB access is wrapped in try/catch, so a
|
||||||
|
* `next build` with no reachable database (the usual Coolify/Docker case) gets
|
||||||
|
* a minimal valid manifest instead of a crash — same contract as
|
||||||
|
* generateStaticParams and the sitemap handler. Projects should still mark the
|
||||||
|
* route dynamic so Next doesn't prerender it at build time:
|
||||||
|
*
|
||||||
|
* // app/manifest.ts
|
||||||
|
* export const dynamic = 'force-dynamic'
|
||||||
*/
|
*/
|
||||||
export declare function createManifestHandler(opts: {
|
export declare function createManifestHandler(opts: {
|
||||||
config: I18nConfig;
|
config: I18nConfig;
|
||||||
|
|||||||
Vendored
+32
-11
@@ -9,22 +9,43 @@ import { getDefaultLocale } from '../i18n/index.js';
|
|||||||
* import { getCachedPayload } from '@/lib/content'
|
* import { getCachedPayload } from '@/lib/content'
|
||||||
* import { i18nConfig } from '@/i18n.config'
|
* import { i18nConfig } from '@/i18n.config'
|
||||||
* export default createManifestHandler({ getCachedPayload, config: i18nConfig })
|
* export default createManifestHandler({ getCachedPayload, config: i18nConfig })
|
||||||
|
*
|
||||||
|
* NOTE on Docker/CI builds: the whole DB access is wrapped in try/catch, so a
|
||||||
|
* `next build` with no reachable database (the usual Coolify/Docker case) gets
|
||||||
|
* a minimal valid manifest instead of a crash — same contract as
|
||||||
|
* generateStaticParams and the sitemap handler. Projects should still mark the
|
||||||
|
* route dynamic so Next doesn't prerender it at build time:
|
||||||
|
*
|
||||||
|
* // app/manifest.ts
|
||||||
|
* export const dynamic = 'force-dynamic'
|
||||||
*/ export function createManifestHandler(opts) {
|
*/ export function createManifestHandler(opts) {
|
||||||
return async ()=>{
|
return async ()=>{
|
||||||
const defaultLocale = getDefaultLocale(opts.config);
|
const defaultLocale = getDefaultLocale(opts.config);
|
||||||
const payload = await opts.getCachedPayload();
|
|
||||||
const settings = await payload.findGlobal({
|
|
||||||
slug: opts.settingsSlug ?? 'site-settings',
|
|
||||||
depth: 1,
|
|
||||||
locale: defaultLocale
|
|
||||||
}).catch(()=>null);
|
|
||||||
const start_url = `/${defaultLocale}`;
|
const start_url = `/${defaultLocale}`;
|
||||||
|
// Minimal, always-valid manifest. Used both when SiteSettings is empty and
|
||||||
|
// when the database is unreachable during a build.
|
||||||
|
const fallback = {
|
||||||
|
display: 'standalone',
|
||||||
|
icons: [],
|
||||||
|
start_url
|
||||||
|
};
|
||||||
|
let settings;
|
||||||
|
try {
|
||||||
|
// getCachedPayload() ITSELF throws when the DB can't be reached (e.g.
|
||||||
|
// `getaddrinfo ENOTFOUND` during `docker build`), BEFORE findGlobal runs
|
||||||
|
// — so the whole thing, not just the query, must sit inside try/catch.
|
||||||
|
const payload = await opts.getCachedPayload();
|
||||||
|
settings = await payload.findGlobal({
|
||||||
|
slug: opts.settingsSlug ?? 'site-settings',
|
||||||
|
depth: 1,
|
||||||
|
locale: defaultLocale
|
||||||
|
}).catch(()=>null);
|
||||||
|
} catch (err) {
|
||||||
|
console.warn('[ipal] createManifestHandler: database not reachable during build (Docker/CI) — returning minimal manifest; it fills in at runtime:', err);
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
if (!settings) {
|
if (!settings) {
|
||||||
return {
|
return fallback;
|
||||||
display: 'standalone',
|
|
||||||
icons: [],
|
|
||||||
start_url
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
const iconSource = settings.favicon ?? settings.logo;
|
const iconSource = settings.favicon ?? settings.logo;
|
||||||
const icons = [];
|
const icons = [];
|
||||||
|
|||||||
+1
-1
File diff suppressed because one or more lines are too long
+34
@@ -0,0 +1,34 @@
|
|||||||
|
import type { CheckboxField, Field } from 'payload';
|
||||||
|
type BuildNoindexFieldArgs = {
|
||||||
|
/** Help text under the checkbox. */
|
||||||
|
description?: string;
|
||||||
|
/** Sidebar label. Default 'Wyklucz z indeksowania (noindex)'. */
|
||||||
|
label?: string;
|
||||||
|
/**
|
||||||
|
* Dotted path, inside the document, that the SEO read path (metadata +
|
||||||
|
* sitemap) consumes. Default 'meta.noindex' — the plugin-seo `meta` group.
|
||||||
|
* The checkbox value is mirrored here on every save, so editors toggle one
|
||||||
|
* friendly switch and the machinery reads a stable location.
|
||||||
|
*/
|
||||||
|
metaPath?: string;
|
||||||
|
/** Field name for the editor-facing checkbox. Default 'noindex'. */
|
||||||
|
name?: string;
|
||||||
|
/** Extend/override the generated checkbox (position, access, etc.). */
|
||||||
|
overrides?: Partial<CheckboxField>;
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* A sidebar `noindex` checkbox that mirrors into `meta.noindex` (what the
|
||||||
|
* sitemap and metadata generators actually read). Replaces the hand-rolled
|
||||||
|
* checkbox + `beforeChange` hook with its `(data as any).meta.noindex = …`
|
||||||
|
* glue copied into every project — no `any`, one source of truth for editors,
|
||||||
|
* one stable read location for the engine.
|
||||||
|
*
|
||||||
|
* Idempotent and order-independent: if either the checkbox OR an existing
|
||||||
|
* `meta.noindex` is set, the page ends up noindex; the two can't drift apart.
|
||||||
|
*
|
||||||
|
* // collections/Pages.ts
|
||||||
|
* import { buildNoindexField } from '@intecion/ipal-kit'
|
||||||
|
* fields: [ /* … *\/ buildNoindexField() ],
|
||||||
|
*/
|
||||||
|
export declare function buildNoindexField(args?: BuildNoindexFieldArgs): Field;
|
||||||
|
export {};
|
||||||
+69
@@ -0,0 +1,69 @@
|
|||||||
|
/** Read a dotted path (e.g. 'meta.noindex') off a loosely-typed object. */ function readPath(obj, path) {
|
||||||
|
let cur = obj;
|
||||||
|
for (const key of path){
|
||||||
|
if (cur == null || typeof cur !== 'object') {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
cur = cur[key];
|
||||||
|
}
|
||||||
|
return cur;
|
||||||
|
}
|
||||||
|
/** Write a dotted path, creating intermediate objects as needed. */ function writePath(obj, path, value) {
|
||||||
|
let cur = obj;
|
||||||
|
for(let i = 0; i < path.length - 1; i++){
|
||||||
|
const key = path[i];
|
||||||
|
const next = cur[key];
|
||||||
|
if (next == null || typeof next !== 'object') {
|
||||||
|
cur[key] = {};
|
||||||
|
}
|
||||||
|
cur = cur[key];
|
||||||
|
}
|
||||||
|
cur[path[path.length - 1]] = value;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* A sidebar `noindex` checkbox that mirrors into `meta.noindex` (what the
|
||||||
|
* sitemap and metadata generators actually read). Replaces the hand-rolled
|
||||||
|
* checkbox + `beforeChange` hook with its `(data as any).meta.noindex = …`
|
||||||
|
* glue copied into every project — no `any`, one source of truth for editors,
|
||||||
|
* one stable read location for the engine.
|
||||||
|
*
|
||||||
|
* Idempotent and order-independent: if either the checkbox OR an existing
|
||||||
|
* `meta.noindex` is set, the page ends up noindex; the two can't drift apart.
|
||||||
|
*
|
||||||
|
* // collections/Pages.ts
|
||||||
|
* import { buildNoindexField } from '@intecion/ipal-kit'
|
||||||
|
* fields: [ /* … *\/ buildNoindexField() ],
|
||||||
|
*/ export function buildNoindexField(args = {}) {
|
||||||
|
const { name = 'noindex', description = 'Zaznacz, aby wykluczyć tę podstronę z indeksowania (robots: noindex, follow) i z sitemap.xml.', label = 'Wyklucz z indeksowania (noindex)', metaPath = 'meta.noindex', overrides = {} } = args;
|
||||||
|
const segments = metaPath.split('.');
|
||||||
|
const mirror = ({ data, value })=>{
|
||||||
|
const shouldNoindex = Boolean(value ?? readPath(data, segments));
|
||||||
|
if (data && typeof data === 'object') {
|
||||||
|
writePath(data, segments, shouldNoindex);
|
||||||
|
}
|
||||||
|
return shouldNoindex;
|
||||||
|
};
|
||||||
|
const { admin: adminOverrides, hooks: hooksOverrides, ...restOverrides } = overrides;
|
||||||
|
return {
|
||||||
|
name,
|
||||||
|
type: 'checkbox',
|
||||||
|
admin: {
|
||||||
|
description,
|
||||||
|
position: 'sidebar',
|
||||||
|
...adminOverrides
|
||||||
|
},
|
||||||
|
defaultValue: false,
|
||||||
|
hooks: {
|
||||||
|
...hooksOverrides,
|
||||||
|
// mirror runs first, then any project-supplied beforeChange hooks.
|
||||||
|
beforeChange: [
|
||||||
|
mirror,
|
||||||
|
...hooksOverrides?.beforeChange ?? []
|
||||||
|
]
|
||||||
|
},
|
||||||
|
label,
|
||||||
|
...restOverrides
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
//# sourceMappingURL=buildNoindexField.js.map
|
||||||
+1
File diff suppressed because one or more lines are too long
Vendored
+1
@@ -9,6 +9,7 @@ export { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js';
|
|||||||
export { createManifestHandler } from './buildManifest.js';
|
export { createManifestHandler } from './buildManifest.js';
|
||||||
export { buildMetadata } from './buildMetadata.js';
|
export { buildMetadata } from './buildMetadata.js';
|
||||||
export type { PageMetadata } from './buildMetadata.js';
|
export type { PageMetadata } from './buildMetadata.js';
|
||||||
|
export { buildNoindexField } from './buildNoindexField.js';
|
||||||
export { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js';
|
export { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js';
|
||||||
export { buildRobots } from './buildRobots.js';
|
export { buildRobots } from './buildRobots.js';
|
||||||
export type { RobotsRules } from './buildRobots.js';
|
export type { RobotsRules } from './buildRobots.js';
|
||||||
|
|||||||
Vendored
+1
@@ -7,6 +7,7 @@ export { buildLlmsTxt } from './buildLlmsTxt.js';
|
|||||||
export { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js';
|
export { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js';
|
||||||
export { createManifestHandler } from './buildManifest.js';
|
export { createManifestHandler } from './buildManifest.js';
|
||||||
export { buildMetadata } from './buildMetadata.js';
|
export { buildMetadata } from './buildMetadata.js';
|
||||||
|
export { buildNoindexField } from './buildNoindexField.js';
|
||||||
export { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js';
|
export { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js';
|
||||||
export { buildRobots } from './buildRobots.js';
|
export { buildRobots } from './buildRobots.js';
|
||||||
export { buildServiceJsonLd } from './buildServiceJsonLd.js';
|
export { buildServiceJsonLd } from './buildServiceJsonLd.js';
|
||||||
|
|||||||
Vendored
+1
-1
@@ -1 +1 @@
|
|||||||
{"version":3,"sources":["../../../src/modules/seo/index.ts"],"sourcesContent":["export { buildAutoFillMetaHook } from './autoFillMeta.js'\nexport type { AutoFillMapping } from './autoFillMeta.js'\nexport { buildArticleJsonLd } from './buildArticleJsonLd.js'\nexport { buildBreadcrumbJsonLd } from './buildBreadcrumbJsonLd.js'\nexport { buildFaqJsonLd } from './buildFaqJsonLd.js'\nexport { buildIconsMetadata } from './buildIconsMetadata.js'\nexport { buildLlmsTxt } from './buildLlmsTxt.js'\nexport { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js'\nexport { createManifestHandler } from './buildManifest.js'\nexport { buildMetadata } from './buildMetadata.js'\nexport type { PageMetadata } from './buildMetadata.js'\nexport { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js'\nexport { buildRobots } from './buildRobots.js'\nexport type { RobotsRules } from './buildRobots.js'\nexport { buildServiceJsonLd } from './buildServiceJsonLd.js'\nexport { buildSitemapEntries } from './buildSitemapEntries.js'\nexport type { SitemapEntry } from './buildSitemapEntries.js'\nexport { buildSitemapXml } from './buildSitemapXml.js'\nexport { buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js'\nexport { buildWebSiteJsonLd } from './buildWebSiteJsonLd.js'\nexport { composeTitle } from './composeTitle.js'\nexport type { TitleOrder } from './composeTitle.js'\nexport { createMetadataGenerator } from './createMetadataGenerator.js'\nexport { createPageMetadata } from './createPageMetadata.js'\nexport { buildHreflangAlternates } from './hreflang.js'\nexport { injectAutoFillMeta } from './injectAutoFillMeta.js'\nexport { injectSeoTabs } from './injectSeoTabs.js'\nexport { JsonLdGraph } from './JsonLdGraph.js'\nexport { readSiteMetaConfig } from './readSiteMetaConfig.js'\nexport type { SiteMetaConfig } from './readSiteMetaConfig.js'\nexport { createLlmsTxtRoute, createSitemapRouteHandler } from './routeHandlers.js'\nexport { buildSeoPlugin } from './seoPluginConfig.js'\nexport { slugsAcrossLocales } from './slugsAcrossLocales.js'\nexport type { SeoMeta, SeoOption } from './types.js'\nexport { validateFaviconField } from './validateFavicon.js'\n"],"names":["buildAutoFillMetaHook","buildArticleJsonLd","buildBreadcrumbJsonLd","buildFaqJsonLd","buildIconsMetadata","buildLlmsTxt","buildLocalBusinessJsonLd","createManifestHandler","buildMetadata","buildOrganizationJsonLd","buildRobots","buildServiceJsonLd","buildSitemapEntries","buildSitemapXml","buildSiteNavigationJsonLd","buildWebSiteJsonLd","composeTitle","createMetadataGenerator","createPageMetadata","buildHreflangAlternates","injectAutoFillMeta","injectSeoTabs","JsonLdGraph","readSiteMetaConfig","createLlmsTxtRoute","createSitemapRouteHandler","buildSeoPlugin","slugsAcrossLocales","validateFaviconField"],"mappings":"AAAA,SAASA,qBAAqB,QAAQ,oBAAmB;AAEzD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,qBAAqB,QAAQ,6BAA4B;AAClE,SAASC,cAAc,QAAQ,sBAAqB;AACpD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,wBAAwB,QAAQ,gCAA+B;AACxE,SAASC,qBAAqB,QAAQ,qBAAoB;AAC1D,SAASC,aAAa,QAAQ,qBAAoB;AAElD,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,WAAW,QAAQ,mBAAkB;AAE9C,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,mBAAmB,QAAQ,2BAA0B;AAE9D,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,yBAAyB,QAAQ,iCAAgC;AAC1E,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,YAAY,QAAQ,oBAAmB;AAEhD,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,uBAAuB,QAAQ,gBAAe;AACvD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,aAAa,QAAQ,qBAAoB;AAClD,SAASC,WAAW,QAAQ,mBAAkB;AAC9C,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,SAASC,kBAAkB,EAAEC,yBAAyB,QAAQ,qBAAoB;AAClF,SAASC,cAAc,QAAQ,uBAAsB;AACrD,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,SAASC,oBAAoB,QAAQ,uBAAsB"}
|
{"version":3,"sources":["../../../src/modules/seo/index.ts"],"sourcesContent":["export { buildAutoFillMetaHook } from './autoFillMeta.js'\nexport type { AutoFillMapping } from './autoFillMeta.js'\nexport { buildArticleJsonLd } from './buildArticleJsonLd.js'\nexport { buildBreadcrumbJsonLd } from './buildBreadcrumbJsonLd.js'\nexport { buildFaqJsonLd } from './buildFaqJsonLd.js'\nexport { buildIconsMetadata } from './buildIconsMetadata.js'\nexport { buildLlmsTxt } from './buildLlmsTxt.js'\nexport { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js'\nexport { createManifestHandler } from './buildManifest.js'\nexport { buildMetadata } from './buildMetadata.js'\nexport type { PageMetadata } from './buildMetadata.js'\nexport { buildNoindexField } from './buildNoindexField.js'\nexport { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js'\nexport { buildRobots } from './buildRobots.js'\nexport type { RobotsRules } from './buildRobots.js'\nexport { buildServiceJsonLd } from './buildServiceJsonLd.js'\nexport { buildSitemapEntries } from './buildSitemapEntries.js'\nexport type { SitemapEntry } from './buildSitemapEntries.js'\nexport { buildSitemapXml } from './buildSitemapXml.js'\nexport { buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js'\nexport { buildWebSiteJsonLd } from './buildWebSiteJsonLd.js'\nexport { composeTitle } from './composeTitle.js'\nexport type { TitleOrder } from './composeTitle.js'\nexport { createMetadataGenerator } from './createMetadataGenerator.js'\nexport { createPageMetadata } from './createPageMetadata.js'\nexport { buildHreflangAlternates } from './hreflang.js'\nexport { injectAutoFillMeta } from './injectAutoFillMeta.js'\nexport { injectSeoTabs } from './injectSeoTabs.js'\nexport { JsonLdGraph } from './JsonLdGraph.js'\nexport { readSiteMetaConfig } from './readSiteMetaConfig.js'\nexport type { SiteMetaConfig } from './readSiteMetaConfig.js'\nexport { createLlmsTxtRoute, createSitemapRouteHandler } from './routeHandlers.js'\nexport { buildSeoPlugin } from './seoPluginConfig.js'\nexport { slugsAcrossLocales } from './slugsAcrossLocales.js'\nexport type { SeoMeta, SeoOption } from './types.js'\nexport { validateFaviconField } from './validateFavicon.js'\n"],"names":["buildAutoFillMetaHook","buildArticleJsonLd","buildBreadcrumbJsonLd","buildFaqJsonLd","buildIconsMetadata","buildLlmsTxt","buildLocalBusinessJsonLd","createManifestHandler","buildMetadata","buildNoindexField","buildOrganizationJsonLd","buildRobots","buildServiceJsonLd","buildSitemapEntries","buildSitemapXml","buildSiteNavigationJsonLd","buildWebSiteJsonLd","composeTitle","createMetadataGenerator","createPageMetadata","buildHreflangAlternates","injectAutoFillMeta","injectSeoTabs","JsonLdGraph","readSiteMetaConfig","createLlmsTxtRoute","createSitemapRouteHandler","buildSeoPlugin","slugsAcrossLocales","validateFaviconField"],"mappings":"AAAA,SAASA,qBAAqB,QAAQ,oBAAmB;AAEzD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,qBAAqB,QAAQ,6BAA4B;AAClE,SAASC,cAAc,QAAQ,sBAAqB;AACpD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,wBAAwB,QAAQ,gCAA+B;AACxE,SAASC,qBAAqB,QAAQ,qBAAoB;AAC1D,SAASC,aAAa,QAAQ,qBAAoB;AAElD,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,WAAW,QAAQ,mBAAkB;AAE9C,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,mBAAmB,QAAQ,2BAA0B;AAE9D,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,yBAAyB,QAAQ,iCAAgC;AAC1E,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,YAAY,QAAQ,oBAAmB;AAEhD,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,uBAAuB,QAAQ,gBAAe;AACvD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,aAAa,QAAQ,qBAAoB;AAClD,SAASC,WAAW,QAAQ,mBAAkB;AAC9C,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,SAASC,kBAAkB,EAAEC,yBAAyB,QAAQ,qBAAoB;AAClF,SAASC,cAAc,QAAQ,uBAAsB;AACrD,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,SAASC,oBAAoB,QAAQ,uBAAsB"}
|
||||||
+14
-4
@@ -6,7 +6,7 @@ faktycznych błędów, które się zdarzyły. Odstępstwa tylko za świadomą de
|
|||||||
|
|
||||||
Powiązane: [standardy-kodu.md](./standardy-kodu.md) (dobre praktyki senior),
|
Powiązane: [standardy-kodu.md](./standardy-kodu.md) (dobre praktyki senior),
|
||||||
[publishing.md](./publishing.md) (cykl publikacji), [getting-started.md](./getting-started.md)
|
[publishing.md](./publishing.md) (cykl publikacji), [getting-started.md](./getting-started.md)
|
||||||
(nowy projekt), ../ANTIGRAVITY-ZASADY-AGENT.md (zasady dla AI).
|
(nowy projekt), ../antigravity_zasady_agent.md (zasady dla AI).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -179,10 +179,14 @@ Pełne szczegóły: [getting-started.md](./getting-started.md). Tu skrót kolejn
|
|||||||
8. **lib/content.ts + lib/payload.ts** — helpery, jedno źródło getCachedPayload
|
8. **lib/content.ts + lib/payload.ts** — helpery, jedno źródło getCachedPayload
|
||||||
9. **proxy.ts** (NIE middleware.ts) — routing locale, obsługa roota
|
9. **proxy.ts** (NIE middleware.ts) — routing locale, obsługa roota
|
||||||
10. **Bloki** — dane przez enhanceProps, nie import lib (cykl)
|
10. **Bloki** — dane przez enhanceProps, nie import lib (cykl)
|
||||||
11. **buildSlugField** zamiast ręcznego slug
|
11. **buildSlugField** zamiast ręcznego slug; **buildNoindexField** na pole noindex
|
||||||
12. **getLocalizedSlugs** zamiast zaszytej mapy ścieżek
|
12. **getLocalizedSlugs** zamiast zaszytej mapy ścieżek
|
||||||
13. **buildSecurityHeaders** w next.config
|
13. **buildSecurityHeaders** w next.config
|
||||||
14. **Test:** root `/` przekierowuje, formularz wysyła, panel działa
|
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
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -249,6 +253,12 @@ Nie mów „działa", dopóki:
|
|||||||
- [ ] sekrety w .env (nie w repo), maskowane w panelu
|
- [ ] sekrety w .env (nie w repo), maskowane w panelu
|
||||||
- [ ] brak plików middleware.ts, brak zaszytej mapy slugów
|
- [ ] brak plików middleware.ts, brak zaszytej mapy slugów
|
||||||
- [ ] strona 404 (not-found.tsx) — edytowalna, per język, link powrotu
|
- [ ] strona 404 (not-found.tsx) — edytowalna, per język, link powrotu
|
||||||
- [ ] formularze z buildera w panelu (NIE własne hardkodowane)
|
- [ ] 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
|
- [ ] compliance: polityki, baner cookies, zgoda RODO w formularzach
|
||||||
(patrz [wymagania-prawne.md](./wymagania-prawne.md))
|
(patrz [wymagania-prawne.md](./wymagania-prawne.md))
|
||||||
+7
-3
@@ -104,7 +104,8 @@ export default buildConfig({
|
|||||||
| Moduł | Opis | Dok |
|
| Moduł | Opis | Dok |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| i18n | Lokalizacja, negocjacja locale, ścieżki URL, strona jednojęzyczna | [i18n.md](./i18n.md) |
|
| i18n | Lokalizacja, negocjacja locale, ścieżki URL, strona jednojęzyczna | [i18n.md](./i18n.md) |
|
||||||
| hooks | Hooki: revalidate ISR, slug history 301, ochrona stron systemowych | [hooks.md](./hooks.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) |
|
||||||
| kolekcje-katalog | Jakie kolekcje budować, kiedy, jak wpiąć (minimum nie maksimum) | [kolekcje-katalog.md](./kolekcje-katalog.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) |
|
| 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) |
|
| deployment | Zmienne .env, ISR/SSG, force-dynamic, Coolify/Docker | [deployment.md](./deployment.md) |
|
||||||
@@ -112,20 +113,23 @@ export default buildConfig({
|
|||||||
| access | Role admin > editor > user, kontrola dostępu | [access.md](./access.md) |
|
| access | Role admin > editor > user, kontrola dostępu | [access.md](./access.md) |
|
||||||
| payload-helpers | getSiteSettings / getSiteIntegrations | [payload-helpers.md](./payload-helpers.md) |
|
| payload-helpers | getSiteSettings / getSiteIntegrations | [payload-helpers.md](./payload-helpers.md) |
|
||||||
| seo | Metadata, hreflang, auto-fill, plugin-seo | [seo.md](./seo.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) |
|
| 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) |
|
| 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) |
|
| 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) |
|
| 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) |
|
| consent | Banner cookies GDPR, Google Consent Mode | [consent.md](./consent.md) |
|
||||||
| turnstile | Cloudflare Turnstile (widget + verify) | [turnstile.md](./turnstile.md) |
|
| turnstile | Cloudflare Turnstile (widget + verify) | [turnstile.md](./turnstile.md) |
|
||||||
| email | Wysyłka: SMTP z panelu lub Microsoft Graph (M365) | [email.md](./email.md) |
|
| email | Wysyłka: SMTP z panelu lub Microsoft Graph (M365) | [email.md](./email.md) |
|
||||||
| forms | Form-builder + submitForm (Turnstile + zapis) | [forms.md](./forms.md) |
|
| forms | Form-builder + submitForm + useForm/useContactForm (logika klienta) | [forms.md](./forms.md) |
|
||||||
| analytics | GA4 / GTM spięte z Consent Mode | [analytics.md](./analytics.md) |
|
| analytics | GA4 / GTM spięte z Consent Mode | [analytics.md](./analytics.md) |
|
||||||
| slug | Auto-slug z tytułu, per locale | [slug.md](./slug.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) |
|
| 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) |
|
| 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) |
|
| security | Nagłówki bezpieczeństwa HTTP (HSTS, X-Frame...) | [security.md](./security.md) |
|
||||||
| content | Blog/archiwa: kolekcje pod stroną-archiwum, listing, paginacja | [content.md](./content.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)
|
Nowy projekt krok po kroku: [getting-started.md](./getting-started.md)
|
||||||
Referencja wdrożenia frontu: [getting-started.md](./getting-started.md)
|
Referencja wdrożenia frontu: [getting-started.md](./getting-started.md)
|
||||||
|
|||||||
+15
-5
@@ -82,7 +82,9 @@ Niniejszy dokument stanowi bezwzględnie obowiązujące reguły pracy dla agenta
|
|||||||
- **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 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.
|
- **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`.
|
- **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 formularz z buildera w panelu (kolekcja Forms) + `submitForm`. NIGDY własny hardkodowany formularz z polami w JSX — omija Turnstile, rate-limit, consent RODO, powiadomienia. Turnstile: `TurnstileProvider` (siteKey raz w layoutcie) + `useTurnstile()` w formularzu.
|
- **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.
|
- **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`.
|
- **WYMAGANE:** Jedno źródło prawdy `i18n.config.ts`, `locale as never`, dane firmy z globala (np. `siteSettings` / `CompanyInfo`), infrastruktura wyłącznie w `.env`.
|
||||||
|
|
||||||
@@ -104,9 +106,10 @@ Niniejszy dokument stanowi bezwzględnie obowiązujące reguły pracy dla agenta
|
|||||||
[[...slug]]/
|
[[...slug]]/
|
||||||
page.tsx # render stron z bloków (podwójne nawiasy!)
|
page.tsx # render stron z bloków (podwójne nawiasy!)
|
||||||
(payload)/ # panel admina
|
(payload)/ # panel admina
|
||||||
manifest.ts # PWA z panelu
|
manifest.ts # PWA z panelu — WYMAGANE export const dynamic = 'force-dynamic'
|
||||||
sitemap.ts # z lib/content + export const dynamic = 'force-dynamic'
|
sitemap.ts # z lib/content + export const dynamic = 'force-dynamic'
|
||||||
robots.ts # z lib/content
|
robots.ts # z lib/content
|
||||||
|
instrumentation.ts # assertEnv(ipalEnvRules(...)) — walidacja ENV na starcie
|
||||||
blocks/
|
blocks/
|
||||||
<NazwaBloku>/
|
<NazwaBloku>/
|
||||||
config.ts # schemat pól bloku
|
config.ts # schemat pól bloku
|
||||||
@@ -134,6 +137,8 @@ Niniejszy dokument stanowi bezwzględnie obowiązujące reguły pracy dla agenta
|
|||||||
2. **Wymagane ISR:** `export const revalidate = 3600` w `page.tsx` stron (zapobiega race condition streamingu metadanych i zapewnia TTFB ~20ms).
|
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.
|
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`.
|
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`.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -193,7 +198,10 @@ zwykłych stron komercyjnych to opcja — dodawaj GDY klient wymaga (Accessibili
|
|||||||
|
|
||||||
Wpinaj w kolekcje gdzie dotyczy (patrz `hooks.md`):
|
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.
|
- **buildRevalidateHook** (afterChange/afterDelete) — ISR odświeżany po zapisie (redaktor od razu widzi zmianę). `revalidatePath` wstrzykiwany z projektu.
|
||||||
- **trackSlugHistoryHook** (beforeChange) — zmiana slug → zapis starego → projekt robi 301 (stary URL nie daje 404).
|
- **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).
|
- **setPublishedAtHook** — auto-data publikacji (blog).
|
||||||
- **normalizeFilenameHook** — czyste nazwy plików (Media, obowiązkowo).
|
- **normalizeFilenameHook** — czyste nazwy plików (Media, obowiązkowo).
|
||||||
- **buildPreventDeleteSystemPage** / **buildValidateUniqueRole** — ochrona stron systemowych.
|
- **buildPreventDeleteSystemPage** / **buildValidateUniqueRole** — ochrona stron systemowych.
|
||||||
@@ -239,9 +247,11 @@ Ten plik to skondensowane reguły. Szczegóły w `node_modules/@intecion/ipal-ki
|
|||||||
| Strukturę, nazewnictwo, konwencje | `fundamenty-projektu.md` |
|
| Strukturę, nazewnictwo, konwencje | `fundamenty-projektu.md` |
|
||||||
| Jakie kolekcje budować (minimum!) | `kolekcje-katalog.md` |
|
| Jakie kolekcje budować (minimum!) | `kolekcje-katalog.md` |
|
||||||
| SEO, metadane, sitemap, favicon, structured data, llms.txt | `seo.md` |
|
| SEO, metadane, sitemap, favicon, structured data, llms.txt | `seo.md` |
|
||||||
| Hooki (revalidate, slug history, ochrona) | `hooks.md` |
|
| Hooki (revalidate, slug history, cross-locale sync, ochrona) | `hooks.md` |
|
||||||
|
| Redirecty 301/308 (resolveRedirect) | `content.md` |
|
||||||
|
| Walidacja ENV na starcie (assertEnv) | `env.md` |
|
||||||
| Bezpieczeństwo, CSP, COOP | `security.md` |
|
| Bezpieczeństwo, CSP, COOP | `security.md` |
|
||||||
| Formularze, Turnstile, submitForm | `forms.md`, `turnstile.md` |
|
| Formularze, Turnstile, submitForm, useForm/useContactForm | `forms.md`, `turnstile.md` |
|
||||||
| i18n, strona jednojęzyczna, ścieżki | `i18n.md` |
|
| i18n, strona jednojęzyczna, ścieżki | `i18n.md` |
|
||||||
| Strony systemowe, routing | `pages.md` |
|
| Strony systemowe, routing | `pages.md` |
|
||||||
| Bloki, RenderBlocks | `blocks.md` |
|
| Bloki, RenderBlocks | `blocks.md` |
|
||||||
|
|||||||
@@ -78,6 +78,28 @@ import { parseConsent, CONSENT_COOKIE, CONSENT_CATEGORIES } from '@intecion/ipal
|
|||||||
// np. gating skryptów server-side na podstawie cookie zgody
|
// np. gating skryptów server-side na podstawie cookie zgody
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### ConsentScript — ładuj skrypt dopiero po zgodzie
|
||||||
|
|
||||||
|
Dla third-party BEZ własnego Consent Mode (Meta Pixel, LinkedIn Insight, czaty,
|
||||||
|
własna analityka) użyj `ConsentScript` — ładuje skrypt tylko po zgodzie dla jego
|
||||||
|
kategorii, reaguje na żywo (akceptacja w banerze → skrypt pojawia się bez
|
||||||
|
przeładowania). Renderuj wewnątrz `<ConsentProvider>`:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { ConsentScript } from '@intecion/ipal-kit/client'
|
||||||
|
|
||||||
|
<ConsentScript category="marketing" src="https://connect.facebook.net/en_US/fbevents.js" />
|
||||||
|
<ConsentScript category="marketing" code={`fbq('init','123');fbq('track','PageView')`} />
|
||||||
|
<ConsentScript category="analytics"
|
||||||
|
src="https://plausible.io/js/script.js"
|
||||||
|
attributes={{ 'data-domain': 'example.com' }} />
|
||||||
|
```
|
||||||
|
|
||||||
|
GA/GTM lepiej przez Consent Mode (`updateConsent` wyżej) — `ConsentScript` jest
|
||||||
|
dla wendorów, których tak nie ugatujesz. Uwaga: skrypt raz załadowany działa do
|
||||||
|
końca strony (tag `<script>` nie da się „odładować") — wycofanie zgody blokuje
|
||||||
|
KOLEJNE ładowanie; dla running tagów polegaj na Consent Mode.
|
||||||
|
|
||||||
## Wygląd — nadpisywanie stylów
|
## Wygląd — nadpisywanie stylów
|
||||||
|
|
||||||
Banner i przycisk mają domyślny, neutralny wygląd (light + dark) i działają bez
|
Banner i przycisk mają domyślny, neutralny wygląd (light + dark) i działają bez
|
||||||
|
|||||||
@@ -190,11 +190,43 @@ const pageMetadata = createPageMetadata({
|
|||||||
prowadzi do archiwum EN (`/en/articles`), nie na stronę główną — najbliżej tego,
|
prowadzi do archiwum EN (`/en/articles`), nie na stronę główną — najbliżej tego,
|
||||||
czego szuka odwiedzający.
|
czego szuka odwiedzający.
|
||||||
|
|
||||||
|
## Redirecty ze slug history — resolveRedirect
|
||||||
|
|
||||||
|
Para do `trackSlugHistoryHook` (patrz [hooks.md](./hooks.md)): hook zapisuje
|
||||||
|
stare slugi, `resolveRedirect` zamienia je z powrotem na 301/308, żeby zmiana
|
||||||
|
slug nie dawała 404. Wywołujesz w catch-all, gdy `resolveRoute` nic nie znajdzie:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { resolveRoute, resolveRedirect } from '@intecion/ipal-kit'
|
||||||
|
import { permanentRedirect, notFound } from 'next/navigation'
|
||||||
|
|
||||||
|
const route = await resolveRoute({ /* … */ })
|
||||||
|
if (!route) {
|
||||||
|
const dest = await resolveRedirect({
|
||||||
|
payload, locale, segments: slug, config: i18nConfig, homeSlug,
|
||||||
|
collections: [{ slug: 'pages' }], // domyślnie [{ slug: 'pages' }]
|
||||||
|
})
|
||||||
|
if (dest) permanentRedirect(dest) // HTTP 308 — pod SEO równoważne 301
|
||||||
|
notFound()
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Zwraca docelową ścieżkę (zlokalizowaną, z collapsowaniem home przez `homeSlug`)
|
||||||
|
albo `null`. Plugin tylko liczy — `permanentRedirect` woła projekt (plugin nie
|
||||||
|
importuje `next/navigation`). Każda kolekcja bez pola historii jest pomijana
|
||||||
|
bezpiecznie. `collections[].historyField` (domyślnie `'slugHistory'`) i
|
||||||
|
`slugField` (domyślnie `'slug'`) konfigurowalne.
|
||||||
|
|
||||||
|
Ograniczenia: tylko kolekcje „płaskie" (slug → ścieżka). Wpisy w archiwach
|
||||||
|
(`/artykuly/<wpis>`) nie są jeszcze obsługiwane. Jeśli `slug` jest `localized`,
|
||||||
|
rozważ `slugHistory` też `localized`, by historie języków się nie nakładały.
|
||||||
|
|
||||||
## Eksport
|
## Eksport
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
import {
|
import {
|
||||||
resolveRoute,
|
resolveRoute,
|
||||||
|
resolveRedirect,
|
||||||
getArchiveEntries,
|
getArchiveEntries,
|
||||||
buildArchivePath,
|
buildArchivePath,
|
||||||
buildEntryPath,
|
buildEntryPath,
|
||||||
|
|||||||
+20
-3
@@ -219,9 +219,26 @@ przetrwają redeploy. Patrz storage.md.
|
|||||||
|
|
||||||
### Health check
|
### Health check
|
||||||
|
|
||||||
Payload wystawia panel pod `/admin` — health check może pingować stronę główną
|
Zalecane: dedykowany endpoint `createHealthRoute` z pluginu — robi realny
|
||||||
albo `/admin`. Nie ustawiaj health check na endpoint wymagający bazy, jeśli
|
round-trip do bazy i zwraca 200/503, więc Coolify/Docker odróżni „proces żyje"
|
||||||
baza wstaje wolniej niż app.
|
od „app gotowa, baza dostępna":
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// app/api/health/route.ts
|
||||||
|
import { createHealthRoute } from '@intecion/ipal-kit'
|
||||||
|
import { getCachedPayload } from '@/lib/content'
|
||||||
|
export const dynamic = 'force-dynamic' // nigdy nie prerenderuj/cache'uj health
|
||||||
|
export const GET = createHealthRoute({ getCachedPayload })
|
||||||
|
```
|
||||||
|
|
||||||
|
Ustaw health check Coolify na `/api/health`. Opcje: `collection` (domyślnie
|
||||||
|
`'pages'` — kolekcja pingowana round-tripem), `extra` (dodatkowe sprawdzenia).
|
||||||
|
Zwraca JSON `{ status, db, tookMs, timestamp }`, `cache-control: no-store`.
|
||||||
|
|
||||||
|
Alternatywnie (prościej, bez bazy): ping strony głównej albo `/admin`. Nie
|
||||||
|
ustawiaj health checku na endpoint wymagający bazy, jeśli baza wstaje wolniej
|
||||||
|
niż app i orchestrator ubije kontener w oknie startu — albo daj odpowiedni
|
||||||
|
start period.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
+119
@@ -0,0 +1,119 @@
|
|||||||
|
# env — walidacja zmiennych środowiskowych na starcie
|
||||||
|
|
||||||
|
Łapie źle skonfigurowany deploy przy starcie, jednym czytelnym komunikatem ze
|
||||||
|
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),
|
||||||
|
[forms.md](./forms.md).
|
||||||
|
|
||||||
|
## Dlaczego bez zod
|
||||||
|
|
||||||
|
Plugin świadomie NIE wciąga `zod`. Wymuszanie biblioteki walidacji na każdym z
|
||||||
|
projektów to narzucona zależność (łamie A0 „żadnych narzuconych zależności").
|
||||||
|
`assertEnv` to mały, zero-dependency walidator robiący dokładnie to, czego
|
||||||
|
potrzeba.
|
||||||
|
|
||||||
|
## Integracja — jedna linia na starcie
|
||||||
|
|
||||||
|
Najlepsze miejsce to `instrumentation.ts` (Next woła `register()` raz przy
|
||||||
|
starcie serwera):
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// instrumentation.ts
|
||||||
|
import { assertEnv, ipalEnvRules } from '@intecion/ipal-kit'
|
||||||
|
|
||||||
|
export function register() {
|
||||||
|
assertEnv(ipalEnvRules({ storage: true, emailGraph: true, turnstile: true }))
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Alternatywnie na górze `payload.config.ts` (ładuje się i w buildzie, i w
|
||||||
|
runtime). Działa tylko po stronie serwera (czyta `process.env`) — NIE importuj
|
||||||
|
do komponentu klienckiego.
|
||||||
|
|
||||||
|
## ipalEnvRules — gotowy schemat dla stacku (opt-in)
|
||||||
|
|
||||||
|
Składa zestaw reguł z funkcji, których projekt faktycznie używa — strona na
|
||||||
|
dysku lokalnym nie jest zmuszana do `R2_*`, strona bez formularzy do Turnstile.
|
||||||
|
To nie sztywny wymagany zestaw (A0: plugin nie żąda configu, którego nie
|
||||||
|
używasz).
|
||||||
|
|
||||||
|
```ts
|
||||||
|
ipalEnvRules({
|
||||||
|
storage?: boolean, // R2_* (R2_BUCKET, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, R2_ENDPOINT, R2_PUBLIC_URL)
|
||||||
|
emailGraph?: boolean, // GRAPH_* (GRAPH_TENANT_ID, GRAPH_CLIENT_ID, GRAPH_CLIENT_SECRET, GRAPH_SENDER)
|
||||||
|
turnstile?: boolean | { siteKeyVar?: string; secretVar?: string },
|
||||||
|
serverUrlVar?: string, // domyślnie 'NEXT_PUBLIC_SERVER_URL'
|
||||||
|
secretVar?: string, // domyślnie 'PAYLOAD_SECRET'
|
||||||
|
databaseVar?: string, // domyślnie 'DATABASE_URI'
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Zawsze (rdzeń): `DATABASE_URI`, `PAYLOAD_SECRET`, `NEXT_PUBLIC_SERVER_URL` (URL),
|
||||||
|
`NODE_ENV` (opcjonalny, oneOf). Nazwy `R2_*` / `GRAPH_*` / `NEXT_PUBLIC_SERVER_URL`
|
||||||
|
odpowiadają temu, co czytają moduły pluginu. Turnstile/DB/secret to zmienne
|
||||||
|
projektowe — dałem powszechne nazwy z możliwością nadpisania.
|
||||||
|
|
||||||
|
Rozszerzenie o własne zmienne — spread:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
assertEnv([
|
||||||
|
...ipalEnvRules({ storage: true }),
|
||||||
|
{ name: 'MY_API_KEY', description: 'Klucz do integracji X' },
|
||||||
|
])
|
||||||
|
```
|
||||||
|
|
||||||
|
## assertEnv — walidator
|
||||||
|
|
||||||
|
```ts
|
||||||
|
assertEnv(rules: EnvRule[], options?: { env?, label? }): void
|
||||||
|
```
|
||||||
|
|
||||||
|
Zbiera WSZYSTKIE problemy i rzuca jeden zagregowany `Error`. Przy braku
|
||||||
|
problemów nie robi nic. `options.env` (domyślnie `process.env`) ułatwia testy;
|
||||||
|
`options.label` zmienia prefiks (domyślnie `[ipal]`).
|
||||||
|
|
||||||
|
### EnvRule
|
||||||
|
|
||||||
|
```ts
|
||||||
|
type EnvRule = {
|
||||||
|
name: string
|
||||||
|
required?: boolean // domyślnie true; false = waliduj tylko gdy obecne
|
||||||
|
kind?: 'string' | 'url' | 'number' | 'port' | 'boolean' | 'email' // domyślnie 'string'
|
||||||
|
oneOf?: readonly string[]
|
||||||
|
description?: string // pokazywane w błędzie — po co ta zmienna
|
||||||
|
validate?: (value: string) => string | true // własna reguła
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Ręcznie, bez presetu:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
assertEnv([
|
||||||
|
{ name: 'DATABASE_URI', description: 'MongoDB connection string' },
|
||||||
|
{ name: 'NEXT_PUBLIC_SERVER_URL', kind: 'url' },
|
||||||
|
{ name: 'NODE_ENV', required: false, oneOf: ['development', 'production', 'test'] },
|
||||||
|
{ name: 'SMTP_PORT', required: false, kind: 'port' },
|
||||||
|
])
|
||||||
|
```
|
||||||
|
|
||||||
|
### Przykładowy komunikat
|
||||||
|
|
||||||
|
```
|
||||||
|
[ipal] Environment validation failed (3 problems):
|
||||||
|
• DATABASE_URI is required but missing — MongoDB connection string
|
||||||
|
• NEXT_PUBLIC_SERVER_URL must be a valid URL (got "example.com") — Public site origin
|
||||||
|
• NODE_ENV must be one of: development, production, test (got "prod") — Node environment
|
||||||
|
Set these in your environment (Coolify → Environment, or .env) and redeploy.
|
||||||
|
```
|
||||||
|
|
||||||
|
Wszystkie braki widzisz naraz — nie poprawiasz ich po jednym przez kilka
|
||||||
|
redeployów.
|
||||||
|
|
||||||
|
## Eksport
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { assertEnv, ipalEnvRules } from '@intecion/ipal-kit'
|
||||||
|
import type { EnvRule, EnvKind, AssertEnvOptions, IpalEnvFeatures } from '@intecion/ipal-kit'
|
||||||
|
```
|
||||||
+110
@@ -159,6 +159,29 @@ Rate limit: 5/min/IP domyślnie, `maxPerMinute` zmienia, `0` wyłącza (gdy limi
|
|||||||
jest z przodu). In-memory — przy wielu instancjach licznik jest per-proces, więc
|
jest z przodu). In-memory — przy wielu instancjach licznik jest per-proces, więc
|
||||||
efektywny limit to per-instancja. Do formularza kontaktowego wystarcza.
|
efektywny limit to per-instancja. Do formularza kontaktowego wystarcza.
|
||||||
|
|
||||||
|
### Honeypot — darmowa druga warstwa antyspam
|
||||||
|
|
||||||
|
Ukryte pole, którego realny użytkownik nie widzi ani nie wypełni, a naiwny bot
|
||||||
|
tak. Zero tarcia (bez sieci, bez interakcji), obok Turnstile. Czyste funkcje —
|
||||||
|
klient renderuje input, serwer sprawdza:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// front — w formularzu:
|
||||||
|
import { honeypotInputProps } from '@intecion/ipal-kit/client'
|
||||||
|
<input {...honeypotInputProps()} /> // off-screen, aria-hidden, tabIndex -1
|
||||||
|
```
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// server action — SPRAWDŹ PIERWSZE, przed submitForm:
|
||||||
|
import { isHoneypotTripped, HONEYPOT_FIELD } from '@intecion/ipal-kit'
|
||||||
|
if (isHoneypotTripped(values)) return { success: true } // udawaj sukces (bot bez sygnału)
|
||||||
|
const { [HONEYPOT_FIELD]: _hp, ...clean } = values // usuń, by submitForm nie widział nieznanego pola
|
||||||
|
return submitForm({ /* … */ data: clean })
|
||||||
|
```
|
||||||
|
|
||||||
|
Nazwa pola domyślnie `company_url` (wygląda realnie dla bota); własna:
|
||||||
|
`honeypotInputProps('website_2')` + `isHoneypotTripped(values, 'website_2')`.
|
||||||
|
|
||||||
### Wynik to KOD, nie tekst
|
### Wynik to KOD, nie tekst
|
||||||
|
|
||||||
`submitForm` zwraca ustrukturyzowany błąd — plugin mówi CO się stało, projekt
|
`submitForm` zwraca ustrukturyzowany błąd — plugin mówi CO się stało, projekt
|
||||||
@@ -238,6 +261,93 @@ To obsługuje WSZYSTKIE kody (w tym `consent`, `rate_limited`, `validation` z
|
|||||||
`{field}`) tekstami z panelu. Ręczny switch (wyżej) zostaw tylko, jeśli nie
|
`{field}`) tekstami z panelu. Ręczny switch (wyżej) zostaw tylko, jeśli nie
|
||||||
używasz modułu notifications. Szczegóły: [notifications.md](./notifications.md).
|
używasz modułu notifications. Szczegóły: [notifications.md](./notifications.md).
|
||||||
|
|
||||||
|
## Logika klienta — useForm / useContactForm (bez markupu)
|
||||||
|
|
||||||
|
`submitForm` to serwer. Po stronie klienta powtarzała się ta sama hydraulika w
|
||||||
|
każdym projekcie: `useState` na pola, regex e-maila, token Turnstile, submit,
|
||||||
|
stan sukcesu/błędu — ~150 linii identycznego kodu na projekt. To wyniesione do
|
||||||
|
hooka. **Hook nie renderuje ŻADNEGO markupu** — projekt zachowuje 100% kontroli
|
||||||
|
nad wyglądem (zasada „nie pozbawiamy projektów kontroli nad wyglądem").
|
||||||
|
|
||||||
|
To warstwa LOGIKI, nie zamiennik buildera. Zasada „pola z buildera" obowiązuje
|
||||||
|
dalej: dla formularzy edytowalnych przez redaktora budujesz `initialValues` i
|
||||||
|
reguły z definicji z panelu i podajesz do `useForm` (wariant dynamiczny niżej).
|
||||||
|
`useContactForm` to preset dla klasycznego formularza kontaktowego o stałych
|
||||||
|
polach — gdy to świadomie właściwy wybór.
|
||||||
|
|
||||||
|
Antywzorzec, który hook eliminuje, to **duplikacja logiki** (walidacja/submit/
|
||||||
|
Turnstile ręcznie w każdym projekcie), a nie „użycie hooka".
|
||||||
|
|
||||||
|
### Preset — formularz kontaktowy (zero walidatorów)
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
'use client'
|
||||||
|
import { useContactForm } from '@intecion/ipal-kit/client'
|
||||||
|
|
||||||
|
const f = useContactForm({
|
||||||
|
submitAction, // Twój server action wołający submitForm
|
||||||
|
requireTurnstile: Boolean(siteKey),
|
||||||
|
requireTopic: topics.length > 0,
|
||||||
|
requireConsent: Boolean(consentText),
|
||||||
|
})
|
||||||
|
// JSX i klasy Twoje — z hooka tylko wiring:
|
||||||
|
<input value={f.values.email} onChange={(e) => f.setField('email', e.target.value)}
|
||||||
|
className={f.errors.email ? 'border-red-500 …' : '…'} />
|
||||||
|
<form onSubmit={f.handleSubmit}>…</form>
|
||||||
|
{f.isSuccess && <PanelSukcesu onReset={f.reset} />}
|
||||||
|
```
|
||||||
|
|
||||||
|
Pola presetu: `name, email, phone, topic, message, consent`. Zwraca:
|
||||||
|
`values, errors, isSubmitting, isSuccess, errorMessage, turnstileToken,
|
||||||
|
setField, setValues, setTurnstileToken, handleSubmit, reset`.
|
||||||
|
|
||||||
|
### Generyczny engine — dowolne / dynamiczne pola
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { useForm, buildValidator, required, email, minLength, pattern } from '@intecion/ipal-kit/client'
|
||||||
|
|
||||||
|
const f = useForm({
|
||||||
|
initialValues: { company: '', nip: '', email: '', message: '' },
|
||||||
|
submitAction,
|
||||||
|
validate: buildValidator({
|
||||||
|
company: [required()],
|
||||||
|
nip: [required(), pattern(/^\d{10}$/, 'NIP = 10 cyfr')],
|
||||||
|
email: [required(), email()],
|
||||||
|
message: [required(), minLength(10)],
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Pola dynamiczne z buildera — schemat budowany w runtime z definicji z panelu:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
const initialValues = Object.fromEntries(fields.map((fl) => [fl.name, fl.type === 'checkbox' ? false : '']))
|
||||||
|
const validate = buildValidator(Object.fromEntries(fields.map((fl) => [fl.name, fl.required ? [required()] : []])))
|
||||||
|
const f = useForm({ initialValues, submitAction, validate })
|
||||||
|
```
|
||||||
|
|
||||||
|
### Walidatory (czyste — też po stronie serwera)
|
||||||
|
|
||||||
|
`required`, `email`, `minLength`, `maxLength`, `checked`, `pattern`, `custom`,
|
||||||
|
`isEmail`, `buildValidator`. Każdy przyjmuje własny komunikat. Są czyste (bez
|
||||||
|
`'use client'`), więc tych samych reguł użyjesz do re-walidacji w server action.
|
||||||
|
|
||||||
|
### errors to STRING, nie boolean
|
||||||
|
|
||||||
|
`errors.<pole>` to komunikat (truthy, gdy błąd). Działa jako warunek `className`
|
||||||
|
jak dawny boolean, a dodatkowo masz tekst do wyświetlenia. `setField` czyści błąd
|
||||||
|
pola przy edycji (domyślnie).
|
||||||
|
|
||||||
|
### resolveLocalized — koniec z getSafeString
|
||||||
|
|
||||||
|
Rozwiązywanie wartości lokalizowanej (topics, etykiety) to jeden import, nie
|
||||||
|
kopiowany `(v as any)[locale]`:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { resolveLocalized } from '@intecion/ipal-kit' // lub /client
|
||||||
|
const label = resolveLocalized(topic.label, locale)
|
||||||
|
```
|
||||||
|
|
||||||
## PUŁAPKA — pola captchy
|
## PUŁAPKA — pola captchy
|
||||||
|
|
||||||
Turnstile wstrzykuje ukryte pole `cf-turnstile-response`. Plugin je toleruje
|
Turnstile wstrzykuje ukryte pole `cf-turnstile-response`. Plugin je toleruje
|
||||||
|
|||||||
+68
-12
@@ -109,21 +109,76 @@ export const Pages: CollectionConfig = {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Projekt w resolveRoute / sprawdzeniu redirectów: jeśli żądany slug jest w
|
Odczyt tej historii robi `resolveRedirect` (moduł content) — NIE pisz własnego
|
||||||
slugHistory jakiejś strony → 301 na jej aktualny slug. Przykład:
|
lookupu. W catch-all, gdy `resolveRoute` nie znajdzie strony:
|
||||||
|
|
||||||
```ts
|
```tsx
|
||||||
// w page.tsx, gdy resolveRoute nie znajdzie strony po slug:
|
import { resolveRoute, resolveRedirect } from '@intecion/ipal-kit'
|
||||||
const byHistory = await payload.find({
|
import { permanentRedirect, notFound } from 'next/navigation'
|
||||||
collection: 'pages',
|
|
||||||
where: { 'slugHistory.slug': { equals: requestedSlug } },
|
const route = await resolveRoute({ /* … */ })
|
||||||
limit: 1,
|
if (!route) {
|
||||||
})
|
const dest = await resolveRedirect({
|
||||||
if (byHistory.docs[0]) {
|
payload, locale, segments: slug, config: i18nConfig, homeSlug,
|
||||||
redirect(`/${locale}/${byHistory.docs[0].slug}`) // 301 na aktualny
|
collections: [{ slug: 'pages' }],
|
||||||
|
})
|
||||||
|
if (dest) permanentRedirect(dest) // HTTP 308 — pod SEO równoważne 301
|
||||||
|
notFound()
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Plugin liczy cel, projekt woła `permanentRedirect` (plugin nie importuje
|
||||||
|
`next/navigation`). Kolekcja bez pola `slugHistory` jest pomijana bezpiecznie
|
||||||
|
(try/catch — ta sama klasa błędu co `_status`). Slugi wielosegmentowe
|
||||||
|
(`uslugi/biznesowe`) działają; wpisy archiwów (`/artykuly/<wpis>`) jeszcze nie.
|
||||||
|
Szczegóły: [content.md](./content.md).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## buildCrossLocaleFieldSync — pola wspólne w lokalizowanym blocks
|
||||||
|
|
||||||
|
Payload lokalizuje całe pole `blocks`/`array` naraz — nie da się oznaczyć
|
||||||
|
pojedynczego podpola (obrazka) jako nielokalizowanego. Efekt: redaktor wybiera
|
||||||
|
obrazki po polsku i musi powtórzyć wybór w każdym języku. Ten hook kopiuje
|
||||||
|
wskazane pola (obrazki, ikony) z edytowanego locale do pozostałych.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { buildCrossLocaleFieldSync } from '@intecion/ipal-kit'
|
||||||
|
import { i18nConfig } from '@/i18n.config'
|
||||||
|
|
||||||
|
hooks: {
|
||||||
|
afterChange: [
|
||||||
|
buildCrossLocaleFieldSync({ config: i18nConfig, collection: 'pages', fields: ['image'] }),
|
||||||
|
],
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- **Lista języków z `config`** — NIGDY nie hardkoduj `['pl','en',…]` (A0:
|
||||||
|
dodanie języka w panelu działa bez zmiany kodu).
|
||||||
|
- **Dopasowanie wierszy po `id`**, fallback pozycyjny tylko gdy `blockType` się
|
||||||
|
zgadza — nie wrzuci obrazka do bloku innego typu.
|
||||||
|
- **Wiele pól:** `fields: ['image', 'backgroundImage', 'icon']`.
|
||||||
|
- **Tylko wypełnione pola** — wyczyszczenie obrazka w jednym języku nie zeruje
|
||||||
|
go w innych (zachowawczo).
|
||||||
|
- Guard `_ipalSyncingCrossLocale` zrywa pętlę `afterChange`→`update`.
|
||||||
|
|
||||||
|
Parametry: `arrayField` (domyślnie `'layout'`), `guardFlag`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## buildNoindexField — checkbox → meta.noindex (pole, nie hook)
|
||||||
|
|
||||||
|
Sidebarowy checkbox `noindex` zgrany z `meta.noindex` (to czyta sitemap i
|
||||||
|
metadata), bez `any`. To field factory — wpinasz w `fields`, nie w `hooks`:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { buildNoindexField } from '@intecion/ipal-kit'
|
||||||
|
fields: [ /* … */ buildNoindexField() ]
|
||||||
|
```
|
||||||
|
|
||||||
|
Opcje: `name`, `label`, `description`, `metaPath` (domyślnie `'meta.noindex'`),
|
||||||
|
`overrides`. Szczegóły: [seo.md](./seo.md).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## KOLEJNOŚĆ hooków (ważne)
|
## KOLEJNOŚĆ hooków (ważne)
|
||||||
@@ -141,9 +196,10 @@ Typowa Pages:
|
|||||||
hooks: {
|
hooks: {
|
||||||
beforeChange: [setPublishedAtHook, trackSlugHistoryHook],
|
beforeChange: [setPublishedAtHook, trackSlugHistoryHook],
|
||||||
beforeDelete: [buildPreventDeleteSystemPage(...)],
|
beforeDelete: [buildPreventDeleteSystemPage(...)],
|
||||||
afterChange: [afterChange], // revalidate
|
afterChange: [afterChange, buildCrossLocaleFieldSync({ config, collection: 'pages', fields: ['image'] })],
|
||||||
afterDelete: [afterDelete],
|
afterDelete: [afterDelete],
|
||||||
}
|
}
|
||||||
|
// pole: buildNoindexField() w `fields`
|
||||||
```
|
```
|
||||||
|
|
||||||
Które hooki wpiąć zależy od kolekcji — nie każda potrzebuje wszystkich (blog:
|
Które hooki wpiąć zależy od kolekcji — nie każda potrzebuje wszystkich (blog:
|
||||||
|
|||||||
+19
@@ -729,6 +729,25 @@ frazy), strony z parametrami, wyniki wyszukiwania. Plugin wspiera to przez pole
|
|||||||
Redaktor zaznacza `noindex` w panelu (pole SEO strony), plugin generuje tag.
|
Redaktor zaznacza `noindex` w panelu (pole SEO strony), plugin generuje tag.
|
||||||
Alternatywnie: dodaj `noindex` do System Pages o rolach prawnych automatycznie.
|
Alternatywnie: dodaj `noindex` do System Pages o rolach prawnych automatycznie.
|
||||||
|
|
||||||
|
### buildNoindexField — przyjazny checkbox w sidebarze
|
||||||
|
|
||||||
|
Zamiast własnego checkboxa + hooka z `(data as any).meta.noindex = …` użyj
|
||||||
|
gotowego pola. Jeden przełącznik dla redaktora, zgrany z `meta.noindex` (to
|
||||||
|
czyta sitemap i metadata), bez `any`, bez rozjazdu między dwoma miejscami:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { buildNoindexField } from '@intecion/ipal-kit'
|
||||||
|
|
||||||
|
export const Pages: CollectionConfig = {
|
||||||
|
fields: [ /* … */ buildNoindexField() ],
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Idempotentne: jeśli ustawiony checkbox LUB istniejące `meta.noindex` — strona
|
||||||
|
wychodzi `noindex`; nie da się ich rozjechać. Opcje: `name` (domyślnie
|
||||||
|
`'noindex'`), `label`, `description`, `metaPath` (domyślnie `'meta.noindex'`),
|
||||||
|
`overrides` (pozycja, access itp.).
|
||||||
|
|
||||||
## robots.txt — blokada parametrów (crawl budget)
|
## robots.txt — blokada parametrów (crawl budget)
|
||||||
|
|
||||||
URL-e z parametrami (`?meter=101-120m2`, `?s=fraza`) marnują budżet indeksowania —
|
URL-e z parametrami (`?meter=101-120m2`, `?s=fraza`) marnują budżet indeksowania —
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@intecion/ipal-kit",
|
"name": "@intecion/ipal-kit",
|
||||||
"version": "1.6.2",
|
"version": "1.6.6",
|
||||||
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
|
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"repository": {
|
"repository": {
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ export { Analytics } from '../modules/analytics/client.js'
|
|||||||
*/
|
*/
|
||||||
export {
|
export {
|
||||||
ConsentProvider,
|
ConsentProvider,
|
||||||
|
ConsentScript,
|
||||||
CookieBanner,
|
CookieBanner,
|
||||||
CookieButton,
|
CookieButton,
|
||||||
useConsent,
|
useConsent,
|
||||||
@@ -24,12 +25,27 @@ export {
|
|||||||
} from '../modules/consent/client.js'
|
} from '../modules/consent/client.js'
|
||||||
|
|
||||||
export type { CookieBannerClassNames } from '../modules/consent/client.js'
|
export type { CookieBannerClassNames } from '../modules/consent/client.js'
|
||||||
|
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js'
|
||||||
export { useContactForm } from '../modules/forms/useContactForm.js'
|
export { useContactForm } from '../modules/forms/useContactForm.js'
|
||||||
export type {
|
export type {
|
||||||
ContactFormErrors,
|
ContactFormErrors,
|
||||||
ContactFormValues,
|
ContactFormValues,
|
||||||
SubmitAction,
|
SubmitAction,
|
||||||
} from '../modules/forms/useContactForm.js'
|
} from '../modules/forms/useContactForm.js'
|
||||||
|
export { useForm } from '../modules/forms/useForm.js'
|
||||||
|
export type { FormErrors, FormSubmitAction, Validator } from '../modules/forms/useForm.js'
|
||||||
|
export {
|
||||||
|
buildValidator,
|
||||||
|
checked,
|
||||||
|
custom,
|
||||||
|
email,
|
||||||
|
isEmail,
|
||||||
|
maxLength,
|
||||||
|
minLength,
|
||||||
|
pattern,
|
||||||
|
required,
|
||||||
|
} from '../modules/forms/validators.js'
|
||||||
|
export type { Rule } from '../modules/forms/validators.js'
|
||||||
// Pure i18n path helpers — no server/RSC deps, safe to import in client
|
// Pure i18n path helpers — no server/RSC deps, safe to import in client
|
||||||
// components (e.g. a LanguageSwitcher that computes locale URLs on the client).
|
// components (e.g. a LanguageSwitcher that computes locale URLs on the client).
|
||||||
export {
|
export {
|
||||||
|
|||||||
+27
-2
@@ -49,6 +49,7 @@ export {
|
|||||||
buildEntryPath,
|
buildEntryPath,
|
||||||
getArchiveEntries,
|
getArchiveEntries,
|
||||||
parsePageParam,
|
parsePageParam,
|
||||||
|
resolveRedirect,
|
||||||
resolveRoute,
|
resolveRoute,
|
||||||
} from './modules/content/index.js'
|
} from './modules/content/index.js'
|
||||||
export type { ArchiveEntries } from './modules/content/index.js'
|
export type { ArchiveEntries } from './modules/content/index.js'
|
||||||
@@ -61,14 +62,37 @@ export type { MailAdapterArgs } from './modules/email/mailAdapter.js'
|
|||||||
// Payload loads the config (or runs generate:importmap) as a plain Node script.
|
// Payload loads the config (or runs generate:importmap) as a plain Node script.
|
||||||
export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js'
|
export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js'
|
||||||
export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js'
|
export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js'
|
||||||
|
// Boot-time environment validation (fail fast on misconfigured deploys).
|
||||||
|
export { assertEnv, ipalEnvRules } from './modules/env/index.js'
|
||||||
|
export type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from './modules/env/index.js'
|
||||||
export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
|
export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
|
||||||
|
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './modules/forms/honeypot.js'
|
||||||
export type {
|
export type {
|
||||||
FormsCollectionOverrides,
|
FormsCollectionOverrides,
|
||||||
FormsFieldsOverride,
|
FormsFieldsOverride,
|
||||||
FormsOption,
|
FormsOption,
|
||||||
} from './modules/forms/types.js'
|
} from './modules/forms/types.js'
|
||||||
export { createContentHelpers } from './modules/frontend/index.js'
|
export type { FormErrors, FormSubmitAction, Validator } from './modules/forms/useForm.js'
|
||||||
|
// Validation rules are pure — exported server-side too, for re-validating a
|
||||||
|
// submission inside a server action. (useForm/useContactForm are client-only →
|
||||||
|
// '@intecion/ipal-kit/client'.)
|
||||||
export {
|
export {
|
||||||
|
buildValidator,
|
||||||
|
checked,
|
||||||
|
custom,
|
||||||
|
email,
|
||||||
|
isEmail,
|
||||||
|
maxLength,
|
||||||
|
minLength,
|
||||||
|
pattern,
|
||||||
|
required,
|
||||||
|
} from './modules/forms/validators.js'
|
||||||
|
export type { Rule } from './modules/forms/validators.js'
|
||||||
|
export { createContentHelpers } from './modules/frontend/index.js'
|
||||||
|
// Healthcheck route (Coolify/Docker liveness with a real DB round-trip).
|
||||||
|
export { createHealthRoute } from './modules/health/index.js'
|
||||||
|
export {
|
||||||
|
buildCrossLocaleFieldSync,
|
||||||
buildPreventDeleteSystemPage,
|
buildPreventDeleteSystemPage,
|
||||||
buildRevalidateHook,
|
buildRevalidateHook,
|
||||||
buildValidateUniqueRole,
|
buildValidateUniqueRole,
|
||||||
@@ -110,8 +134,8 @@ export {
|
|||||||
SITE_SETTINGS_SLUG,
|
SITE_SETTINGS_SLUG,
|
||||||
} from './modules/payload/index.js'
|
} from './modules/payload/index.js'
|
||||||
export { buildSecurityHeaders } from './modules/security/index.js'
|
export { buildSecurityHeaders } from './modules/security/index.js'
|
||||||
|
|
||||||
export { buildCsp } from './modules/security/index.js'
|
export { buildCsp } from './modules/security/index.js'
|
||||||
|
|
||||||
export type { BuildCspArgs } from './modules/security/index.js'
|
export type { BuildCspArgs } from './modules/security/index.js'
|
||||||
export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'
|
export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'
|
||||||
export type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js'
|
export type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js'
|
||||||
@@ -135,6 +159,7 @@ export {
|
|||||||
buildOrganizationJsonLd,
|
buildOrganizationJsonLd,
|
||||||
validateFaviconField,
|
validateFaviconField,
|
||||||
} from './modules/seo/index.js'
|
} from './modules/seo/index.js'
|
||||||
|
export { buildNoindexField } from './modules/seo/index.js'
|
||||||
export {
|
export {
|
||||||
buildBreadcrumbJsonLd,
|
buildBreadcrumbJsonLd,
|
||||||
buildSiteNavigationJsonLd,
|
buildSiteNavigationJsonLd,
|
||||||
|
|||||||
@@ -0,0 +1,109 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useEffect, useRef } from 'react'
|
||||||
|
|
||||||
|
import type { ConsentCategory } from './categories.js'
|
||||||
|
|
||||||
|
import { useConsentContext } from './ConsentContext.js'
|
||||||
|
|
||||||
|
type ConsentScriptProps = {
|
||||||
|
/** Default true. */
|
||||||
|
async?: boolean
|
||||||
|
/** Extra attributes on the <script> (e.g. { 'data-domain': 'x.com' }). */
|
||||||
|
attributes?: Record<string, string>
|
||||||
|
/**
|
||||||
|
* Consent category that must be granted before the script loads. Typically
|
||||||
|
* 'analytics' (GA, Plausible) or 'marketing' (Meta Pixel, ads, chat widgets).
|
||||||
|
*/
|
||||||
|
category: ConsentCategory
|
||||||
|
/**
|
||||||
|
* Inline JS to run once granted. If `src` is also set, it runs after the
|
||||||
|
* external script loads (so init code can rely on the library). A plain
|
||||||
|
* string of code — NOT user input (you control it), it goes into a <script>.
|
||||||
|
*/
|
||||||
|
code?: string
|
||||||
|
defer?: boolean
|
||||||
|
/** Stable id used to dedupe — the script is injected at most once. */
|
||||||
|
id?: string
|
||||||
|
/** External script URL. Injected only once the category is granted. */
|
||||||
|
src?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Loads a third-party script ONLY after the visitor has granted consent for its
|
||||||
|
* category — the GDPR-correct default for anything that isn't strictly
|
||||||
|
* necessary. Renders nothing until then. Reacts live to the consent context, so
|
||||||
|
* a script appears the moment the visitor accepts in the banner, with no reload.
|
||||||
|
*
|
||||||
|
* Use this for third parties that have NO Google Consent Mode of their own (Meta
|
||||||
|
* Pixel, LinkedIn Insight, chat widgets, custom analytics). GA/GTM are better
|
||||||
|
* handled by Consent Mode (the module's updateConsent already does that) — reach
|
||||||
|
* for ConsentScript when a vendor can't be gated that way.
|
||||||
|
*
|
||||||
|
* Must be rendered inside <ConsentProvider>.
|
||||||
|
*
|
||||||
|
* <ConsentScript category="marketing" src="https://connect.facebook.net/en_US/fbevents.js" />
|
||||||
|
* <ConsentScript category="analytics"
|
||||||
|
* src="https://plausible.io/js/script.js"
|
||||||
|
* attributes={{ 'data-domain': 'example.com' }} />
|
||||||
|
* <ConsentScript category="marketing" code={`fbq('init','123');fbq('track','PageView')`} />
|
||||||
|
*
|
||||||
|
* Note on withdrawal: once a script has loaded it keeps running for that page
|
||||||
|
* (a <script> tag can't be truly unloaded) — withdrawing consent stops the NEXT
|
||||||
|
* load. For vendors that support it, prefer Consent Mode so running tags honor
|
||||||
|
* the change immediately; ConsentScript gates the initial load.
|
||||||
|
*/
|
||||||
|
export function ConsentScript({
|
||||||
|
id,
|
||||||
|
async: asyncAttr = true,
|
||||||
|
attributes,
|
||||||
|
category,
|
||||||
|
code,
|
||||||
|
defer,
|
||||||
|
src,
|
||||||
|
}: ConsentScriptProps) {
|
||||||
|
const { state } = useConsentContext()
|
||||||
|
const granted = state[category] === true
|
||||||
|
const injectedRef = useRef(false)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!granted || injectedRef.current) {return}
|
||||||
|
if (!src && !code) {return}
|
||||||
|
|
||||||
|
const dedupeId = id ?? (src ? `ipal-cs-${src}` : undefined)
|
||||||
|
if (dedupeId && document.getElementById(dedupeId)) {
|
||||||
|
injectedRef.current = true
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
injectedRef.current = true
|
||||||
|
|
||||||
|
const runInline = () => {
|
||||||
|
if (!code) {return}
|
||||||
|
const inline = document.createElement('script')
|
||||||
|
if (dedupeId) {inline.id = `${dedupeId}-inline`}
|
||||||
|
inline.textContent = code
|
||||||
|
document.head.appendChild(inline)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (src) {
|
||||||
|
const el = document.createElement('script')
|
||||||
|
el.src = src
|
||||||
|
if (dedupeId) {el.id = dedupeId}
|
||||||
|
if (asyncAttr) {el.async = true}
|
||||||
|
if (defer) {el.defer = true}
|
||||||
|
if (attributes) {for (const [k, v] of Object.entries(attributes)) {el.setAttribute(k, v)}}
|
||||||
|
el.addEventListener('load', runInline, { once: true })
|
||||||
|
document.head.appendChild(el)
|
||||||
|
} else {
|
||||||
|
runInline()
|
||||||
|
}
|
||||||
|
// Deliberately no removal on cleanup: a loaded third-party script can't be
|
||||||
|
// meaningfully unloaded. Withdrawal is handled by not re-injecting (and, for
|
||||||
|
// vendors that support it, Consent Mode). See the component doc.
|
||||||
|
}, [granted, src, code, id, attributes, asyncAttr, defer])
|
||||||
|
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
export default ConsentScript
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
'use client'
|
'use client'
|
||||||
export { ConsentProvider, useConsentContext } from './ConsentContext.js'
|
export { ConsentProvider, useConsentContext } from './ConsentContext.js'
|
||||||
|
export { ConsentScript } from './ConsentScript.js'
|
||||||
export { CookieBanner } from './CookieBanner.js'
|
export { CookieBanner } from './CookieBanner.js'
|
||||||
export type { CookieBannerClassNames } from './CookieBanner.js'
|
export type { CookieBannerClassNames } from './CookieBanner.js'
|
||||||
export { CookieButton } from './CookieButton.js'
|
export { CookieButton } from './CookieButton.js'
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ export { buildArchiveFields } from './archiveFields.js'
|
|||||||
export { getArchiveEntries } from './getArchiveEntries.js'
|
export { getArchiveEntries } from './getArchiveEntries.js'
|
||||||
export type { ArchiveEntries } from './getArchiveEntries.js'
|
export type { ArchiveEntries } from './getArchiveEntries.js'
|
||||||
export { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js'
|
export { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js'
|
||||||
|
export { resolveRedirect } from './resolveRedirect.js'
|
||||||
export { resolveRoute } from './resolveRoute.js'
|
export { resolveRoute } from './resolveRoute.js'
|
||||||
export type { ResolvedRoute } from './resolveRoute.js'
|
export type { ResolvedRoute } from './resolveRoute.js'
|
||||||
export type { ContentCollectionOption, ContentOption } from './types.js'
|
export type { ContentCollectionOption, ContentOption } from './types.js'
|
||||||
|
|||||||
@@ -0,0 +1,119 @@
|
|||||||
|
import type { BasePayload } from 'payload'
|
||||||
|
|
||||||
|
import type { I18nConfig } from '../i18n/index.js'
|
||||||
|
|
||||||
|
import { buildLocalizedPath } from '../i18n/index.js'
|
||||||
|
|
||||||
|
type RedirectCollection = {
|
||||||
|
/**
|
||||||
|
* Array field holding past slugs, each row `{ slug }`. Default 'slugHistory'
|
||||||
|
* — the field `trackSlugHistoryHook` writes. The subfield queried is
|
||||||
|
* `<field>.slug`.
|
||||||
|
*/
|
||||||
|
historyField?: string
|
||||||
|
/** Collection slug to search, e.g. 'pages'. */
|
||||||
|
slug: string
|
||||||
|
/** Current-slug field on the doc. Default 'slug'. */
|
||||||
|
slugField?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
type ResolveRedirectArgs = {
|
||||||
|
/**
|
||||||
|
* Collections to search, in order. Default [{ slug: 'pages' }]. A collection
|
||||||
|
* without a slug-history field is skipped safely (no crash), so passing a
|
||||||
|
* collection that lacks it costs nothing.
|
||||||
|
*/
|
||||||
|
collections?: RedirectCollection[]
|
||||||
|
config: I18nConfig
|
||||||
|
/** Home slug map/string, so a renamed homepage still collapses to the root. */
|
||||||
|
homeSlug?: Record<string, string> | string
|
||||||
|
/** Active locale (the request's locale). */
|
||||||
|
locale: string
|
||||||
|
payload: BasePayload
|
||||||
|
/** Incoming route segments (what 404'd), e.g. ['uslugi', 'stara-nazwa']. */
|
||||||
|
segments: string[] | undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
type DocShape = { slug?: unknown }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolves a 301/308 destination for a URL that no longer matches any current
|
||||||
|
* slug, by looking the old slug up in each collection's slug-history. Returns
|
||||||
|
* the current localized path to redirect to, or null when nothing matches.
|
||||||
|
*
|
||||||
|
* This is the read side of `trackSlugHistoryHook`: that hook records old slugs
|
||||||
|
* on save; this turns them back into a redirect so a renamed page never 404s
|
||||||
|
* (a real SEO loss). The plugin only COMPUTES the destination — the project
|
||||||
|
* issues the redirect, keeping the peer-dep boundary (no next/navigation import
|
||||||
|
* here):
|
||||||
|
*
|
||||||
|
* // app/[locale]/[[...slug]]/page.tsx (or app/[[...slug]] when single-locale)
|
||||||
|
* const route = await resolveRoute({ ... })
|
||||||
|
* if (!route) {
|
||||||
|
* const dest = await resolveRedirect({
|
||||||
|
* payload, locale, segments: slug, config: i18nConfig, homeSlug,
|
||||||
|
* collections: [{ slug: 'pages' }],
|
||||||
|
* })
|
||||||
|
* if (dest) permanentRedirect(dest) // from 'next/navigation' → HTTP 308 (SEO-equivalent to 301)
|
||||||
|
* notFound()
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* Multi-segment slugs (an editor slug like 'uslugi/biznesowe') are matched as
|
||||||
|
* the joined path, so they work unchanged. Archive ENTRY URLs
|
||||||
|
* (/artykuly/<entry>) aren't handled here yet — only flat collections; pass
|
||||||
|
* the collections whose slugs map directly to a path.
|
||||||
|
*/
|
||||||
|
export async function resolveRedirect({
|
||||||
|
collections = [{ slug: 'pages' }],
|
||||||
|
config,
|
||||||
|
homeSlug,
|
||||||
|
locale,
|
||||||
|
payload,
|
||||||
|
segments,
|
||||||
|
}: ResolveRedirectArgs): Promise<null | string> {
|
||||||
|
const oldSlug = (segments ?? []).filter(Boolean).join('/')
|
||||||
|
// Root never redirects — there's no "old slug" for the locale home.
|
||||||
|
if (!oldSlug) {return null}
|
||||||
|
|
||||||
|
for (const col of collections) {
|
||||||
|
const historyField = col.historyField ?? 'slugHistory'
|
||||||
|
const slugField = col.slugField ?? 'slug'
|
||||||
|
|
||||||
|
let currentSlug: string | undefined
|
||||||
|
try {
|
||||||
|
const res = await payload.find({
|
||||||
|
collection: col.slug as never,
|
||||||
|
depth: 0,
|
||||||
|
limit: 1,
|
||||||
|
locale: locale as never,
|
||||||
|
pagination: false,
|
||||||
|
where: { [`${historyField}.slug`]: { equals: oldSlug } } as never,
|
||||||
|
})
|
||||||
|
const doc = (res?.docs?.[0] ?? null) as DocShape | null
|
||||||
|
if (doc && typeof doc[slugField as keyof DocShape] === 'string') {
|
||||||
|
currentSlug = doc[slugField as keyof DocShape] as string
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Collection has no slug-history field (path not queryable) or the query
|
||||||
|
// failed — skip it rather than 500 the 404 path. Same guard as the
|
||||||
|
// drafts/_status lesson.
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!currentSlug || currentSlug === oldSlug) {continue}
|
||||||
|
|
||||||
|
const dest = buildLocalizedPath({
|
||||||
|
config,
|
||||||
|
homeSlug,
|
||||||
|
locale,
|
||||||
|
slugs: { [locale]: currentSlug },
|
||||||
|
})
|
||||||
|
|
||||||
|
// Never redirect a path to itself (would loop).
|
||||||
|
if (dest && dest !== `/${oldSlug}` && dest !== `/${locale}/${oldSlug}`) {
|
||||||
|
return dest
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null
|
||||||
|
}
|
||||||
Vendored
+137
@@ -0,0 +1,137 @@
|
|||||||
|
/**
|
||||||
|
* Zero-dependency environment validation. The plugin deliberately does NOT pull
|
||||||
|
* in zod — forcing a validation library on every project would be a dependency
|
||||||
|
* the project didn't ask for (against the A0 "no imposed deps" rule). This is a
|
||||||
|
* tiny validator that does the one thing we need: check the vars a deploy needs
|
||||||
|
* and FAIL FAST with a readable, all-at-once message instead of a cryptic
|
||||||
|
* runtime crash (e.g. `getaddrinfo ENOTFOUND` halfway through a Docker build).
|
||||||
|
*/
|
||||||
|
|
||||||
|
export type EnvKind = 'boolean' | 'email' | 'number' | 'port' | 'string' | 'url'
|
||||||
|
|
||||||
|
export type EnvRule = {
|
||||||
|
/** Shown in the error to tell the deployer what the var is for. */
|
||||||
|
description?: string
|
||||||
|
/** Shape check applied when a value is present. Default 'string' (non-empty). */
|
||||||
|
kind?: EnvKind
|
||||||
|
/** Variable name, e.g. 'DATABASE_URI'. */
|
||||||
|
name: string
|
||||||
|
/** Allowed values (e.g. NODE_ENV). Checked when a value is present. */
|
||||||
|
oneOf?: readonly string[]
|
||||||
|
/** Default true. When false, the var is only validated if present. */
|
||||||
|
required?: boolean
|
||||||
|
/** Custom check: return true if OK, or an error message string. */
|
||||||
|
validate?: (value: string) => string | true
|
||||||
|
}
|
||||||
|
|
||||||
|
export type AssertEnvOptions = {
|
||||||
|
/** Source of values. Default process.env. */
|
||||||
|
env?: Record<string, string | undefined>
|
||||||
|
/** Error prefix. Default '[ipal]'. */
|
||||||
|
label?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const EMAIL_RE = /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/
|
||||||
|
|
||||||
|
/** Validate one present value against its rule. Returns an error message or null. */
|
||||||
|
function checkValue(rule: EnvRule, value: string): null | string {
|
||||||
|
const { name, kind = 'string', oneOf } = rule
|
||||||
|
|
||||||
|
if (oneOf && !oneOf.includes(value)) {
|
||||||
|
return `${name} must be one of: ${oneOf.join(', ')} (got "${value}")`
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (kind) {
|
||||||
|
case 'boolean':
|
||||||
|
if (!/^(true|false|1|0|yes|no)$/i.test(value)) {
|
||||||
|
return `${name} must be a boolean (true/false/1/0/yes/no, got "${value}")`
|
||||||
|
}
|
||||||
|
break
|
||||||
|
case 'email':
|
||||||
|
if (!EMAIL_RE.test(value)) {return `${name} must be an e-mail address (got "${value}")`}
|
||||||
|
break
|
||||||
|
case 'number':
|
||||||
|
if (!Number.isFinite(Number(value))) {return `${name} must be a number (got "${value}")`}
|
||||||
|
break
|
||||||
|
case 'port': {
|
||||||
|
const n = Number(value)
|
||||||
|
if (!Number.isInteger(n) || n < 1 || n > 65535) {
|
||||||
|
return `${name} must be a port 1–65535 (got "${value}")`
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
case 'url':
|
||||||
|
try {
|
||||||
|
|
||||||
|
new URL(value)
|
||||||
|
} catch {
|
||||||
|
return `${name} must be a valid URL (got "${value}")`
|
||||||
|
}
|
||||||
|
break
|
||||||
|
case 'string':
|
||||||
|
default:
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rule.validate) {
|
||||||
|
const res = rule.validate(value)
|
||||||
|
if (res !== true) {return typeof res === 'string' ? res : `${name} is invalid`}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validates the given rules against the environment and THROWS a single,
|
||||||
|
* aggregated error listing every problem at once (not just the first). Call it
|
||||||
|
* once at boot — in payload.config.ts, or Next's instrumentation.ts register().
|
||||||
|
*
|
||||||
|
* import { assertEnv, ipalEnvRules } from '@intecion/ipal-kit'
|
||||||
|
* assertEnv(ipalEnvRules({ storage: true, turnstile: true }))
|
||||||
|
*
|
||||||
|
* or with hand-written rules:
|
||||||
|
*
|
||||||
|
* assertEnv([
|
||||||
|
* { name: 'DATABASE_URI', description: 'MongoDB connection string' },
|
||||||
|
* { name: 'NEXT_PUBLIC_SERVER_URL', kind: 'url' },
|
||||||
|
* { name: 'NODE_ENV', oneOf: ['development', 'production', 'test'] },
|
||||||
|
* ])
|
||||||
|
*
|
||||||
|
* Runs server-side only (reads process.env) — never import it into a client
|
||||||
|
* component.
|
||||||
|
*/
|
||||||
|
export function assertEnv(rules: EnvRule[], options: AssertEnvOptions = {}): void {
|
||||||
|
const env = options.env ?? process.env
|
||||||
|
const label = options.label ?? '[ipal]'
|
||||||
|
const problems: string[] = []
|
||||||
|
|
||||||
|
for (const rule of rules) {
|
||||||
|
const raw = env[rule.name]
|
||||||
|
const value = typeof raw === 'string' ? raw.trim() : ''
|
||||||
|
const required = rule.required !== false
|
||||||
|
|
||||||
|
if (!value) {
|
||||||
|
if (required) {
|
||||||
|
problems.push(
|
||||||
|
`${rule.name} is required but missing${rule.description ? ` — ${rule.description}` : ''}`,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
continue // optional + absent → nothing to check
|
||||||
|
}
|
||||||
|
|
||||||
|
const err = checkValue(rule, value)
|
||||||
|
if (err) {
|
||||||
|
problems.push(`${err}${rule.description ? ` — ${rule.description}` : ''}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (problems.length === 0) {return}
|
||||||
|
|
||||||
|
const message =
|
||||||
|
`${label} Environment validation failed (${problems.length} ` +
|
||||||
|
`problem${problems.length === 1 ? '' : 's'}):\n` +
|
||||||
|
problems.map((p) => ` • ${p}`).join('\n') +
|
||||||
|
`\nSet these in your environment (Coolify → Environment, or .env) and redeploy.`
|
||||||
|
|
||||||
|
throw new Error(message)
|
||||||
|
}
|
||||||
Vendored
+4
@@ -0,0 +1,4 @@
|
|||||||
|
export { assertEnv } from './assertEnv.js'
|
||||||
|
export type { EnvRule, EnvKind, AssertEnvOptions } from './assertEnv.js'
|
||||||
|
export { ipalEnvRules } from './ipalEnvRules.js'
|
||||||
|
export type { IpalEnvFeatures } from './ipalEnvRules.js'
|
||||||
Vendored
+103
@@ -0,0 +1,103 @@
|
|||||||
|
import type { EnvRule } from './assertEnv.js'
|
||||||
|
|
||||||
|
type TurnstileNames = { secretVar?: string; siteKeyVar?: string }
|
||||||
|
|
||||||
|
export type IpalEnvFeatures = {
|
||||||
|
/** Override the database var. Default 'DATABASE_URI'. */
|
||||||
|
databaseVar?: string
|
||||||
|
/** Microsoft Graph e-mail (graphAdapter). Adds the GRAPH_* vars. */
|
||||||
|
emailGraph?: boolean
|
||||||
|
/** Override the Payload secret var. Default 'PAYLOAD_SECRET'. */
|
||||||
|
secretVar?: string
|
||||||
|
/** Override the site-URL var. Default 'NEXT_PUBLIC_SERVER_URL'. */
|
||||||
|
serverUrlVar?: string
|
||||||
|
/** R2 object storage (buildR2Storage). Adds the R2_* vars. */
|
||||||
|
storage?: boolean
|
||||||
|
/**
|
||||||
|
* Cloudflare Turnstile. true uses the common var names
|
||||||
|
* (NEXT_PUBLIC_TURNSTILE_SITE_KEY + TURNSTILE_SECRET_KEY); pass an object to
|
||||||
|
* override either name if your project differs.
|
||||||
|
*/
|
||||||
|
turnstile?: boolean | TurnstileNames
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The env schema for a standard ipal-kit deploy, assembled from the features the
|
||||||
|
* project actually uses — so a site on local-disk storage isn't forced to set
|
||||||
|
* R2_*, and a site with no forms isn't forced to set Turnstile. Opt-in, not a
|
||||||
|
* fixed required set (A0: the plugin never demands config a project doesn't use).
|
||||||
|
*
|
||||||
|
* Variable names match what the plugin's own modules read (R2_*, GRAPH_*,
|
||||||
|
* NEXT_PUBLIC_SERVER_URL). DATABASE_URI and PAYLOAD_SECRET are Payload-core.
|
||||||
|
* Override any name via the options if your project names them differently.
|
||||||
|
*
|
||||||
|
* assertEnv(ipalEnvRules({ storage: true, emailGraph: true, turnstile: true }))
|
||||||
|
*
|
||||||
|
* Extend with project-specific vars by spreading:
|
||||||
|
*
|
||||||
|
* assertEnv([
|
||||||
|
* ...ipalEnvRules({ storage: true }),
|
||||||
|
* { name: 'MY_API_KEY', description: 'Third-party integration key' },
|
||||||
|
* ])
|
||||||
|
*/
|
||||||
|
export function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] {
|
||||||
|
const {
|
||||||
|
databaseVar = 'DATABASE_URI',
|
||||||
|
emailGraph = false,
|
||||||
|
secretVar = 'PAYLOAD_SECRET',
|
||||||
|
serverUrlVar = 'NEXT_PUBLIC_SERVER_URL',
|
||||||
|
storage = false,
|
||||||
|
turnstile = false,
|
||||||
|
} = features
|
||||||
|
|
||||||
|
const rules: EnvRule[] = [
|
||||||
|
{ name: databaseVar, description: 'Database connection string (e.g. MongoDB URI)' },
|
||||||
|
{ name: secretVar, description: 'Payload secret used to sign tokens' },
|
||||||
|
{
|
||||||
|
name: serverUrlVar,
|
||||||
|
description: 'Public site origin, e.g. https://example.com',
|
||||||
|
kind: 'url',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'NODE_ENV',
|
||||||
|
description: 'Node environment',
|
||||||
|
oneOf: ['development', 'production', 'test'],
|
||||||
|
required: false,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
if (storage) {
|
||||||
|
rules.push(
|
||||||
|
{ name: 'R2_BUCKET', description: 'R2 bucket name' },
|
||||||
|
{ name: 'R2_ACCESS_KEY_ID', description: 'R2 access key id' },
|
||||||
|
{ name: 'R2_SECRET_ACCESS_KEY', description: 'R2 secret access key' },
|
||||||
|
{ name: 'R2_ENDPOINT', description: 'R2 S3 API endpoint URL', kind: 'url' },
|
||||||
|
{ name: 'R2_PUBLIC_URL', description: 'Public base URL media is served from', kind: 'url' },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (emailGraph) {
|
||||||
|
rules.push(
|
||||||
|
{ name: 'GRAPH_TENANT_ID', description: 'Microsoft Graph tenant id' },
|
||||||
|
{ name: 'GRAPH_CLIENT_ID', description: 'Microsoft Graph client id' },
|
||||||
|
{ name: 'GRAPH_CLIENT_SECRET', description: 'Microsoft Graph client secret' },
|
||||||
|
{ name: 'GRAPH_SENDER', description: 'From-address mail is sent as', kind: 'email' },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (turnstile) {
|
||||||
|
const names = typeof turnstile === 'object' ? turnstile : {}
|
||||||
|
rules.push(
|
||||||
|
{
|
||||||
|
name: names.siteKeyVar ?? 'NEXT_PUBLIC_TURNSTILE_SITE_KEY',
|
||||||
|
description: 'Cloudflare Turnstile public site key',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: names.secretVar ?? 'TURNSTILE_SECRET_KEY',
|
||||||
|
description: 'Cloudflare Turnstile secret key',
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return rules
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
/**
|
||||||
|
* A honeypot: a hidden field real users never see or fill, but naive bots do.
|
||||||
|
* A cheap, zero-friction second layer alongside Turnstile — no network call, no
|
||||||
|
* user interaction. Pure functions, usable on client (render the input) and
|
||||||
|
* server (check it in the action).
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Default field name. Looks like a real field a bot would want to fill, but is
|
||||||
|
* not one your form uses. Override per project if you like — just keep the
|
||||||
|
* client and server in sync.
|
||||||
|
*/
|
||||||
|
export const HONEYPOT_FIELD = 'company_url'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Props for the hidden input. Hidden from sight AND from assistive tech and tab
|
||||||
|
* order, so no real user (sighted, screen-reader, or keyboard) ever fills it —
|
||||||
|
* only a bot auto-filling every field.
|
||||||
|
*
|
||||||
|
* <input {...honeypotInputProps()} />
|
||||||
|
* // or with your own name:
|
||||||
|
* <input {...honeypotInputProps('website_2')} />
|
||||||
|
*/
|
||||||
|
export function honeypotInputProps(name: string = HONEYPOT_FIELD) {
|
||||||
|
return {
|
||||||
|
name,
|
||||||
|
type: 'text' as const,
|
||||||
|
'aria-hidden': true,
|
||||||
|
autoComplete: 'off' as const,
|
||||||
|
tabIndex: -1,
|
||||||
|
// Off-screen rather than display:none — some bots skip display:none fields.
|
||||||
|
style: {
|
||||||
|
height: '1px',
|
||||||
|
left: '-9999px',
|
||||||
|
overflow: 'hidden' as const,
|
||||||
|
position: 'absolute' as const,
|
||||||
|
width: '1px',
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* True when the honeypot was filled → treat the submission as spam and drop it
|
||||||
|
* (silently return success so the bot gets no signal). Call it FIRST in your
|
||||||
|
* server action, before submitForm:
|
||||||
|
*
|
||||||
|
* if (isHoneypotTripped(values)) return { success: true } // pretend-accept
|
||||||
|
* // strip it so submitForm doesn't see an unknown field:
|
||||||
|
* const { [HONEYPOT_FIELD]: _hp, ...clean } = values
|
||||||
|
* return submitForm({ ...clean })
|
||||||
|
*/
|
||||||
|
export function isHoneypotTripped(
|
||||||
|
values: Record<string, unknown>,
|
||||||
|
name: string = HONEYPOT_FIELD,
|
||||||
|
): boolean {
|
||||||
|
const v = values[name]
|
||||||
|
return typeof v === 'string' ? v.trim().length > 0 : v != null
|
||||||
|
}
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
// buildFormsPlugin is config-time (safe anywhere). submitForm is server-only
|
// buildFormsPlugin is config-time (safe anywhere). submitForm is server-only
|
||||||
// (Turnstile secret) — never import it from a client component.
|
// (Turnstile secret) — never import it from a client component.
|
||||||
export { buildFormsPlugin } from './formsPluginConfig.js'
|
export { buildFormsPlugin } from './formsPluginConfig.js'
|
||||||
|
// Honeypot anti-spam (pure — client renders the input, server checks it).
|
||||||
|
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './honeypot.js'
|
||||||
export { checkRateLimit } from './rateLimit.js'
|
export { checkRateLimit } from './rateLimit.js'
|
||||||
export type { RateLimitArgs } from './rateLimit.js'
|
export type { RateLimitArgs } from './rateLimit.js'
|
||||||
export { submitForm } from './submitForm.js'
|
export { submitForm } from './submitForm.js'
|
||||||
@@ -8,5 +10,21 @@ export type { SubmitFormArgs, SubmitFormResult } from './submitForm.js'
|
|||||||
export type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption } from './types.js'
|
export type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption } from './types.js'
|
||||||
export { useContactForm } from './useContactForm.js'
|
export { useContactForm } from './useContactForm.js'
|
||||||
export type { ContactFormErrors, ContactFormValues, SubmitAction } from './useContactForm.js'
|
export type { ContactFormErrors, ContactFormValues, SubmitAction } from './useContactForm.js'
|
||||||
|
// Generic form engine (any field set) + the standard contact-form preset.
|
||||||
|
export { useForm } from './useForm.js'
|
||||||
|
export type { FormErrors, FormSubmitAction, Validator } from './useForm.js'
|
||||||
export { validateSubmission } from './validateSubmission.js'
|
export { validateSubmission } from './validateSubmission.js'
|
||||||
export type { FormValidationResult } from './validateSubmission.js'
|
export type { FormValidationResult } from './validateSubmission.js'
|
||||||
|
// Composable validation rules (pure — safe on server or client).
|
||||||
|
export {
|
||||||
|
buildValidator,
|
||||||
|
checked,
|
||||||
|
custom,
|
||||||
|
email,
|
||||||
|
isEmail,
|
||||||
|
maxLength,
|
||||||
|
minLength,
|
||||||
|
pattern,
|
||||||
|
required,
|
||||||
|
} from './validators.js'
|
||||||
|
export type { Rule } from './validators.js'
|
||||||
|
|||||||
@@ -1,10 +1,15 @@
|
|||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { useCallback, useState } from 'react'
|
import { useMemo } from 'react'
|
||||||
|
|
||||||
import type { SubmitFormResult } from './submitForm.js'
|
import { type FormSubmitAction, useForm } from './useForm.js'
|
||||||
|
import { buildValidator, checked, email, minLength, required } from './validators.js'
|
||||||
|
|
||||||
/** Field values the form tracks. Projects add/remove keys freely. */
|
/**
|
||||||
|
* Field values of the STANDARD contact form. This is a preset shape — projects
|
||||||
|
* that need a different field set (or dynamic builder fields) should use
|
||||||
|
* `useForm` directly instead, where the shape is fully open.
|
||||||
|
*/
|
||||||
export type ContactFormValues = {
|
export type ContactFormValues = {
|
||||||
consent: boolean
|
consent: boolean
|
||||||
email: string
|
email: string
|
||||||
@@ -14,22 +19,15 @@ export type ContactFormValues = {
|
|||||||
topic: string
|
topic: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ContactFormErrors = Partial<Record<keyof ContactFormValues, boolean>>
|
export type ContactFormErrors = Partial<Record<keyof ContactFormValues, string>>
|
||||||
|
export type SubmitAction = FormSubmitAction<ContactFormValues>
|
||||||
/**
|
|
||||||
* The project's server action that calls submitForm (server-only, holds the
|
|
||||||
* Turnstile secret). The hook is a client hook, so it can't call submitForm
|
|
||||||
* directly — the project injects its action.
|
|
||||||
*/
|
|
||||||
export type SubmitAction = (
|
|
||||||
values: ContactFormValues,
|
|
||||||
turnstileToken?: string,
|
|
||||||
) => Promise<{ message?: string; success: boolean } | SubmitFormResult>
|
|
||||||
|
|
||||||
type UseContactFormOptions = {
|
type UseContactFormOptions = {
|
||||||
/** Generic error message shown when the action throws. */
|
/** Generic error message shown when the action fails/throws. */
|
||||||
errorFallback?: string
|
errorFallback?: string
|
||||||
initialTopic?: string
|
initialTopic?: string
|
||||||
|
/** Override the per-field error message (shown via `errors.<field>`). */
|
||||||
|
messages?: Partial<Record<keyof ContactFormValues, string>>
|
||||||
/** Minimum message length. Default 10. */
|
/** Minimum message length. Default 10. */
|
||||||
minMessageLength?: number
|
minMessageLength?: number
|
||||||
/** Whether consent is required (project passes true when consentText shown). */
|
/** Whether consent is required (project passes true when consentText shown). */
|
||||||
@@ -41,35 +39,22 @@ type UseContactFormOptions = {
|
|||||||
submitAction: SubmitAction
|
submitAction: SubmitAction
|
||||||
}
|
}
|
||||||
|
|
||||||
const EMAIL_RE = /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/
|
|
||||||
const EMPTY: ContactFormValues = {
|
|
||||||
name: '',
|
|
||||||
consent: false,
|
|
||||||
email: '',
|
|
||||||
message: '',
|
|
||||||
phone: '',
|
|
||||||
topic: '',
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* All contact-form logic (state, validation, Turnstile token, submit, success)
|
* Zero-config preset over `useForm` for the everyday contact form: standard
|
||||||
* WITHOUT any markup — the project owns 100% of the look. Replaces the ~150
|
* fields (name/email/phone/topic/message/consent) and standard rules, wired
|
||||||
* lines of identical logic copied into every project's ContactForm, while the
|
* for you. Markup and styling stay 100% in the project — this only removes the
|
||||||
* project keeps full control over field layout and styling.
|
* duplicated logic.
|
||||||
*
|
*
|
||||||
* const f = useContactForm({ submitAction, requireTurnstile: Boolean(siteKey),
|
* const f = useContactForm({ submitAction, requireTurnstile: Boolean(siteKey),
|
||||||
* requireTopic: topics.length > 0, requireConsent: Boolean(consentText) })
|
* requireTopic: topics.length > 0, requireConsent: Boolean(consentText) })
|
||||||
* // in JSX — your own fields/classes:
|
*
|
||||||
* <input value={f.values.name} onChange={(e) => f.setField('name', e.target.value)}
|
* Need custom or dynamic fields? Drop the preset and call `useForm` + validators.
|
||||||
* className={f.errors.name ? 'border-red-500' : '…'} />
|
|
||||||
* <Turnstile siteKey={siteKey} onToken={f.setTurnstileToken} />
|
|
||||||
* <form onSubmit={f.handleSubmit}>…</form>
|
|
||||||
* {f.isSuccess && <YourSuccessPanel onReset={f.reset} />}
|
|
||||||
*/
|
*/
|
||||||
export function useContactForm(options: UseContactFormOptions) {
|
export function useContactForm(options: UseContactFormOptions) {
|
||||||
const {
|
const {
|
||||||
errorFallback = 'Something went wrong. Please try again.',
|
errorFallback,
|
||||||
initialTopic = '',
|
initialTopic = '',
|
||||||
|
messages,
|
||||||
minMessageLength = 10,
|
minMessageLength = 10,
|
||||||
requireConsent = false,
|
requireConsent = false,
|
||||||
requireTopic = false,
|
requireTopic = false,
|
||||||
@@ -77,76 +62,30 @@ export function useContactForm(options: UseContactFormOptions) {
|
|||||||
submitAction,
|
submitAction,
|
||||||
} = options
|
} = options
|
||||||
|
|
||||||
const [values, setValues] = useState<ContactFormValues>({ ...EMPTY, topic: initialTopic })
|
const validate = useMemo(
|
||||||
const [errors, setErrors] = useState<ContactFormErrors>({})
|
() =>
|
||||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
buildValidator<ContactFormValues>({
|
||||||
const [isSuccess, setIsSuccess] = useState(false)
|
name: [required(messages?.name)],
|
||||||
const [errorMessage, setErrorMessage] = useState<null | string>(null)
|
email: [required(messages?.email), email(messages?.email)],
|
||||||
const [turnstileToken, setTurnstileToken] = useState<null | string>(null)
|
...(requireTopic ? { topic: [required(messages?.topic)] } : {}),
|
||||||
|
message: [required(messages?.message), minLength(minMessageLength, messages?.message)],
|
||||||
const setField = useCallback(
|
...(requireConsent ? { consent: [checked(messages?.consent)] } : {}),
|
||||||
<K extends keyof ContactFormValues>(key: K, value: ContactFormValues[K]) => {
|
}),
|
||||||
setValues((prev) => ({ ...prev, [key]: value }))
|
[requireTopic, requireConsent, minMessageLength, messages],
|
||||||
},
|
|
||||||
[],
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const validate = useCallback((): boolean => {
|
return useForm<ContactFormValues>({
|
||||||
const errs: ContactFormErrors = {}
|
errorFallback,
|
||||||
if (!values.name.trim()) {errs.name = true}
|
initialValues: {
|
||||||
if (!values.email.trim() || !EMAIL_RE.test(values.email)) {errs.email = true}
|
name: '',
|
||||||
if (requireTopic && !values.topic) {errs.topic = true}
|
consent: false,
|
||||||
if (!values.message.trim() || values.message.length < minMessageLength) {errs.message = true}
|
email: '',
|
||||||
if (requireConsent && !values.consent) {errs.consent = true}
|
message: '',
|
||||||
setErrors(errs)
|
phone: '',
|
||||||
return Object.keys(errs).length === 0
|
topic: initialTopic,
|
||||||
}, [values, requireTopic, requireConsent, minMessageLength])
|
|
||||||
|
|
||||||
const handleSubmit = useCallback(
|
|
||||||
async (e: { preventDefault: () => void }) => {
|
|
||||||
e.preventDefault()
|
|
||||||
setErrorMessage(null)
|
|
||||||
if (!validate()) {return}
|
|
||||||
if (requireTurnstile && !turnstileToken) {
|
|
||||||
setErrorMessage(errorFallback)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
setIsSubmitting(true)
|
|
||||||
try {
|
|
||||||
const result = await submitAction(values, turnstileToken ?? undefined)
|
|
||||||
if (result.success) {
|
|
||||||
setIsSuccess(true)
|
|
||||||
setTurnstileToken(null)
|
|
||||||
} else {
|
|
||||||
setErrorMessage(('message' in result && result.message) || errorFallback)
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
setErrorMessage(err instanceof Error ? err.message : errorFallback)
|
|
||||||
} finally {
|
|
||||||
setIsSubmitting(false)
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
[validate, requireTurnstile, turnstileToken, submitAction, values, errorFallback],
|
requireTurnstile,
|
||||||
)
|
submitAction,
|
||||||
|
validate,
|
||||||
const reset = useCallback(() => {
|
})
|
||||||
setValues({ ...EMPTY, topic: initialTopic })
|
|
||||||
setErrors({})
|
|
||||||
setIsSuccess(false)
|
|
||||||
setErrorMessage(null)
|
|
||||||
setTurnstileToken(null)
|
|
||||||
}, [initialTopic])
|
|
||||||
|
|
||||||
return {
|
|
||||||
errorMessage,
|
|
||||||
errors,
|
|
||||||
handleSubmit,
|
|
||||||
isSubmitting,
|
|
||||||
isSuccess,
|
|
||||||
reset,
|
|
||||||
setField,
|
|
||||||
setTurnstileToken,
|
|
||||||
turnstileToken,
|
|
||||||
values,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,172 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useState, useCallback, useRef, useMemo } from 'react'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Error map: a field key → its error message. A field is "in error" iff it has
|
||||||
|
* a key here, so `errors.email` is both the truthy flag (for a red border) AND
|
||||||
|
* the message (to display). Empty object = valid.
|
||||||
|
*/
|
||||||
|
export type FormErrors<T> = Partial<Record<keyof T, string>>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The project's server action that calls submitForm (server-only, holds the
|
||||||
|
* Turnstile secret). This hook is a client hook, so it can't call submitForm
|
||||||
|
* directly — the project injects its action. The result only needs `success`
|
||||||
|
* plus an optional `message`; richer shapes (SubmitFormResult) satisfy it.
|
||||||
|
*/
|
||||||
|
export type FormSubmitAction<T> = (
|
||||||
|
values: T,
|
||||||
|
turnstileToken?: string,
|
||||||
|
) => Promise<{ success: boolean; message?: string }>
|
||||||
|
|
||||||
|
/** Turns the current values into an error map. Empty map = valid. */
|
||||||
|
export type Validator<T> = (values: T) => FormErrors<T>
|
||||||
|
|
||||||
|
type UseFormOptions<T extends Record<string, unknown>> = {
|
||||||
|
/** Defines the field set AND the reset state. Any shape you like. */
|
||||||
|
initialValues: T
|
||||||
|
submitAction: FormSubmitAction<T>
|
||||||
|
/** Project-owned validation. Compose one with `buildValidator` + rules, or write your own. */
|
||||||
|
validate?: Validator<T>
|
||||||
|
/** Require a Turnstile token before submit (when the widget is shown). */
|
||||||
|
requireTurnstile?: boolean
|
||||||
|
/** Generic error message shown when the action fails/throws with no message. */
|
||||||
|
errorFallback?: string
|
||||||
|
/** Clear a field's error as soon as the user edits it. Default true. */
|
||||||
|
clearErrorOnChange?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fully generic form engine: state, validation, Turnstile token, submit,
|
||||||
|
* success/error — WITHOUT any markup. The project owns 100% of the look AND
|
||||||
|
* the field set: there is no baked-in shape here. Replaces the identical
|
||||||
|
* ~150 lines of form plumbing copied into every project.
|
||||||
|
*
|
||||||
|
* The field set comes from `initialValues`; the rules come from `validate`
|
||||||
|
* (so dynamic/builder-driven forms just build both at runtime). For the
|
||||||
|
* everyday contact form use the `useContactForm` preset instead — it wires
|
||||||
|
* the standard fields and rules for you.
|
||||||
|
*
|
||||||
|
* const f = useForm({
|
||||||
|
* initialValues: { email: '', message: '' },
|
||||||
|
* submitAction, // your server action
|
||||||
|
* validate: buildValidator({ email: [required(), email()], message: [required()] }),
|
||||||
|
* requireTurnstile: Boolean(siteKey),
|
||||||
|
* })
|
||||||
|
* <input value={f.values.email}
|
||||||
|
* onChange={(e) => f.setField('email', e.target.value)}
|
||||||
|
* className={f.errors.email ? 'border-red-500' : '…'} />
|
||||||
|
* <form onSubmit={f.handleSubmit}>…</form>
|
||||||
|
*/
|
||||||
|
export function useForm<T extends Record<string, unknown>>(options: UseFormOptions<T>) {
|
||||||
|
const {
|
||||||
|
initialValues,
|
||||||
|
submitAction,
|
||||||
|
validate,
|
||||||
|
requireTurnstile = false,
|
||||||
|
errorFallback = 'Something went wrong. Please try again.',
|
||||||
|
clearErrorOnChange = true,
|
||||||
|
} = options
|
||||||
|
|
||||||
|
// Freeze the initial snapshot so `reset` is stable even though callers pass a
|
||||||
|
// fresh object literal every render.
|
||||||
|
const initialRef = useRef(initialValues)
|
||||||
|
|
||||||
|
const [values, setValues] = useState<T>(initialRef.current)
|
||||||
|
const [errors, setErrors] = useState<FormErrors<T>>({})
|
||||||
|
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||||
|
const [isSuccess, setIsSuccess] = useState(false)
|
||||||
|
const [errorMessage, setErrorMessage] = useState<string | null>(null)
|
||||||
|
const [turnstileToken, setTurnstileToken] = useState<string | null>(null)
|
||||||
|
|
||||||
|
const setField = useCallback(
|
||||||
|
<K extends keyof T>(key: K, value: T[K]) => {
|
||||||
|
setValues((prev) => ({ ...prev, [key]: value }))
|
||||||
|
if (clearErrorOnChange) {
|
||||||
|
setErrors((prev) => {
|
||||||
|
if (!prev[key]) return prev
|
||||||
|
const next = { ...prev }
|
||||||
|
delete next[key]
|
||||||
|
return next
|
||||||
|
})
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[clearErrorOnChange],
|
||||||
|
)
|
||||||
|
|
||||||
|
// Validate against the LATEST values via a ref, so handleSubmit stays stable
|
||||||
|
// and never reads a stale snapshot.
|
||||||
|
const valuesRef = useRef(values)
|
||||||
|
valuesRef.current = values
|
||||||
|
const validateRef = useRef(validate)
|
||||||
|
validateRef.current = validate
|
||||||
|
|
||||||
|
const handleSubmit = useCallback(
|
||||||
|
async (e?: { preventDefault?: () => void }) => {
|
||||||
|
e?.preventDefault?.()
|
||||||
|
setErrorMessage(null)
|
||||||
|
|
||||||
|
const errs = validateRef.current ? validateRef.current(valuesRef.current) : {}
|
||||||
|
setErrors(errs)
|
||||||
|
if (Object.keys(errs).length > 0) return
|
||||||
|
|
||||||
|
if (requireTurnstile && !turnstileToken) {
|
||||||
|
setErrorMessage(errorFallback)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
setIsSubmitting(true)
|
||||||
|
try {
|
||||||
|
const result = await submitAction(valuesRef.current, turnstileToken ?? undefined)
|
||||||
|
if (result.success) {
|
||||||
|
setIsSuccess(true)
|
||||||
|
setTurnstileToken(null)
|
||||||
|
} else {
|
||||||
|
setErrorMessage(result.message || errorFallback)
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
setErrorMessage(err instanceof Error ? err.message : errorFallback)
|
||||||
|
} finally {
|
||||||
|
setIsSubmitting(false)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[requireTurnstile, turnstileToken, submitAction, errorFallback],
|
||||||
|
)
|
||||||
|
|
||||||
|
const reset = useCallback(() => {
|
||||||
|
setValues(initialRef.current)
|
||||||
|
setErrors({})
|
||||||
|
setIsSuccess(false)
|
||||||
|
setErrorMessage(null)
|
||||||
|
setTurnstileToken(null)
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
return useMemo(
|
||||||
|
() => ({
|
||||||
|
values,
|
||||||
|
errors,
|
||||||
|
isSubmitting,
|
||||||
|
isSuccess,
|
||||||
|
errorMessage,
|
||||||
|
turnstileToken,
|
||||||
|
setField,
|
||||||
|
setValues,
|
||||||
|
setErrors,
|
||||||
|
setTurnstileToken,
|
||||||
|
handleSubmit,
|
||||||
|
reset,
|
||||||
|
}),
|
||||||
|
[
|
||||||
|
values,
|
||||||
|
errors,
|
||||||
|
isSubmitting,
|
||||||
|
isSuccess,
|
||||||
|
errorMessage,
|
||||||
|
turnstileToken,
|
||||||
|
setField,
|
||||||
|
handleSubmit,
|
||||||
|
reset,
|
||||||
|
],
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
import type { FormErrors, Validator } from './useForm.js'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Composable validation rules + a builder that turns a per-field schema into a
|
||||||
|
* `Validator<T>`. These are the bits that actually repeat across projects
|
||||||
|
* (required / email / min-length / checkbox-must-be-true); the field SET and
|
||||||
|
* the MARKUP stay in the project.
|
||||||
|
*
|
||||||
|
* Pure functions, no 'use client' — usable both in the client `useForm` hook
|
||||||
|
* and server-side (e.g. re-validating inside a server action).
|
||||||
|
*
|
||||||
|
* const validate = buildValidator<MyValues>({
|
||||||
|
* email: [required(), email()],
|
||||||
|
* message: [required(), minLength(10)],
|
||||||
|
* consent: [checked()],
|
||||||
|
* })
|
||||||
|
*
|
||||||
|
* Dynamic / builder-driven forms build the schema at runtime:
|
||||||
|
*
|
||||||
|
* const schema = Object.fromEntries(
|
||||||
|
* fields.map((f) => [f.name, f.required ? [required()] : []]),
|
||||||
|
* )
|
||||||
|
* const validate = buildValidator(schema)
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** A rule returns `true` when the value is OK, or an error message string. */
|
||||||
|
export type Rule = (value: unknown, values: Record<string, unknown>) => true | string
|
||||||
|
|
||||||
|
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
||||||
|
|
||||||
|
/** Standalone e-mail check, handy outside the rule system too. */
|
||||||
|
export const isEmail = (v: unknown): boolean => typeof v === 'string' && EMAIL_RE.test(v.trim())
|
||||||
|
|
||||||
|
/** Non-empty string, non-null, and (for checkboxes) not `false`. */
|
||||||
|
export const required =
|
||||||
|
(msg = 'required'): Rule =>
|
||||||
|
(v) => {
|
||||||
|
if (v == null) return msg
|
||||||
|
if (typeof v === 'string' && !v.trim()) return msg
|
||||||
|
if (v === false) return msg
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
export const email =
|
||||||
|
(msg = 'invalid email'): Rule =>
|
||||||
|
(v) =>
|
||||||
|
isEmail(v) ? true : msg
|
||||||
|
|
||||||
|
export const minLength =
|
||||||
|
(n: number, msg?: string): Rule =>
|
||||||
|
(v) =>
|
||||||
|
typeof v === 'string' && v.trim().length >= n ? true : (msg ?? `min ${n} chars`)
|
||||||
|
|
||||||
|
export const maxLength =
|
||||||
|
(n: number, msg?: string): Rule =>
|
||||||
|
(v) =>
|
||||||
|
typeof v === 'string' && v.trim().length <= n ? true : (msg ?? `max ${n} chars`)
|
||||||
|
|
||||||
|
/** Checkbox must be ticked (true). */
|
||||||
|
export const checked =
|
||||||
|
(msg = 'required'): Rule =>
|
||||||
|
(v) =>
|
||||||
|
v === true ? true : msg
|
||||||
|
|
||||||
|
/** Value must match a regex (ignored when empty — pair with `required` to force). */
|
||||||
|
export const pattern =
|
||||||
|
(re: RegExp, msg = 'invalid format'): Rule =>
|
||||||
|
(v) =>
|
||||||
|
typeof v !== 'string' || v.trim() === '' || re.test(v.trim()) ? true : msg
|
||||||
|
|
||||||
|
/** Escape hatch: any predicate → rule. */
|
||||||
|
export const custom =
|
||||||
|
(test: (value: unknown, values: Record<string, unknown>) => boolean, msg: string): Rule =>
|
||||||
|
(v, values) =>
|
||||||
|
test(v, values) ? true : msg
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compose a `Validator<T>` from per-field rule lists. First failing rule for a
|
||||||
|
* field wins. Fields with no rules (or an empty list) are skipped.
|
||||||
|
*/
|
||||||
|
export function buildValidator<T extends Record<string, unknown>>(
|
||||||
|
schema: Partial<Record<keyof T, Rule[]>>,
|
||||||
|
): Validator<T> {
|
||||||
|
return (values) => {
|
||||||
|
const errs: FormErrors<T> = {}
|
||||||
|
const all = values as Record<string, unknown>
|
||||||
|
for (const key in schema) {
|
||||||
|
const rules = schema[key as keyof T]
|
||||||
|
if (!rules || rules.length === 0) continue
|
||||||
|
for (const rule of rules) {
|
||||||
|
const res = rule(all[key], all)
|
||||||
|
if (res !== true) {
|
||||||
|
errs[key as keyof T] = res
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return errs
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
import type { BasePayload } from 'payload'
|
||||||
|
|
||||||
|
type CreateHealthRouteArgs = {
|
||||||
|
/**
|
||||||
|
* Collection to ping for a real DB round-trip. Default 'pages'. Pick any
|
||||||
|
* collection that always exists in the project.
|
||||||
|
*/
|
||||||
|
collection?: string
|
||||||
|
/**
|
||||||
|
* Optional extra checks merged into the body (e.g. a cache or queue ping).
|
||||||
|
* Throwing marks the whole healthcheck unhealthy.
|
||||||
|
*/
|
||||||
|
extra?: () => Promise<Record<string, unknown>>
|
||||||
|
/** Same cached accessor the rest of the app uses. */
|
||||||
|
getCachedPayload: () => Promise<BasePayload>
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A liveness/readiness route for Coolify/Docker healthchecks and uptime
|
||||||
|
* monitors. Does a real DB round-trip (not just "process is up") and returns
|
||||||
|
* 200 when reachable, 503 when not — so an orchestrator can restart or hold
|
||||||
|
* traffic off a container whose database is down.
|
||||||
|
*
|
||||||
|
* // app/api/health/route.ts
|
||||||
|
* import { createHealthRoute } from '@intecion/ipal-kit'
|
||||||
|
* import { getCachedPayload } from '@/lib/content'
|
||||||
|
* export const dynamic = 'force-dynamic' // never prerender/cache a healthcheck
|
||||||
|
* export const GET = createHealthRoute({ getCachedPayload })
|
||||||
|
*
|
||||||
|
* Point Coolify's healthcheck at /api/health. Uses the global `Response`
|
||||||
|
* (standard in Next route handlers) — no next/server import, peer-dep clean.
|
||||||
|
*/
|
||||||
|
export function createHealthRoute(args: CreateHealthRouteArgs): () => Promise<Response> {
|
||||||
|
const { collection = 'pages', extra, getCachedPayload } = args
|
||||||
|
|
||||||
|
return async () => {
|
||||||
|
const startedAt = Date.now()
|
||||||
|
try {
|
||||||
|
const payload = await getCachedPayload()
|
||||||
|
// Cheapest real round-trip: ask for at most one row, no population.
|
||||||
|
await payload.find({
|
||||||
|
collection: collection as never,
|
||||||
|
depth: 0,
|
||||||
|
limit: 1,
|
||||||
|
pagination: false,
|
||||||
|
})
|
||||||
|
|
||||||
|
const extraData = extra ? await extra() : {}
|
||||||
|
const body = {
|
||||||
|
db: 'up',
|
||||||
|
status: 'ok',
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
tookMs: Date.now() - startedAt,
|
||||||
|
...extraData,
|
||||||
|
}
|
||||||
|
return new Response(JSON.stringify(body), {
|
||||||
|
headers: { 'cache-control': 'no-store', 'content-type': 'application/json' },
|
||||||
|
status: 200,
|
||||||
|
})
|
||||||
|
} catch (err) {
|
||||||
|
const body = {
|
||||||
|
db: 'down',
|
||||||
|
error: err instanceof Error ? err.message : 'unknown',
|
||||||
|
status: 'error',
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
tookMs: Date.now() - startedAt,
|
||||||
|
}
|
||||||
|
return new Response(JSON.stringify(body), {
|
||||||
|
headers: { 'cache-control': 'no-store', 'content-type': 'application/json' },
|
||||||
|
status: 503,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
export { createHealthRoute } from './createHealthRoute.js'
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
import type { BasePayload, CollectionAfterChangeHook } from 'payload'
|
||||||
|
|
||||||
|
import type { I18nConfig } from '../i18n/index.js'
|
||||||
|
|
||||||
|
import { getLocaleCodes } from '../i18n/index.js'
|
||||||
|
|
||||||
|
type Row = { blockType?: string; id?: number | string } & Record<string, unknown>
|
||||||
|
|
||||||
|
type BuildCrossLocaleFieldSyncArgs = {
|
||||||
|
/**
|
||||||
|
* The localized `blocks`/`array` field whose rows hold the shared fields.
|
||||||
|
* Default 'layout'.
|
||||||
|
*/
|
||||||
|
arrayField?: string
|
||||||
|
/**
|
||||||
|
* Slug of the collection this hook is attached to — needed to re-read and
|
||||||
|
* update the other locales. (A hook can't discover its own collection.)
|
||||||
|
*/
|
||||||
|
collection: string
|
||||||
|
config: I18nConfig
|
||||||
|
/**
|
||||||
|
* Fields WITHIN each row that are conceptually language-independent (a shared
|
||||||
|
* media reference, an icon, a color) and should be propagated from the edited
|
||||||
|
* locale to every other locale — e.g. ['image'] or ['image', 'backgroundImage'].
|
||||||
|
*
|
||||||
|
* Only fields with a value in the source are copied: clearing a field in one
|
||||||
|
* language does NOT wipe it in the others (conservative, matches the hand-
|
||||||
|
* rolled hooks this replaces). Text and other truly-localized fields are never
|
||||||
|
* touched.
|
||||||
|
*/
|
||||||
|
fields: string[]
|
||||||
|
/**
|
||||||
|
* Flag name set on `req` to break the update→afterChange→update loop.
|
||||||
|
* Default '_ipalSyncingCrossLocale'. Override only if two syncs run on one
|
||||||
|
* collection and must not share a guard.
|
||||||
|
*/
|
||||||
|
guardFlag?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Relationship/upload values arrive as an id or a populated object — normalize to the id. */
|
||||||
|
function toId(value: unknown): null | number | string {
|
||||||
|
if (value == null) {return null}
|
||||||
|
if (typeof value === 'string' || typeof value === 'number') {return value}
|
||||||
|
if (typeof value === 'object' && 'id' in (value as Record<string, unknown>)) {
|
||||||
|
const id = (value as Record<string, unknown>).id
|
||||||
|
return typeof id === 'string' || typeof id === 'number' ? id : null
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Propagates language-independent fields (images, icons…) that live INSIDE a
|
||||||
|
* localized `blocks`/`array` field from the just-edited locale to every other
|
||||||
|
* configured locale.
|
||||||
|
*
|
||||||
|
* Why this exists: Payload localizes an array/blocks field as a whole, so there
|
||||||
|
* is no way to mark a single sub-field (the image) as non-localized — each
|
||||||
|
* locale keeps its own copy of every row, image included. Without this, an
|
||||||
|
* editor who picks images in Polish has to re-pick the SAME images in English,
|
||||||
|
* German, … This hook does that copy automatically.
|
||||||
|
*
|
||||||
|
* A0-safe: the locale list comes from `config`, never a hard-coded array — add
|
||||||
|
* a language in the panel and it's covered with no code change. (The hand-rolled
|
||||||
|
* versions this replaces carried a literal `['pl','en',...]` that silently
|
||||||
|
* dropped any locale not listed.)
|
||||||
|
*
|
||||||
|
* Row matching: by Payload row `id` when the same id exists in both locales
|
||||||
|
* (robust to reordering and to several blocks of the same type); otherwise it
|
||||||
|
* falls back to the positional index, but only when the block types at that
|
||||||
|
* index match — so it never writes an image into a block of a different type.
|
||||||
|
*
|
||||||
|
* // collections/Pages.ts
|
||||||
|
* import { buildCrossLocaleFieldSync } from '@intecion/ipal-kit'
|
||||||
|
* hooks: {
|
||||||
|
* afterChange: [
|
||||||
|
* buildCrossLocaleFieldSync({ config: i18nConfig, collection: 'pages', fields: ['image'] }),
|
||||||
|
* ],
|
||||||
|
* }
|
||||||
|
*/
|
||||||
|
export function buildCrossLocaleFieldSync(
|
||||||
|
args: BuildCrossLocaleFieldSyncArgs,
|
||||||
|
): CollectionAfterChangeHook {
|
||||||
|
const {
|
||||||
|
arrayField = 'layout',
|
||||||
|
collection,
|
||||||
|
config,
|
||||||
|
fields,
|
||||||
|
guardFlag = '_ipalSyncingCrossLocale',
|
||||||
|
} = args
|
||||||
|
|
||||||
|
return async ({ doc, req }) => {
|
||||||
|
const reqAny = req as unknown as Record<string, unknown>
|
||||||
|
// Re-entry guard: our own payload.update() below re-fires afterChange.
|
||||||
|
if (reqAny[guardFlag] || !doc?.id) {return doc}
|
||||||
|
|
||||||
|
const sourceRows = (doc as Record<string, unknown>)[arrayField]
|
||||||
|
if (!Array.isArray(sourceRows) || sourceRows.length === 0) {return doc}
|
||||||
|
|
||||||
|
// Source locale = the locale being written. Fall back to the configured
|
||||||
|
// default rather than a hard-coded 'pl' when req.locale is absent.
|
||||||
|
const sourceLocale = typeof req.locale === 'string' ? req.locale : config.defaultLocale
|
||||||
|
const otherLocales = getLocaleCodes(config).filter((l) => l !== sourceLocale)
|
||||||
|
if (otherLocales.length === 0) {return doc} // single-locale site: nothing to sync
|
||||||
|
|
||||||
|
const payload = req.payload
|
||||||
|
|
||||||
|
reqAny[guardFlag] = true
|
||||||
|
try {
|
||||||
|
for (const locale of otherLocales) {
|
||||||
|
let targetDoc: Record<string, unknown>
|
||||||
|
try {
|
||||||
|
targetDoc = (await payload.findByID({
|
||||||
|
id: doc.id as never,
|
||||||
|
collection: collection as never,
|
||||||
|
depth: 0,
|
||||||
|
locale: locale as never,
|
||||||
|
})) as Record<string, unknown>
|
||||||
|
} catch {
|
||||||
|
continue // locale not yet created for this doc — nothing to sync into
|
||||||
|
}
|
||||||
|
|
||||||
|
const targetRows = targetDoc[arrayField]
|
||||||
|
if (!Array.isArray(targetRows) || targetRows.length === 0) {continue}
|
||||||
|
|
||||||
|
// id → row index, for robust matching across locales.
|
||||||
|
const byId = new Map<number | string, number>()
|
||||||
|
;(targetRows as Row[]).forEach((row, i) => {
|
||||||
|
if (row?.id != null) {byId.set(row.id, i)}
|
||||||
|
})
|
||||||
|
|
||||||
|
let changed = false
|
||||||
|
|
||||||
|
;(sourceRows as Row[]).forEach((sourceRow, idx) => {
|
||||||
|
if (!sourceRow) {return}
|
||||||
|
|
||||||
|
// Match by id first; else positional index, but only if block types agree.
|
||||||
|
let targetRow: Row | undefined
|
||||||
|
if (sourceRow.id != null && byId.has(sourceRow.id)) {
|
||||||
|
targetRow = (targetRows as Row[])[byId.get(sourceRow.id)!]
|
||||||
|
} else {
|
||||||
|
const candidate = (targetRows as Row[])[idx]
|
||||||
|
if (candidate && candidate.blockType === sourceRow.blockType) {targetRow = candidate}
|
||||||
|
}
|
||||||
|
if (!targetRow) {return}
|
||||||
|
|
||||||
|
for (const field of fields) {
|
||||||
|
const sourceId = toId(sourceRow[field])
|
||||||
|
if (sourceId == null) {continue} // don't propagate a cleared field
|
||||||
|
if (toId(targetRow[field]) !== sourceId) {
|
||||||
|
targetRow[field] = sourceId
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
if (changed) {
|
||||||
|
await payload.update({
|
||||||
|
id: doc.id as never,
|
||||||
|
collection: collection as never,
|
||||||
|
data: { [arrayField]: targetRows } as never,
|
||||||
|
locale: locale as never,
|
||||||
|
req,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
payload.logger?.error?.({ err, msg: `[ipal] cross-locale ${arrayField} sync failed` })
|
||||||
|
} finally {
|
||||||
|
reqAny[guardFlag] = false
|
||||||
|
}
|
||||||
|
|
||||||
|
return doc
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
// żeby był jeden katalog "wszystkie hooki pluginu"). Źródło prawdy to ich moduły.
|
// żeby był jeden katalog "wszystkie hooki pluginu"). Źródło prawdy to ich moduły.
|
||||||
export { normalizeFilenameHook } from '../media/index.js'
|
export { normalizeFilenameHook } from '../media/index.js'
|
||||||
export { buildAutoFillMetaHook, validateFaviconField } from '../seo/index.js'
|
export { buildAutoFillMetaHook, validateFaviconField } from '../seo/index.js'
|
||||||
|
export { buildCrossLocaleFieldSync } from './buildCrossLocaleFieldSync.js'
|
||||||
export { buildRevalidateHook } from './buildRevalidateHook.js'
|
export { buildRevalidateHook } from './buildRevalidateHook.js'
|
||||||
export { buildPreventDeleteSystemPage } from './preventDeleteSystemPage.js'
|
export { buildPreventDeleteSystemPage } from './preventDeleteSystemPage.js'
|
||||||
export { setPublishedAtHook } from './setPublishedAt.js'
|
export { setPublishedAtHook } from './setPublishedAt.js'
|
||||||
|
|||||||
@@ -39,6 +39,15 @@ type SettingsShape = {
|
|||||||
* import { getCachedPayload } from '@/lib/content'
|
* import { getCachedPayload } from '@/lib/content'
|
||||||
* import { i18nConfig } from '@/i18n.config'
|
* import { i18nConfig } from '@/i18n.config'
|
||||||
* export default createManifestHandler({ getCachedPayload, config: i18nConfig })
|
* export default createManifestHandler({ getCachedPayload, config: i18nConfig })
|
||||||
|
*
|
||||||
|
* NOTE on Docker/CI builds: the whole DB access is wrapped in try/catch, so a
|
||||||
|
* `next build` with no reachable database (the usual Coolify/Docker case) gets
|
||||||
|
* a minimal valid manifest instead of a crash — same contract as
|
||||||
|
* generateStaticParams and the sitemap handler. Projects should still mark the
|
||||||
|
* route dynamic so Next doesn't prerender it at build time:
|
||||||
|
*
|
||||||
|
* // app/manifest.ts
|
||||||
|
* export const dynamic = 'force-dynamic'
|
||||||
*/
|
*/
|
||||||
export function createManifestHandler(opts: {
|
export function createManifestHandler(opts: {
|
||||||
config: I18nConfig
|
config: I18nConfig
|
||||||
@@ -47,18 +56,35 @@ export function createManifestHandler(opts: {
|
|||||||
}): () => Promise<Manifest> {
|
}): () => Promise<Manifest> {
|
||||||
return async () => {
|
return async () => {
|
||||||
const defaultLocale = getDefaultLocale(opts.config)
|
const defaultLocale = getDefaultLocale(opts.config)
|
||||||
const payload = await opts.getCachedPayload()
|
|
||||||
const settings = (await payload
|
|
||||||
.findGlobal({
|
|
||||||
slug: (opts.settingsSlug ?? 'site-settings') as never,
|
|
||||||
depth: 1,
|
|
||||||
locale: defaultLocale as never,
|
|
||||||
})
|
|
||||||
.catch(() => null)) as null | SettingsShape
|
|
||||||
|
|
||||||
const start_url = `/${defaultLocale}`
|
const start_url = `/${defaultLocale}`
|
||||||
|
|
||||||
|
// Minimal, always-valid manifest. Used both when SiteSettings is empty and
|
||||||
|
// when the database is unreachable during a build.
|
||||||
|
const fallback: Manifest = { display: 'standalone', icons: [], start_url }
|
||||||
|
|
||||||
|
let settings: null | SettingsShape
|
||||||
|
try {
|
||||||
|
// getCachedPayload() ITSELF throws when the DB can't be reached (e.g.
|
||||||
|
// `getaddrinfo ENOTFOUND` during `docker build`), BEFORE findGlobal runs
|
||||||
|
// — so the whole thing, not just the query, must sit inside try/catch.
|
||||||
|
const payload = await opts.getCachedPayload()
|
||||||
|
settings = (await payload
|
||||||
|
.findGlobal({
|
||||||
|
slug: (opts.settingsSlug ?? 'site-settings') as never,
|
||||||
|
depth: 1,
|
||||||
|
locale: defaultLocale as never,
|
||||||
|
})
|
||||||
|
.catch(() => null)) as null | SettingsShape
|
||||||
|
} catch (err) {
|
||||||
|
console.warn(
|
||||||
|
'[ipal] createManifestHandler: database not reachable during build (Docker/CI) — returning minimal manifest; it fills in at runtime:',
|
||||||
|
err,
|
||||||
|
)
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
|
||||||
if (!settings) {
|
if (!settings) {
|
||||||
return { display: 'standalone', icons: [], start_url }
|
return fallback
|
||||||
}
|
}
|
||||||
|
|
||||||
const iconSource = settings.favicon ?? settings.logo
|
const iconSource = settings.favicon ?? settings.logo
|
||||||
|
|||||||
@@ -0,0 +1,95 @@
|
|||||||
|
import type { CheckboxField, Field, FieldHook } from 'payload'
|
||||||
|
|
||||||
|
type BuildNoindexFieldArgs = {
|
||||||
|
/** Help text under the checkbox. */
|
||||||
|
description?: string
|
||||||
|
/** Sidebar label. Default 'Wyklucz z indeksowania (noindex)'. */
|
||||||
|
label?: string
|
||||||
|
/**
|
||||||
|
* Dotted path, inside the document, that the SEO read path (metadata +
|
||||||
|
* sitemap) consumes. Default 'meta.noindex' — the plugin-seo `meta` group.
|
||||||
|
* The checkbox value is mirrored here on every save, so editors toggle one
|
||||||
|
* friendly switch and the machinery reads a stable location.
|
||||||
|
*/
|
||||||
|
metaPath?: string
|
||||||
|
/** Field name for the editor-facing checkbox. Default 'noindex'. */
|
||||||
|
name?: string
|
||||||
|
/** Extend/override the generated checkbox (position, access, etc.). */
|
||||||
|
overrides?: Partial<CheckboxField>
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Read a dotted path (e.g. 'meta.noindex') off a loosely-typed object. */
|
||||||
|
function readPath(obj: null | Record<string, unknown> | undefined, path: string[]): unknown {
|
||||||
|
let cur: unknown = obj
|
||||||
|
for (const key of path) {
|
||||||
|
if (cur == null || typeof cur !== 'object') {return undefined}
|
||||||
|
cur = (cur as Record<string, unknown>)[key]
|
||||||
|
}
|
||||||
|
return cur
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Write a dotted path, creating intermediate objects as needed. */
|
||||||
|
function writePath(obj: Record<string, unknown>, path: string[], value: unknown): void {
|
||||||
|
let cur: Record<string, unknown> = obj
|
||||||
|
for (let i = 0; i < path.length - 1; i++) {
|
||||||
|
const key = path[i]
|
||||||
|
const next = cur[key]
|
||||||
|
if (next == null || typeof next !== 'object') {cur[key] = {}}
|
||||||
|
cur = cur[key] as Record<string, unknown>
|
||||||
|
}
|
||||||
|
cur[path[path.length - 1]] = value
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A sidebar `noindex` checkbox that mirrors into `meta.noindex` (what the
|
||||||
|
* sitemap and metadata generators actually read). Replaces the hand-rolled
|
||||||
|
* checkbox + `beforeChange` hook with its `(data as any).meta.noindex = …`
|
||||||
|
* glue copied into every project — no `any`, one source of truth for editors,
|
||||||
|
* one stable read location for the engine.
|
||||||
|
*
|
||||||
|
* Idempotent and order-independent: if either the checkbox OR an existing
|
||||||
|
* `meta.noindex` is set, the page ends up noindex; the two can't drift apart.
|
||||||
|
*
|
||||||
|
* // collections/Pages.ts
|
||||||
|
* import { buildNoindexField } from '@intecion/ipal-kit'
|
||||||
|
* fields: [ /* … *\/ buildNoindexField() ],
|
||||||
|
*/
|
||||||
|
export function buildNoindexField(args: BuildNoindexFieldArgs = {}): Field {
|
||||||
|
const {
|
||||||
|
name = 'noindex',
|
||||||
|
description = 'Zaznacz, aby wykluczyć tę podstronę z indeksowania (robots: noindex, follow) i z sitemap.xml.',
|
||||||
|
label = 'Wyklucz z indeksowania (noindex)',
|
||||||
|
metaPath = 'meta.noindex',
|
||||||
|
overrides = {},
|
||||||
|
} = args
|
||||||
|
|
||||||
|
const segments = metaPath.split('.')
|
||||||
|
|
||||||
|
const mirror: FieldHook = ({ data, value }) => {
|
||||||
|
const shouldNoindex = Boolean(value ?? readPath(data as Record<string, unknown>, segments))
|
||||||
|
if (data && typeof data === 'object') {
|
||||||
|
writePath(data as Record<string, unknown>, segments, shouldNoindex)
|
||||||
|
}
|
||||||
|
return shouldNoindex
|
||||||
|
}
|
||||||
|
|
||||||
|
const { admin: adminOverrides, hooks: hooksOverrides, ...restOverrides } = overrides
|
||||||
|
|
||||||
|
return {
|
||||||
|
name,
|
||||||
|
type: 'checkbox',
|
||||||
|
admin: {
|
||||||
|
description,
|
||||||
|
position: 'sidebar',
|
||||||
|
...adminOverrides,
|
||||||
|
},
|
||||||
|
defaultValue: false,
|
||||||
|
hooks: {
|
||||||
|
...hooksOverrides,
|
||||||
|
// mirror runs first, then any project-supplied beforeChange hooks.
|
||||||
|
beforeChange: [mirror, ...(hooksOverrides?.beforeChange ?? [])],
|
||||||
|
},
|
||||||
|
label,
|
||||||
|
...restOverrides,
|
||||||
|
} as CheckboxField
|
||||||
|
}
|
||||||
@@ -9,6 +9,7 @@ export { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js'
|
|||||||
export { createManifestHandler } from './buildManifest.js'
|
export { createManifestHandler } from './buildManifest.js'
|
||||||
export { buildMetadata } from './buildMetadata.js'
|
export { buildMetadata } from './buildMetadata.js'
|
||||||
export type { PageMetadata } from './buildMetadata.js'
|
export type { PageMetadata } from './buildMetadata.js'
|
||||||
|
export { buildNoindexField } from './buildNoindexField.js'
|
||||||
export { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js'
|
export { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js'
|
||||||
export { buildRobots } from './buildRobots.js'
|
export { buildRobots } from './buildRobots.js'
|
||||||
export type { RobotsRules } from './buildRobots.js'
|
export type { RobotsRules } from './buildRobots.js'
|
||||||
|
|||||||
Reference in New Issue
Block a user