Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
12fbd424a5 | ||
|
|
6b4336f961 | ||
|
|
1413e96731 | ||
|
|
e1431a7c49 |
@@ -13,7 +13,7 @@ export default async function LocaleLayout({ children, params }: Props) {
|
||||
return (
|
||||
<html lang={locale}>
|
||||
<body>
|
||||
<SiteProviders banner={<CookieBanner equalChoice />} logEndpoint="/api/ipal/consent" shell={await getSiteShell(locale)} stats={{ locale }}>
|
||||
<SiteProviders banner={<CookieBanner controls="switch" equalChoice settings="detailed" />} logEndpoint="/api/ipal/consent" shell={await getSiteShell(locale)} stats={{ locale }}>
|
||||
<main>{children}</main>
|
||||
</SiteProviders>
|
||||
</body>
|
||||
|
||||
@@ -8,6 +8,68 @@ wersji naraz przejdź po kolei wszystkie sekcje „Wymaga zmian w projekcie” o
|
||||
wersji, którą masz. Nowe wydanie = nowa sekcja na górze; najstarsze usuwamy
|
||||
dopiero powyżej 20.
|
||||
|
||||
## 1.12.3
|
||||
|
||||
### Nowe
|
||||
- **Duże okno ustawień cookies ze szczegółami** — `<CookieBanner settings="detailed" />`. Każda kategoria to karta
|
||||
z przełącznikiem (wł./wył.), opisem i rozwijaną listą ciasteczek, które obejmuje (nazwa, dostawca, cel, czas) —
|
||||
z **Cookie Settings → Cookies**. Tryb wybiera programista: `'inline'` (domyślnie, bez zmian), `'modal'`,
|
||||
`'detailed'`. Nowa grupa w globalu **Cookie Settings → Detail labels** (podpisy listy, per język; puste →
|
||||
angielskie). `ConsentTexts` ma opcjonalne `cookies` i `details` (wypełnia je `getConsentTexts`). Nowe sloty
|
||||
`classNames`: `categoryCard`, `cookies`, `cookiesToggle`, `cookieList`, `cookie`, `cookieName`, `cookieMeta`.
|
||||
consent.md → „Duże okno ze szczegółami”.
|
||||
|
||||
### Dokumentacja
|
||||
- consent.md: porównanie trzech trybów `settings`, który wybrać (brief milczy → `detailed` przy wypełnionej liście
|
||||
Cookies), nowe pola w tabeli tekstów z panelu, sloty i uchwyty `data-ipal`.
|
||||
- AGENT.md (§0b poz. 12, §7, compliance), PROGRAMISTA §2.8 / §2.11 / §6 poz. 46, skille `ipal-setup`, `ipal-site`,
|
||||
`ipal-upgrade`, `ipal-locale-add` (Detail labels i Cookies w każdym języku), `ipal-consent-check` (import zasila
|
||||
też okno `detailed` — sprawdź je po imporcie).
|
||||
|
||||
### Wymaga zmian w projekcie
|
||||
1. Postgres/SQLite: nowe pola w globalu Cookie Settings → `payload migrate:create`. MongoDB bez zmian.
|
||||
2. Opcjonalnie: `<CookieBanner settings="detailed" />`, wypełnij Cookie Settings → Cookies (skan:
|
||||
`ipal-consent-check` → cookie-scan) i Detail labels w każdym języku.
|
||||
|
||||
## 1.12.2
|
||||
|
||||
### Poprawki
|
||||
- **Pusty panel admina na produkcji przez import mapę z deva.** `buildR2Storage` bez `R2_*` zwracał no-op, więc
|
||||
`pnpm dev` / `generate:importmap` bez R2 zapisywał `importMap.js` bez `S3ClientUploadHandler`; projekt to
|
||||
commitował, a produkcyjny panel (z R2) renderował pustą stronę bez błędu w konsoli. Teraz adapter jest
|
||||
rejestrowany zawsze (bez R2 jako `enabled: false`, media dalej na dysku) — import mapa jest identyczna w każdym
|
||||
środowisku. `ipal-audit`: ERROR „import map without the R2 upload handler”.
|
||||
- **Cookie Settings — tekst „Zapisz” nie ginie po 1.11.1 (MongoDB).** Pierwszy zapis globala usuwał stare
|
||||
`buttons.save` i przycisk wracał do „Save preferences” we wszystkich językach. Plugin przy starcie kopiuje
|
||||
`buttons.save` → `buttons.savePreferences` (wszystkie języki), gdy nowego pola brak. `getConsentTexts` czytał stare
|
||||
pole jako tekst, a Mongo zwraca je jako mapę `{ pl, en }` (pola nie ma w schemacie) — w banerze mogło wyjść
|
||||
„[object Object]”.
|
||||
- `ipal-audit`: `"exclude"` w kilku liniach tsconfig nie jest już zgłaszany; `a11y`, `i18n`, `l10n` to nie „numbered
|
||||
fields”; łapie linki `` `${prefix}/${slug}` `` i ścieżki stron wpisane w kod (`` `${prefix}/kontakt` ``); komunikat
|
||||
„panel text in Polish — admin labels/descriptions are English” (był mylący „panel is English”).
|
||||
|
||||
### Nowe
|
||||
- **Media tylko do odczytu:** samo `R2_PUBLIC_URL` (absolutne, poza produkcją) → adresy plików z domeny mediów,
|
||||
upload i usuwanie zablokowane (403). Lokalny dev na bazie produkcyjnej bez kluczy do bucketa. `ipalEnvRules` w
|
||||
devie nie wymaga wtedy reszty `R2_*`. storage.md → „Zachowanie”.
|
||||
- **`context: { ipalSkipAutoFill: true }`** (`SKIP_AUTO_FILL`) — zapis bez auto-fill meta i `aiSummary`. Dla migracji
|
||||
danych i skryptów, które mają zapisać tylko to, co ustawiają. seo.md.
|
||||
- **`createPageRoute` przekierowuje stronę główną spod jej sluga** (`/pl/home` → 308 `/pl`). Wyłączenie:
|
||||
`homeAlias: false`. Usuń własne przekierowanie z `page.tsx`. pages.md.
|
||||
|
||||
### Dokumentacja
|
||||
- i18n.md: `fallback: true` utrwala tekst języka domyślnego w pustych polach innych języków przy zapisie — skutki i
|
||||
jak pisać skrypty.
|
||||
- PROGRAMISTA §1: `pnpm up --latest @intecion/ipal-kit` (samo `pnpm up` nie wyjdzie poza dokładną wersję); 401 przy
|
||||
publicznym rejestrze = stary token w `~/.npmrc`.
|
||||
|
||||
### Wymaga zmian w projekcie
|
||||
1. `pnpm up --latest @intecion/ipal-kit`, potem `pnpm payload generate:importmap` i sprawdź, że `importMap.js` ma
|
||||
`@payloadcms/storage-s3/client#S3ClientUploadHandler` (projekt z `buildR2Storage`). Commituj.
|
||||
2. Własne przekierowanie strony głównej spod sluga (np. w `render` z `buildLocalizedPath`) — usuń, robi to
|
||||
`createPageRoute`.
|
||||
3. Opcjonalnie: lokalny dev na bazie produkcyjnej → w `.env` samo `R2_PUBLIC_URL` zamiast kluczy R2.
|
||||
|
||||
## 1.12.1
|
||||
|
||||
### Nowe
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@ Szczegóły API — jeden plik na moduł:
|
||||
| Widget dostępności (opcjonalny) | [accessibility.md](./accessibility.md) |
|
||||
| GA4, GTM, Meta Pixel, Clarity, LinkedIn, TikTok, `defer` | [analytics.md](./analytics.md) |
|
||||
| Bloki, RenderBlocks, enhanceProps | [blocks.md](./blocks.md) |
|
||||
| Zgoda cookies, baner | [consent.md](./consent.md) |
|
||||
| Zgoda cookies, baner, okno ustawień (w pasku / modal / duże ze szczegółami ciasteczek) | [consent.md](./consent.md) |
|
||||
| Strona w budowie — blokada podstron z popupem (narzędzie deweloperskie) | [construction.md](./construction.md) |
|
||||
| Routing, archiwa, redirecty, Markdown, wyszukiwarka | [content.md](./content.md) |
|
||||
| Email SMTP / Graph | [email.md](./email.md) |
|
||||
|
||||
+3
-2
@@ -63,7 +63,7 @@ strona), **P** = test w panelu. Pełny kod: PROGRAMISTA.md §2.
|
||||
| 9 | **Media / R2 / szybkość** | `Media` z `focalPoint`, `normalizeFilenameHook`, `buildOptimizeUploadHook`, `buildMediaPlaceholderHook` + pole; **zawsze** `buildR2Storage(['media'], { s3Storage })` + `@payloadcms/storage-s3`; `R2_*` w `.env.example`; `<MediaPreconnect/>`; `images: buildImagesConfig()` i `buildUploadSecurityHeaders()` w `next.config.ts`; `<Media>` projektu przez `mediaImageProps`/`videoProps` (§6.11b) | `buildR2Storage`, `mediaImageProps`, `videoProps`, `buildImagesConfig` | A, S |
|
||||
| 10 | **Formularze** | każdy formularz z **seeda** (`scripts/seed-form-*.ts`: pola, potwierdzenie, mail do firmy **i** potwierdzenie do klienta, każdy język); blok z `<RenderForm>` + `formClasses.ts` (wygląd, raz); `actions.ts` = `createSubmitAction({ getCachedPayload, headers })`; `forms: {…}` w `ipalKit`; `email: mailAdapter()` | `RenderForm` (`/rsc`), `createSubmitAction`, `mailAdapter` | A, P |
|
||||
| 11 | **Turnstile** | `<SiteProviders>` w `[locale]/layout.tsx` (wpina `TurnstileProvider` z kluczem z panelu); widget renderuje `RenderForm`; klucze w Site Integrations | `SiteProviders`, `getTurnstileConfig`, `TurnstileProvider` | A, P |
|
||||
| 12 | Zgoda + analityka | `<SiteProviders logEndpoint="/api/ipal/consent" banner={<CookieBanner equalChoice />}>` (ConsentProvider, baner, CookieButton, Analytics w dobrej kolejności); ID narzędzi w panelu; lista ciasteczek ze skanu (cookie-scan → import) + `<CookieTable>` na stronie polityki cookies | consent.md, analytics.md | A, `ipal-consent-check` |
|
||||
| 12 | Zgoda + analityka | `<SiteProviders logEndpoint="/api/ipal/consent" banner={<CookieBanner equalChoice settings="detailed" />}>` (ConsentProvider, baner, CookieButton, Analytics w dobrej kolejności); tryb okna ustawień (`settings`: `inline` / `modal` / `detailed`) wg designu, brief milczy → `detailed`, decyzja do „Ustaleń projektu”; ID narzędzi w panelu; lista ciasteczek ze skanu (cookie-scan → import) — zasila `<CookieTable>` na stronie polityki **i** listy w oknie `detailed`; Cookie Settings → Detail labels w każdym języku | consent.md, analytics.md | A, `ipal-consent-check` |
|
||||
| 13 | Bezpieczeństwo | `buildSecurityHeaders` w `next.config.ts`; `twoFactor: { issuer, plugin: payloadTotp }`; CSP `report-only` → `enforce`; `IPAL_IP_HEADER` na produkcji | security.md, forms.md | A |
|
||||
| 14 | Operacje | `src/app/api/health/route.ts` (`healthRoute`); `src/instrumentation.ts` z `assertEnv(ipalEnvRules({ storage: true, ipHeader: true }))`; staging z `IPAL_NOINDEX=1`; testy smoke (§8a) | `healthRoute`, `assertEnv`, `ipalEnvRules` | A |
|
||||
| 15 | Strony systemowe | Site Settings → System Pages: homepage, 404, polityka prywatności, cookies; linki prawne w stopce przez rolę (`getSystemLinks(locale)`) | `getSystemLinks`, `getSystemPagePath`, `getNotFoundPage` | P |
|
||||
@@ -844,6 +844,7 @@ projekcie → **ipal-plugin-gap**, nie kopia.
|
||||
| Potrzeba | Użyj | Doc |
|
||||
|---|---|---|
|
||||
| Baner, ustawienia, przycisk cookies | `<SiteProviders banner={<CookieBanner …/>}>`, `CookieButton`, `useConsent` | consent.md |
|
||||
| Okno ustawień: w pasku / małe / duże ze szczegółami ciasteczek | `<CookieBanner settings="inline" \| "modal" \| "detailed">` — nie buduj własnego okna ani listy ciasteczek | consent.md → „Duże okno ze szczegółami” |
|
||||
| Skrypt zależny od zgody | `ConsentScript` | consent.md |
|
||||
| Tabela ciasteczek na polityce | `<CookieTable>` (`/rsc`), `getCookieTable` | consent.md |
|
||||
| GA4, GTM, Pixel, Clarity, LinkedIn, TikTok | ID w panelu — `SiteProviders` ładuje `Analytics` (`analytics={{ defer: true }}`) | analytics.md |
|
||||
@@ -855,7 +856,7 @@ projekcie → **ipal-plugin-gap**, nie kopia.
|
||||
**Compliance (PL/EU) — mechanizm z pluginu, treść od klienta:** strony polityk
|
||||
jako System Pages, `CookieBanner` + `CookieButton`, checkbox `consent` w
|
||||
formularzach (enforcement server-side), dane administratora w globalu, tabela
|
||||
ciasteczek z panelu (`<CookieTable>`, skan: ipal-consent-check). Treści prawnych nie piszesz. Widget dostępności — tylko gdy klient
|
||||
ciasteczek z panelu (`<CookieTable>` i okno `settings="detailed"`, skan: ipal-consent-check). Treści prawnych nie piszesz. Widget dostępności — tylko gdy klient
|
||||
wymaga (accessibility.md).
|
||||
|
||||
**Bezpieczeństwo:** 2FA wymuszone (`ipalKit({ twoFactor: { issuer, plugin:
|
||||
|
||||
@@ -53,7 +53,7 @@ echo "ipal-audit — $(pwd)"
|
||||
# --- Skill templates must not be compiled as project code ---
|
||||
if [ -d .agents ] && [ -f tsconfig.json ]; then
|
||||
report ERROR "tsconfig.json does not exclude .agents" "skill templates (.ts/.tsx) break tsc / next build — \"exclude\": [\"node_modules\", \".agents\"]" \
|
||||
"$(grep -qE '"exclude"[^]]*\.agents' tsconfig.json || echo tsconfig.json)"
|
||||
"$(tr -d '\n' < tsconfig.json | grep -qE '"exclude"[^]]*\.agents' || echo tsconfig.json)"
|
||||
fi
|
||||
|
||||
# --- Sitemap: one route, look from the plugin (seo.md) ---
|
||||
@@ -197,7 +197,10 @@ if [ -n "$FRONT" ]; then
|
||||
report ERROR "hardcoded homepage slug" "links.md — the homepage comes from Site Settings: resolveLink(link, locale) / getHomeSlug(locale), never a slug name in code" \
|
||||
"$(g "(===|!==|==|!=) *['\"](home|homepage|strona-glowna|glowna|start|index)['\"]|['\"](home|homepage|strona-glowna|glowna|start|index)['\"] *(===|!==|==|!=)" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | grep -vE "[Tt]ype *[!=]==? *['\"]home|['\"]home['\"] *[!=]==? *[A-Za-z_.]*[Tt]ype" | nc '=')"
|
||||
report ERROR "URL built from a slug by hand" "links.md — resolveLink / resolveNav (lib/content) or buildLocalizedPath: locale prefix, homepage, unsafe and dead links" \
|
||||
"$(g '`/\$\{[^}]*[Ss]lug|['"'"'"]/['"'"'"] *\+ *[A-Za-z_.?]*[Ss]lug' $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '[Ss]lug')"
|
||||
"$(g '`/\$\{[^}]*[Ss]lug|`\$\{[A-Za-z_.]*\}/\$\{[^}]*[Ss]lug|['"'"'"]/['"'"'"] *\+ *[A-Za-z_.?]*[Ss]lug' $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '[Ss]lug')"
|
||||
# `${prefix}/kontakt`, `/${locale}/kontakt` — a page path typed into the code (fallback links)
|
||||
report ERROR "page path hardcoded in a link" "links.md — a missing link renders nothing; never a fallback to a slug typed in code" \
|
||||
"$(g '`\$\{[A-Za-z_.]*\}/[a-z][a-z0-9-]*`|`/\$\{locale\}/[a-z][a-z0-9-]*`' $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '`')"
|
||||
fi
|
||||
if [ -n "$FRONT" ]; then
|
||||
report ERROR "logic keyed on content text" "§2 the editor can rename it any time — a style/flag is a panel field (e.g. buildLinkField({ appearances: [...] }))" \
|
||||
@@ -274,6 +277,15 @@ if [ -n "$CFG" ]; then
|
||||
need ERROR '' "forms in ipalKit" "$CFG → ipalKit({ forms: {…} }) — forms are built in the panel" 'forms *:' "$CFG"
|
||||
need ERROR '' "mailAdapter" "$CFG → email: mailAdapter() — form e-mails go through the panel transport" 'mailAdapter\(' "$CFG"
|
||||
need ERROR r2 "R2 storage" "$CFG → buildR2Storage(['media'], { s3Storage }) — always wired, local disk only without R2_* env" 'buildR2Storage' "$CFG"
|
||||
# pnpm dev / generate:importmap with ipal-kit < 1.12.2 and no R2_* env dropped the storage-s3
|
||||
# client handler → blank admin in production (where R2 is on)
|
||||
if grep -q 'buildR2Storage' "$CFG" 2>/dev/null; then
|
||||
for IM in src/app/\(payload\)/*/importMap.js; do
|
||||
[ -f "$IM" ] || continue
|
||||
report ERROR "import map without the R2 upload handler" "storage.md — pnpm payload generate:importmap (ipal-kit ≥ 1.12.2 writes it with or without R2_* env); without it the production admin renders blank" \
|
||||
"$(grep -q 'S3ClientUploadHandler' "$IM" || echo "$IM")"
|
||||
done
|
||||
fi
|
||||
need ERROR r2 "@payloadcms/storage-s3" "pnpm add @payloadcms/storage-s3 (same version as payload)" '"@payloadcms/storage-s3"' package.json
|
||||
need ERROR twofactor "2FA" "$CFG → twoFactor: { issuer, plugin: payloadTotp }" 'payloadTotp' "$CFG"
|
||||
report WARNING "robots blocks AI bots" "§0b.8 — only with the client's decision in AGENTS.md" \
|
||||
|
||||
@@ -22,7 +22,8 @@ for (const file of files) {
|
||||
const src = strip(readFileSync(file, 'utf8'))
|
||||
|
||||
// numbered slots: cta1Label, feature2Title, image3, phone2 → array with "+ Add …"
|
||||
for (const m of src.matchAll(/name:\s*['"]([a-zA-Z]+[0-9]+[a-zA-Z0-9]*)['"]/g)) {
|
||||
// digits at the end or before a new word (cta1Label) — not numeronyms like a11y, i18n, l10n
|
||||
for (const m of src.matchAll(/name:\s*['"]([a-zA-Z]+[0-9]+(?:[A-Z][a-zA-Z0-9]*)?)['"]/g)) {
|
||||
if (/^(h[1-6]|x[0-9]|[a-z]?2fa)$/i.test(m[1])) continue
|
||||
out('ERROR', 'numbered fields → one array field with labels {singular, plural} ("+ Add …")', file, src, m.index, m[1])
|
||||
}
|
||||
@@ -30,7 +31,7 @@ for (const file of files) {
|
||||
// panel text must be English and short
|
||||
for (const m of src.matchAll(/\b(label|description|singular|plural|placeholder)\s*:\s*(['"`])((?:(?!\2).)*)\2/g)) {
|
||||
const text = m[3]
|
||||
if (POLISH.test(text)) out('WARNING', 'panel is English — labels/descriptions in English', file, src, m.index, `${m[1]}: "${text.slice(0, 60)}"`)
|
||||
if (POLISH.test(text)) out('WARNING', 'panel text in Polish — admin labels/descriptions are English', file, src, m.index, `${m[1]}: "${text.slice(0, 60)}"`)
|
||||
else if (m[1] === 'description' && text.length > 120) out('WARNING', 'description over 120 chars — one short sentence: what it does / where it shows', file, src, m.index, `${text.length} chars`)
|
||||
}
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ się załadować wcześniej tylko z sygnałem Consent Mode „denied” i bez ci
|
||||
renderowany albo starsza wersja ipal-kit bez atrybutów `data-ipal` na przyciskach → **ipal-upgrade**.
|
||||
|
||||
Skrypt wymaga przycisków z `data-ipal="accept"` / `"reject"` — ma je
|
||||
`CookieBanner` z pluginu. Własny baner w projekcie to naruszenie AGENT.md §7.
|
||||
`CookieBanner` z pluginu w każdym trybie `settings` (`inline`, `modal`, `detailed`). Własny baner w projekcie to naruszenie AGENT.md §7.
|
||||
|
||||
## Lista ciasteczek do polityki cookies (cookie-scan)
|
||||
|
||||
@@ -55,7 +55,10 @@ Po każdej zmianie narzędzi (nowy piksel, czat, mapa, wideo) i przed oddaniem s
|
||||
LOCALE=pl pnpm payload run .agents/skills/ipal-consent-check/scripts/import-cookies.ts cookie-scan/cookies.json
|
||||
```
|
||||
Łączy po nazwie, nie nadpisuje zmian redaktora (`OVERWRITE=1` wymusza). Nie usuwa ciasteczek,
|
||||
których skan nie widział — to robi redaktor w panelu.
|
||||
których skan nie widział — to robi redaktor w panelu. Ta sama lista zasila okno
|
||||
`<CookieBanner settings="detailed">` (rozwijana lista pod każdą kategorią) — po imporcie otwórz
|
||||
„Ustawienia” w banerze i sprawdź, że każda kategoria pokazuje swoje ciasteczka, a podpisy
|
||||
(Cookie Settings → Detail labels) są w danym języku.
|
||||
3. Strona polityki cookies pokazuje tabelę z panelu — **nie wklejaj listy do treści polityki**:
|
||||
```tsx
|
||||
import { getCookieTable, getConsentTexts } from '@intecion/ipal-kit'
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/**
|
||||
* Imports a cookie-scan result into Cookie Settings → Cookies (panel), so the
|
||||
* cookie policy page (<CookieTable>) lists what the site really sets.
|
||||
* cookie policy page (<CookieTable>) and the detailed consent window
|
||||
* (<CookieBanner settings="detailed">) list what the site really sets.
|
||||
*
|
||||
* LOCALE=pl pnpm payload run .agents/skills/ipal-consent-check/scripts/import-cookies.ts cookie-scan/cookies.json
|
||||
* # second language: scan again with --lang en, then import with LOCALE=en
|
||||
|
||||
@@ -53,7 +53,7 @@ Uzupełnij w tej kolejności (panel albo skrypt Local API z `locale: 'de'`):
|
||||
| Homepage/404/polityka | System Pages (relacje wspólne) + ich slug w `de` | `/de` → 404, link polityki pusty |
|
||||
| Header / Footer — etykiety linków | globale nawigacji | puste pozycje menu |
|
||||
| Site Settings — nazwa, opis, OG | Site Settings | tytuł/OG z fallbacku |
|
||||
| Cookie Settings — wszystkie teksty + `privacyLinkLabel` | Cookie Settings | baner w innym języku (RODO: zgoda musi być zrozumiała) |
|
||||
| Cookie Settings — wszystkie teksty + `privacyLinkLabel`, Detail labels, Cookies (`purpose`, `duration`) | Cookie Settings | baner / okno `detailed` w innym języku (RODO: zgoda musi być zrozumiała); skan + import z `--lang <kod>` (ipal-consent-check) |
|
||||
| Notifications — `form.*` | Notifications | komunikaty formularza z angielskiego fallbacku |
|
||||
| Forms — etykiety pól, potwierdzenie, Emails | Forms (każdy formularz) | formularz w złym języku |
|
||||
| SEO tab — meta title/description | każda strona | duplikaty/braki w seo-check |
|
||||
|
||||
@@ -39,7 +39,8 @@ tylko, gdy użytkownik o to poprosi. Pełna budowa strony: skill **ipal-site**.
|
||||
przez `next/font` z `latin-ext`, `@source` na plugin (AGENT.md §6.11, przykład w `../ipal-block/resources/kod-sekcji.md`).
|
||||
6. **Routing** — `proxy.ts` (`createProxy(i18nConfig, { NextResponse, markdown: true })`), `lib/content.ts`
|
||||
(`createContentHelpers` z `markdownAlternate: true`, `summaryField`, `mcp` — PROGRAMISTA §2.7),
|
||||
layout bez `<head>`: `<SiteProviders shell={await getSiteShell(locale)} logEndpoint banner={<CookieBanner equalChoice />}>`,
|
||||
layout bez `<head>`: `<SiteProviders shell={await getSiteShell(locale)} logEndpoint banner={<CookieBanner equalChoice settings="detailed" />}>`
|
||||
(tryb okna ustawień `inline` / `modal` / `detailed` wg designu — consent.md),
|
||||
catch-all: `createPageRoute(content, { blocks, notFound, permanentRedirect, blockProps })` + literał `revalidate`,
|
||||
`not-found.tsx`: `createNotFoundPage(content, { load: loadNotFoundView })` + `notFoundView.ts` z
|
||||
`renderNotFoundView` (PROGRAMISTA §2.6–2.8, pages.md).
|
||||
@@ -53,7 +54,7 @@ tylko, gdy użytkownik o to poprosi. Pełna budowa strony: skill **ipal-site**.
|
||||
wpuszcza boty AI (PROGRAMISTA §2.8, AGENT.md §0b.5–8).
|
||||
9. **Formularze** — skill **ipal-form**: blok z `<RenderForm>`, `formClasses.ts`, `createSubmitAction` raz, każdy formularz z seeda
|
||||
(mail do firmy + potwierdzenie do klienta). Cookies: skan + import (ipal-consent-check), `<CookieTable>`
|
||||
na stronie polityki cookies.
|
||||
na stronie polityki cookies; ta sama lista pokazuje się w oknie `settings="detailed"` (Detail labels w panelu).
|
||||
10. **Nawigacja** — skill **ipal-nav**.
|
||||
11. **Kontrola kompletu** — `pnpm generate:types`, `pnpm payload generate:importmap`,
|
||||
**ipal-audit** (pełny) = 0 błędów, w tym sekcja „missing: …” (§0b); po
|
||||
|
||||
@@ -68,8 +68,8 @@ formularz z polami w JSX, trasa `api/contact`, `nodemailer`, reCAPTCHA (AGENT.md
|
||||
Nie wymyślaj danych firmy, cen, opinii, liczb, certyfikatów, nazwisk.
|
||||
2. `pnpm payload run scripts/seed-content.ts` → lista placeholderów trafia do raportu.
|
||||
3. System Pages: Homepage, 404, polityka prywatności (strona istnieje; treść
|
||||
polityki od klienta → placeholder). Cookie Settings, Notifications — teksty w
|
||||
każdym języku.
|
||||
polityki od klienta → placeholder). Cookie Settings (z Detail labels i listą Cookies
|
||||
ze skanu), Notifications — teksty w każdym języku.
|
||||
4. **ipal-locale-add → `locale-coverage`** = 0 braków (albo świadome w raporcie).
|
||||
5. Obrazy: zostawiasz puste pola upload (redaktor dodaje) albo wgrywasz pliki z
|
||||
briefu przez panel — przygotowane (WebP/JPG ≤ 1.5 MB, ≤ 2560 px).
|
||||
|
||||
@@ -50,6 +50,11 @@ własny spis treści (→ `extractHeadings` + `TableOfContents` + `headingIds`),
|
||||
`CmsLink['appearance']` (typy linków bez stylu to teraz `CmsLinkPlain`). Cookie Settings: `buttons.save` →
|
||||
`buttons.savePreferences` — w `migrate:create` wybierz **rename** kolumny, żeby zachować teksty.
|
||||
|
||||
**→ 1.12.3 (PROGRAMISTA §6, poz. 46):** Postgres/SQLite: `migrate:create` (nowa grupa Cookie Settings →
|
||||
`detailLabels`, same nowe kolumny — bez rename). Własne okno ustawień cookies albo lista ciasteczek dopisana do
|
||||
banera → `<CookieBanner settings="detailed">` i usuń kopię. Przy `detailed`: Cookie Settings → Cookies wypełnione
|
||||
(skan, **ipal-consent-check**) i Detail labels w każdym języku.
|
||||
|
||||
## 2. Inwentaryzacja (bez zmian w kodzie)
|
||||
Dla **każdej** pozycji tabeli PROGRAMISTA §6 pokaż dowód (grep / plik), czy
|
||||
dotyczy projektu. Uruchom skill **ipal-audit** (`--quick`) i dołącz wynik.
|
||||
|
||||
+40
-5
@@ -2,8 +2,9 @@
|
||||
|
||||
Banner zgody na cookies (GDPR): 4 kategorie (necessary / functional /
|
||||
analytics / marketing), zapis w cookie z wersjonowaniem, Google Consent Mode,
|
||||
treść z globala CookieSettings. Domyślny wygląd w czystym Tailwind,
|
||||
nadpisywalny.
|
||||
treść z globala CookieSettings. Okno ustawień w trzech trybach do wyboru
|
||||
(`settings`: w pasku, małe okno, duże okno ze szczegółami ciasteczek). Domyślny
|
||||
wygląd w czystym Tailwind, nadpisywalny.
|
||||
|
||||
## Zależność
|
||||
|
||||
@@ -177,7 +178,8 @@ Podany className zastępuje domyślny (nie dokleja się). Każdy element ma swó
|
||||
| `actions` | rząd przycisków banera |
|
||||
| `primaryButton`, `secondaryButton` | dwa style przycisków (domyślne dla wszystkich) |
|
||||
| `acceptButton`, `rejectButton`, `settingsButton`, `saveButton`, `backButton` | pojedyncze przyciski — puste → `primaryButton` / `secondaryButton` |
|
||||
| `overlay`, `dialog`, `closeButton` | modal ustawień (`settings="modal"`) |
|
||||
| `overlay`, `dialog`, `closeButton` | modal ustawień (`settings="modal"` / `"detailed"`) |
|
||||
| `categoryCard`, `cookies`, `cookiesToggle`, `cookieList`, `cookie`, `cookieName`, `cookieMeta` | duże okno (`settings="detailed"`): karta kategorii, rozwijana lista ciasteczek, jedno ciasteczko, nazwa, siatka dostawca / cel / czas |
|
||||
| `settingsTitle`, `settingsDescription`, `categories`, `category`, `categoryTitle`, `categoryDescription` | widok ustawień |
|
||||
| `control`, `controlThumb`, `badge` | checkbox / przełącznik, kciuk przełącznika, znacznik „Zawsze aktywne” |
|
||||
| `settingsActions` | rząd przycisków pod kategoriami |
|
||||
@@ -198,6 +200,36 @@ Podany className zastępuje domyślny (nie dokleja się). Każdy element ma swó
|
||||
|
||||
Domyślnie (bez tych propsów) baner wygląda i działa jak przed 1.10.0.
|
||||
|
||||
### Duże okno ze szczegółami (`settings="detailed"`, 1.12.3)
|
||||
|
||||
Trzy tryby ustawień do wyboru w projekcie — jeden prop:
|
||||
|
||||
| `settings` | Co widzi użytkownik po „Ustawienia” |
|
||||
|---|---|
|
||||
| `'inline'` (domyślnie) | kategorie w samym pasku banera |
|
||||
| `'modal'` | małe okno na środku: kategoria + krótki opis + przełącznik |
|
||||
| `'detailed'` | duże okno: każda kategoria to karta z przełącznikiem, opisem i rozwijaną listą jej ciasteczek (nazwa, dostawca, cel, czas przechowywania) |
|
||||
|
||||
```tsx
|
||||
<CookieBanner equalChoice controls="switch" settings="detailed" />
|
||||
```
|
||||
|
||||
Lista ciasteczek bierze się z **Cookie Settings → Cookies** (to samo źródło co `<CookieTable>` na stronie
|
||||
polityki), filtrowana po kategorii — kategoria bez wpisów nie ma rozwijanej listy. Podpisy listy: **Cookie
|
||||
Settings → Detail labels** (`cookies` — np. „Używane ciasteczka”, licznik dopisuje się sam; `provider`, `purpose`,
|
||||
`duration`), per język; puste → angielskie. `getConsentTexts` przekazuje to w `texts.cookies` / `texts.details`
|
||||
— nic nie trzeba podawać w kodzie. Zamykanie jak w `'modal'` (✕, Escape, klik w tło). Domyślna szerokość okna
|
||||
`max-w-4xl` — zmiana przez `classNames.dialog`.
|
||||
|
||||
Który tryb wybrać: decyduje design projektu. Brief milczy → `'detailed'` (użytkownik widzi przy zgodzie, jakie
|
||||
ciasteczka i od kogo — pełna informacja w miejscu decyzji), pod warunkiem że lista Cookies jest wypełniona ze skanu
|
||||
(`ipal-consent-check` → cookie-scan); pusta lista = okno bez rozwijanych list, wtedy wystarczy `'modal'`. Decyzję
|
||||
zapisz w `AGENTS.md` → „Ustalenia projektu”.
|
||||
|
||||
Nie buduj własnego okna ani listy ciasteczek w projekcie (AGENT.md §7). Wygląd zmieniasz tokenami i `classNames`;
|
||||
gdy potrzebujesz całkiem innego układu, dane są w kontekście: `useConsentContext()` → `texts.cookies`,
|
||||
`texts.details`, `state`, `savePreferences`.
|
||||
|
||||
Teksty z panelu (**Cookie Settings**, per język) — puste pole = element się nie pokazuje:
|
||||
|
||||
| Pole | Gdzie |
|
||||
@@ -206,14 +238,17 @@ Teksty z panelu (**Cookie Settings**, per język) — puste pole = element się
|
||||
| `title` | tytuł banera („Szanujemy Twoją prywatność”) |
|
||||
| `settingsDescription` | opis pod tytułem ustawień |
|
||||
| `alwaysActiveLabel` | znacznik przy „Niezbędne” zamiast wyłączonego przełącznika |
|
||||
| `detailLabels.cookies` / `.provider` / `.purpose` / `.duration` | podpisy listy ciasteczek w oknie `settings="detailed"` (puste → angielskie) |
|
||||
| `cookies` (lista) | ciasteczka per kategoria — okno `detailed` i `<CookieTable>`; `purpose`, `duration` per język |
|
||||
| `buttons.close` | etykieta przycisku ✕ dla czytników ekranu (puste → „Close”) |
|
||||
| `buttons.savePreferences` | „Zapisz” w ustawieniach (do 1.11.0 pole `save` — nazwa zarezerwowana w Mongoose; w kodzie dalej `texts.buttons.save`) |
|
||||
| `buttons.savePreferences` | „Zapisz” w ustawieniach (do 1.11.0 pole `save` — nazwa zarezerwowana w Mongoose; w kodzie dalej `texts.buttons.save`). MongoDB: od 1.12.2 plugin przy starcie kopiuje stare `save` (wszystkie języki), gdy `savePreferences` brak |
|
||||
|
||||
Nowe pola w globalu = migracja w projektach na Postgres/SQLite (`payload migrate:create`); MongoDB bez zmian.
|
||||
|
||||
Elementy mają też stabilne uchwyty `data-ipal` do CSS i testów e2e (używa ich
|
||||
`ipal-consent-check`): `banner`, `cookie-button` oraz przyciski `settings`, `reject`,
|
||||
`accept`, `back`, `save`; w trybie modal także `consent-overlay`, `consent-dialog`, `close`.
|
||||
`accept`, `back`, `save`; w trybie modal także `consent-overlay`, `consent-dialog`, `close`; w trybie detailed
|
||||
dodatkowo `category-<kategoria>` (karta) i `cookies` (rozwijana lista).
|
||||
|
||||
Dostępność: dialog banera i `CookieButton` mają `aria-label` z **Cookie Settings →
|
||||
title** albo **settingsTitle** (per język) — bez tekstów na sztywno w komponentach. Modal ma
|
||||
|
||||
+18
-1
@@ -65,6 +65,15 @@ curl -s -o /dev/null -w "%{http_code}\n" \
|
||||
https://git.intecion.net/api/packages/IntecionSoftware/npm/@intecion%2Fipal-kit # 200
|
||||
```
|
||||
|
||||
**Aktualizacja do najnowszej wersji:** `pnpm up --latest @intecion/ipal-kit`. Samo
|
||||
`pnpm up @intecion/ipal-kit` nic nie zmieni, gdy `package.json` ma wersję dokładną
|
||||
(`"1.8.13"`) — zostaje w zakresie. Potem sekcje „Wymaga zmian w projekcie” z CHANGELOG.
|
||||
|
||||
**401 przy pobieraniu paczki** (`ERR_PNPM_FETCH_401 … Unauthorized`) mimo publicznego
|
||||
rejestru: w `~/.npmrc` jest stary `_authToken` dla `git.intecion.net`, a nieważny token
|
||||
blokuje także odczyt. Usuń tę linię (token potrzebny tylko do publikacji, §8.3) albo
|
||||
jednorazowo: `NPM_CONFIG_USERCONFIG=/dev/null pnpm up --latest @intecion/ipal-kit`.
|
||||
|
||||
---
|
||||
|
||||
## 2. NOWY PROJEKT — KOLEJNOŚĆ
|
||||
@@ -277,6 +286,12 @@ zmienisz albo wyłączysz: `banner={<CookieBanner classNames={…} />}` / `false
|
||||
`analytics={{ defer: true }}` / `false`, `jsonLd={[buildNavigationJsonLd(…)]}`, `cookieMap`,
|
||||
`preconnect={false}`. Zupełnie własny układ: te same dane z `shell` do providerów (consent.md).
|
||||
|
||||
Okno ustawień zgody wybierasz propem `settings` banera: `'inline'` (domyślnie — kategorie w pasku),
|
||||
`'modal'` (małe okno na środku) albo `'detailed'` (duże okno: każda kategoria z przełącznikiem, opisem i
|
||||
rozwijaną listą ciasteczek z Cookie Settings → Cookies). Przykład:
|
||||
`banner={<CookieBanner equalChoice controls="switch" settings="detailed" />}` — opis: consent.md → „Duże okno ze
|
||||
szczegółami”.
|
||||
|
||||
```tsx
|
||||
// src/app/(frontend)/[locale]/[[...slug]]/page.tsx — PODWÓJNE nawiasy
|
||||
import { notFound, permanentRedirect } from 'next/navigation'
|
||||
@@ -393,7 +408,8 @@ pnpm dev
|
||||
3. **Pages** — strona główna z tytułem **w każdym języku** (pusty slug EN = 404 na `/en`).
|
||||
4. **Site Settings → System Pages** — Homepage (bez tego `/pl` → 404), 404,
|
||||
polityki; archiwa kolekcji treści.
|
||||
5. **Cookie Settings** — teksty banera per język.
|
||||
5. **Cookie Settings** — teksty banera per język; **Cookies** (lista ze skanu, `ipal-consent-check`) i **Detail
|
||||
labels** (podpisy listy w oknie `settings="detailed"`) — też w każdym języku.
|
||||
6. **Notifications** — komunikaty formularzy per język.
|
||||
7. **Site Integrations** — SMTP/Graph (From Name, From Address), Turnstile, ID
|
||||
analityki/pikseli.
|
||||
@@ -568,6 +584,7 @@ Rób po jednej pozycji, buduj, sprawdzaj. Kolejność wg wagi:
|
||||
| 43 | **1.11.1** — `<Media>` ustawia kolor tła tylko dla JPEG | usuń warunek — `mediaImageProps` robi to sam (`placeholderColor`) | storage.md |
|
||||
| 44 | **1.11.1** — `CmsLink['appearance']` zastąpione własnym typem, bo typ zależał od kolejności pól | typy per kształt: `CmsLink`, `CmsLinkPlain`, `CmsLinkNoLabel`; `pnpm generate:types` i popraw importy | links.md |
|
||||
| 45 | **1.11.1** — opis formatu w etykiecie pola formularza / godzina jako tekst | pole **Placeholder** w panelu, typ **Time**; Postgres: `migrate:create` | forms.md |
|
||||
| 46 | **1.12.3** — własne okno ustawień cookies / lista ciasteczek w banerze pisana w projekcie | `<CookieBanner settings="detailed">` (lista z Cookie Settings → Cookies, podpisy: Detail labels); usuń własną wersję; Postgres: `migrate:create` | consent.md |
|
||||
| 33 | **1.9.2** — `src/fields/sectionHeader.ts`, `sectionSettings.ts`, `lib/navigation.ts`, ręczne `resolveLinkHref` w `CMSLink` | `buildSectionHeaderField`, `buildSectionSettingsField` (ten sam kształt danych — bez migracji), `resolveNav`, `resolveLink` z `lib/content` | blocks.md, links.md |
|
||||
|
||||
Po aktualizacji pakietu: `pnpm ipal:skills` (nowe wersje skilli), `pnpm payload generate:importmap`, `rm -rf .next`, restart dev, grep nowego symbolu w
|
||||
|
||||
@@ -24,6 +24,17 @@ Plugin ustawia `config.localization` z tego. Walidacja jest eager (fail-fast
|
||||
przy starcie): pusta lista, duplikaty kodów, `defaultLocale` spoza listy,
|
||||
zły format kodu → błąd `[ipal] i18n: ...`.
|
||||
|
||||
**`fallback: true` a zapis.** Odczyt w języku bez wartości daje wartość języka domyślnego —
|
||||
i **zapis dokumentu utrwala ją**: zapis strony (w panelu albo `payload.update`) w dowolnym
|
||||
języku zapisuje tekst PL w polach lokalizowanych, które w EN/DE były puste (np. pusty
|
||||
`subheading` bloku dostaje polski). Skutki: niewidoczne braki tłumaczeń stają się polskim
|
||||
tekstem na stronie EN/DE. Dlatego:
|
||||
- tłumacz każde pole w każdym języku (nie licz na fallback),
|
||||
- skrypty migracji/seedów czytają z `fallbackLocale: false` i zapisują tylko to, co ustawiają
|
||||
(`context: { ipalSkipAutoFill: true }` — seo.md); dane do zmiany najpierw sprawdź na kopii bazy,
|
||||
- `fallback: false` wyłącza i odczyt z języka domyślnego (puste pola na stronie EN/DE) —
|
||||
świadoma decyzja projektu.
|
||||
|
||||
## Front — helpery
|
||||
|
||||
Wszystkie helpery są czyste (przyjmują config jako argument). Trzymaj swój
|
||||
|
||||
@@ -120,6 +120,10 @@ Domyślnie `'notFound'`; własna decyzja: `onMissing: ({ locale, segments }) =>
|
||||
const route = createPageRoute(content, { blocks: blockRegistry, notFound, permanentRedirect, redirect, onMissing: 'redirectHome' })
|
||||
```
|
||||
|
||||
**Strona główna pod własnym slugiem** (1.12.2): `/pl/home` (slug strony przypisanej jako
|
||||
Homepage) → 308 na `/pl` — jeden adres strony (canonical i tak wskazywał root; Search Console
|
||||
zgłaszało duplikat). Wyłączenie: `createPageRoute(…, { homeAlias: false })`.
|
||||
|
||||
Ręcznie (pełny plik — gdy potrzebujesz czegoś, czego `createNotFoundPage` nie ma):
|
||||
|
||||
```tsx
|
||||
|
||||
@@ -41,6 +41,11 @@ pierwsze akapity bez nagłówków, całe zdania do ~155 znaków). Nigdy nie nadp
|
||||
tego, co edytor wpisał ręcznie; przy częściowym zapisie (REST PATCH,
|
||||
`payload.update` z kilkoma polami) czyta zapisany opis z dokumentu.
|
||||
|
||||
Skrypt, który ma zapisać dokładnie to, co ustawia (migracja danych, uzupełnianie pól na
|
||||
produkcji): `payload.update({ …, context: { [SKIP_AUTO_FILL]: true } })` — `SKIP_AUTO_FILL`
|
||||
(`'ipalSkipAutoFill'`) z `@intecion/ipal-kit` wyłącza auto-fill meta i `aiSummary` dla tego
|
||||
zapisu (1.12.2).
|
||||
|
||||
Pod polem opisu w tabie SEO stoi podpowiedź (`MetaDescriptionCheck`, `/admin`):
|
||||
opis pusty, taki sam jak `siteDescription` z Site Settings albo taki sam jak w innym
|
||||
dokumencie kolekcji. Tylko informuje — zapisu nie blokuje. Długość pokazuje licznik
|
||||
|
||||
@@ -61,6 +61,16 @@ działa tylko bez env R2.
|
||||
- **Brak zmiennych** → fallback na lokalny dysk (dev działa bez R2, zero konfiguracji).
|
||||
- **Część zmiennych** → ostrzeżenie w logu + fallback (częściowa konfiguracja =
|
||||
pewnie pomyłka).
|
||||
- **Tylko `R2_PUBLIC_URL`** (absolutny, poza produkcją) → **media tylko do odczytu** (1.12.2):
|
||||
adresy plików z domeny mediów, upload i usuwanie zablokowane (403). Do lokalnego deva
|
||||
podpiętego pod bazę produkcyjną — widać obrazy, a nic nie trafia do prawdziwego bucketa.
|
||||
|
||||
**Import map nie zależy od env (1.12.2).** Gdy projekt wstrzykuje `s3Storage`, adapter jest
|
||||
rejestrowany zawsze — bez R2 jako wyłączony (`enabled: false`, dysk lokalny). storage-s3 i tak
|
||||
dopisuje wtedy swój `S3ClientUploadHandler` do import mapy, więc `pnpm dev` /
|
||||
`generate:importmap` bez `R2_*` zapisuje ten sam `importMap.js` co produkcja. Do 1.12.1 dev bez
|
||||
R2 usuwał ten wpis, a produkcyjny panel (z R2) renderował **pustą stronę** bez błędu w konsoli.
|
||||
`ipal-audit` zgłasza import mapę bez handlera.
|
||||
|
||||
To wzorzec „degrade gracefully" — jak mailAdapter, który wraca do SMTP, gdy brak
|
||||
Graph. Projekt działa niezależnie od tego, czy R2 jest skonfigurowany.
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@intecion/ipal-kit",
|
||||
"version": "1.12.1",
|
||||
"version": "1.12.3",
|
||||
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
|
||||
@@ -100,6 +100,20 @@ export const cookieSettingsFields: Field[] = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'detailLabels',
|
||||
type: 'group',
|
||||
admin: {
|
||||
description:
|
||||
'Labels of the cookie list in the detailed settings window (CookieBanner settings="detailed"). The list itself comes from Cookies below.',
|
||||
},
|
||||
fields: [
|
||||
{ name: 'cookies', type: 'text', admin: { description: 'Expander under each category, e.g. "Cookies used" — the count is added.' }, localized: true },
|
||||
{ name: 'provider', type: 'text', localized: true },
|
||||
{ name: 'purpose', type: 'text', localized: true },
|
||||
{ name: 'duration', type: 'text', localized: true },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'categories',
|
||||
type: 'array',
|
||||
@@ -122,7 +136,7 @@ export const cookieSettingsFields: Field[] = [
|
||||
type: 'array',
|
||||
admin: {
|
||||
description:
|
||||
'Cookies the site uses — shown on the cookie policy page (<CookieTable>). Fill it from a scan: ipal-consent-check → cookie-scan.',
|
||||
'Cookies the site uses — shown on the cookie policy page (<CookieTable>) and per category in the detailed settings window. Fill it from a scan: ipal-consent-check → cookie-scan.',
|
||||
initCollapsed: true,
|
||||
},
|
||||
fields: [
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { BasePayload } from 'payload'
|
||||
|
||||
type MongoGlobals = {
|
||||
collection?: {
|
||||
updateOne: (
|
||||
filter: Record<string, unknown>,
|
||||
update: Record<string, unknown>[],
|
||||
) => Promise<{ modifiedCount?: number }>
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 1.11.1 renamed Cookie Settings `buttons.save` → `buttons.savePreferences` (Mongoose
|
||||
* reserves `save`). MongoDB keeps the old key, but the first save of the global — panel
|
||||
* or script — rewrites the document without it, and the button text silently falls back
|
||||
* to "Save preferences" in every language. Runs once per start: copies the old value
|
||||
* (all locales at once) into the new field when the new one is still missing.
|
||||
* SQL adapters: the column rename happens in the migration (`migrate:create` → rename).
|
||||
*/
|
||||
export async function migrateCookieSettingsSaveButton(payload: BasePayload): Promise<void> {
|
||||
if (payload.db.name !== 'mongoose') {return}
|
||||
const globals = (payload.db as unknown as { globals?: MongoGlobals }).globals
|
||||
if (!globals?.collection) {return}
|
||||
try {
|
||||
const result = await globals.collection.updateOne(
|
||||
{
|
||||
'buttons.save': { $exists: true },
|
||||
'buttons.savePreferences': { $exists: false },
|
||||
globalType: 'cookie-settings',
|
||||
},
|
||||
[{ $set: { 'buttons.savePreferences': '$buttons.save' } }],
|
||||
)
|
||||
if (result.modifiedCount) {
|
||||
payload.logger.info('[ipal] Cookie Settings: buttons.save copied to buttons.savePreferences (1.11.1 rename).')
|
||||
}
|
||||
} catch (error) {
|
||||
payload.logger.error({ err: error, msg: '[ipal] Cookie Settings: could not migrate buttons.save → buttons.savePreferences' })
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -216,7 +216,7 @@ export { createLlmsTxtRoute, createManifestHandler, createSitemapRouteHandler }
|
||||
export { buildIconsMetadata, buildOrganizationJsonLd, sameAsUrls, validateFaviconField } from './modules/seo/index.js'
|
||||
export { buildNoindexField } from './modules/seo/index.js'
|
||||
export { buildSpeakableJsonLd } from './modules/seo/index.js'
|
||||
export { buildSummaryField } from './modules/seo/index.js'
|
||||
export { buildSummaryField, SKIP_AUTO_FILL } from './modules/seo/index.js'
|
||||
export { buildBreadcrumbJsonLd, buildNavigationJsonLd, buildSiteNavigationJsonLd, buildWebSiteJsonLd } from './modules/seo/index.js'
|
||||
// Local SEO structured data — LocalBusiness (map pack), Service (offering), FAQPage.
|
||||
export { buildFaqJsonLd, buildLocalBusinessJsonLd, buildServiceJsonLd } from './modules/seo/index.js'
|
||||
|
||||
@@ -32,6 +32,8 @@ export type CookieBannerClassNames = {
|
||||
categories?: string
|
||||
/** Settings view: one category row/card. */
|
||||
category?: string
|
||||
/** Detailed window: the card around one category (row + cookie list). */
|
||||
categoryCard?: string
|
||||
categoryDescription?: string
|
||||
categoryTitle?: string
|
||||
/** Settings dialog (modal mode): the ✕ button. */
|
||||
@@ -42,7 +44,19 @@ export type CookieBannerClassNames = {
|
||||
control?: string
|
||||
/** Settings view: the switch knob (controls="switch"). */
|
||||
controlThumb?: string
|
||||
/** Settings dialog box (modal mode). */
|
||||
/** Detailed window: one cookie in a category's list. */
|
||||
cookie?: string
|
||||
/** Detailed window: list of cookies under a category. */
|
||||
cookieList?: string
|
||||
/** Detailed window: provider / purpose / duration grid of one cookie. */
|
||||
cookieMeta?: string
|
||||
/** Detailed window: cookie name. */
|
||||
cookieName?: string
|
||||
/** Detailed window: <details> wrapping a category's cookie list. */
|
||||
cookies?: string
|
||||
/** Detailed window: the <summary> that expands the cookie list. */
|
||||
cookiesToggle?: string
|
||||
/** Settings dialog box (modal mode; detailed mode uses a wider default). */
|
||||
dialog?: string
|
||||
/** Small label above the banner title (CookieSettings → eyebrow). */
|
||||
eyebrow?: string
|
||||
@@ -111,12 +125,19 @@ const defaults: Required<CookieBannerClassNames> = {
|
||||
body: 'mx-auto max-w-4xl',
|
||||
categories: 'flex flex-col gap-3',
|
||||
category: 'flex items-start justify-between gap-4',
|
||||
categoryCard: `flex flex-col gap-3 ${radius} border p-4 ${border}`,
|
||||
categoryDescription: `text-xs ${mutedText}`,
|
||||
categoryTitle: `text-sm font-medium ${strongText}`,
|
||||
closeButton: `shrink-0 ${radius} p-1 ${mutedText} hover:bg-[var(--ipal-hover,#f5f5f5)] dark:hover:bg-[var(--ipal-hover-dark,#262626)]`,
|
||||
content: 'flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between',
|
||||
control: 'mt-1 h-4 w-4 shrink-0 accent-[var(--ipal-primary,#2563eb)]',
|
||||
controlThumb: 'pointer-events-none inline-block size-5 rounded-full bg-white shadow transition-transform translate-x-0.5 data-[checked=true]:translate-x-[1.375rem]',
|
||||
cookie: `flex flex-col gap-1 border-t pt-2 first:border-t-0 first:pt-0 ${border}`,
|
||||
cookieList: 'mt-3 flex flex-col gap-2',
|
||||
cookieMeta: `grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 text-xs ${mutedText}`,
|
||||
cookieName: `font-mono text-xs font-semibold ${strongText}`,
|
||||
cookies: 'group',
|
||||
cookiesToggle: `inline-flex cursor-pointer select-none items-center gap-1 text-xs font-medium ${accent} hover:underline [&::-webkit-details-marker]:hidden`,
|
||||
dialog: `relative max-h-[90vh] w-full max-w-2xl overflow-y-auto ${radius} border p-6 shadow-2xl ${surface} ${border}`,
|
||||
eyebrow: `mb-1 text-xs font-semibold uppercase tracking-wider ${accent}`,
|
||||
icon: `h-6 w-6 shrink-0 ${accent}`,
|
||||
@@ -137,6 +158,9 @@ const defaults: Required<CookieBannerClassNames> = {
|
||||
}
|
||||
|
||||
/** Default switch track (controls="switch") — the checkbox default doesn't fit a <button>. */
|
||||
/** Default dialog for settings="detailed" — wider and taller than the modal one. */
|
||||
const DETAILED_DIALOG = `relative max-h-[90vh] w-full max-w-4xl overflow-y-auto ${radius} border p-6 shadow-2xl sm:p-8 ${surface} ${border}`
|
||||
|
||||
const SWITCH_TRACK =
|
||||
'relative inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full bg-[var(--ipal-border,#d4d4d4)] transition-colors data-[checked=true]:bg-[var(--ipal-primary,#2563eb)] disabled:cursor-default disabled:opacity-60 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--ipal-primary,#2563eb)]'
|
||||
|
||||
@@ -155,10 +179,14 @@ type CookieBannerProps = {
|
||||
/** Banner buttons, in this order. Default ['settings', 'reject', 'accept']. */
|
||||
order?: CookieBannerAction[]
|
||||
/**
|
||||
* Where category settings open: in the banner itself (default) or in a centred
|
||||
* dialog over a dimmed page ('modal' — closes with ✕, Escape or a click outside).
|
||||
* Where category settings open:
|
||||
* - 'inline' (default) — in the banner itself;
|
||||
* - 'modal' — a centred dialog over a dimmed page (closes with ✕, Escape or a click outside);
|
||||
* - 'detailed' — like 'modal', but a large window: each category is a card with its
|
||||
* on/off control, description and an expandable list of its cookies (name, provider,
|
||||
* purpose, duration) from Cookie Settings → Cookies.
|
||||
*/
|
||||
settings?: 'inline' | 'modal'
|
||||
settings?: 'detailed' | 'inline' | 'modal'
|
||||
/** Buttons under the categories, in this order. Default ['back', 'save']. */
|
||||
settingsActions?: CookieSettingsAction[]
|
||||
}
|
||||
@@ -180,7 +208,8 @@ export function CookieBanner({
|
||||
const [showSettings, setShowSettings] = useState(false)
|
||||
const [choices, setChoices] = useState<Record<ConsentCategory, boolean>>(state)
|
||||
const closeRef = useRef<HTMLButtonElement>(null)
|
||||
const modal = settings === 'modal'
|
||||
const modal = settings !== 'inline'
|
||||
const detailed = settings === 'detailed'
|
||||
|
||||
useEffect(() => {
|
||||
setChoices(state)
|
||||
@@ -273,11 +302,68 @@ export function CookieBanner({
|
||||
)
|
||||
}
|
||||
|
||||
const cookieList = (cat: ConsentCategory) => {
|
||||
const rows = texts.cookies?.filter((row) => row.category === cat) ?? []
|
||||
const labels = texts.details
|
||||
if (!labels || rows.length === 0) {return null}
|
||||
return (
|
||||
<details className={cn('cookies')} data-ipal="cookies">
|
||||
<summary className={cn('cookiesToggle')}>
|
||||
<svg aria-hidden="true" className="transition-transform group-open:rotate-90" fill="none" height="14" stroke="currentColor" strokeLinecap="round" strokeWidth="2" viewBox="0 0 24 24" width="14">
|
||||
<path d="m9 18 6-6-6-6" />
|
||||
</svg>
|
||||
{labels.cookies} ({rows.length})
|
||||
</summary>
|
||||
<ul className={cn('cookieList')}>
|
||||
{rows.map((row) => (
|
||||
<li className={cn('cookie')} key={row.name}>
|
||||
<code className={cn('cookieName')}>{row.name}</code>
|
||||
<dl className={cn('cookieMeta')}>
|
||||
{row.provider && (
|
||||
<>
|
||||
<dt>{labels.provider}</dt>
|
||||
<dd>{row.provider}</dd>
|
||||
</>
|
||||
)}
|
||||
{row.purpose && (
|
||||
<>
|
||||
<dt>{labels.purpose}</dt>
|
||||
<dd>{row.purpose}</dd>
|
||||
</>
|
||||
)}
|
||||
{row.duration && (
|
||||
<>
|
||||
<dt>{labels.duration}</dt>
|
||||
<dd>{row.duration}</dd>
|
||||
</>
|
||||
)}
|
||||
</dl>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</details>
|
||||
)
|
||||
}
|
||||
|
||||
const categoryRow = (cat: ConsentCategory) => (
|
||||
<>
|
||||
<div>
|
||||
<p className={cn('categoryTitle')} id={`ipal-consent-${cat}`}>
|
||||
{texts.categories[cat].title}
|
||||
</p>
|
||||
<p className={cn('categoryDescription')} id={`ipal-consent-${cat}-desc`}>
|
||||
{texts.categories[cat].description}
|
||||
</p>
|
||||
</div>
|
||||
{control(cat)}
|
||||
</>
|
||||
)
|
||||
|
||||
const settingsView = (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<h2 className={cn('settingsTitle')} id="ipal-consent-title">
|
||||
{icon && !modal && <Cookie aria-hidden="true" className={cn('icon')} />}
|
||||
{icon && (!modal || detailed) && <Cookie aria-hidden="true" className={cn('icon')} />}
|
||||
{texts.settingsTitle}
|
||||
</h2>
|
||||
{modal && (
|
||||
@@ -290,19 +376,18 @@ export function CookieBanner({
|
||||
</div>
|
||||
{texts.settingsDescription && <p className={cn('settingsDescription')}>{texts.settingsDescription}</p>}
|
||||
<ul className={cn('categories')}>
|
||||
{CONSENT_CATEGORIES.map((cat) => (
|
||||
<li className={cn('category')} key={cat}>
|
||||
<div>
|
||||
<p className={cn('categoryTitle')} id={`ipal-consent-${cat}`}>
|
||||
{texts.categories[cat].title}
|
||||
</p>
|
||||
<p className={cn('categoryDescription')} id={`ipal-consent-${cat}-desc`}>
|
||||
{texts.categories[cat].description}
|
||||
</p>
|
||||
</div>
|
||||
{control(cat)}
|
||||
</li>
|
||||
))}
|
||||
{CONSENT_CATEGORIES.map((cat) =>
|
||||
detailed ? (
|
||||
<li className={cn('categoryCard')} data-ipal={`category-${cat}`} key={cat}>
|
||||
<div className={cn('category')}>{categoryRow(cat)}</div>
|
||||
{cookieList(cat)}
|
||||
</li>
|
||||
) : (
|
||||
<li className={cn('category')} key={cat}>
|
||||
{categoryRow(cat)}
|
||||
</li>
|
||||
),
|
||||
)}
|
||||
</ul>
|
||||
<div className={cn('settingsActions')}>{settingsActions.map(button)}</div>
|
||||
</div>
|
||||
@@ -321,7 +406,7 @@ export function CookieBanner({
|
||||
// klik w tło zamyka dialog; klawiatura: Escape (listener wyżej) i przycisk ✕
|
||||
role="presentation"
|
||||
>
|
||||
<div aria-labelledby="ipal-consent-title" aria-modal="true" className={cn('dialog')} data-ipal="consent-dialog" role="dialog">
|
||||
<div aria-labelledby="ipal-consent-title" aria-modal="true" className={classNames?.dialog ?? (detailed ? DETAILED_DIALOG : defaults.dialog)} data-ipal="consent-dialog" role="dialog">
|
||||
{settingsView}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { BasePayload } from 'payload'
|
||||
|
||||
import type { I18nConfig } from '../i18n/index.js'
|
||||
import type { ConsentTexts } from './texts.js'
|
||||
import type { ConsentTexts, CookieTableRow } from './texts.js'
|
||||
|
||||
import { resolveLocalized } from '../i18n/resolveLocalized.js'
|
||||
import { getSystemPagePath } from '../pages/index.js'
|
||||
@@ -28,6 +28,7 @@ const FALLBACK: ConsentTexts = {
|
||||
title: 'Necessary',
|
||||
},
|
||||
},
|
||||
details: { cookies: 'Cookies used', duration: 'Duration', provider: 'Provider', purpose: 'Purpose' },
|
||||
message:
|
||||
'We use cookies to run the site, analyze traffic, and improve your experience. You can accept all, reject non-essential, or choose which to allow.',
|
||||
privacyLink: null,
|
||||
@@ -40,12 +41,16 @@ const FALLBACK_PRIVACY_LABEL = 'Privacy policy'
|
||||
type CookieSettingsData = {
|
||||
alwaysActiveLabel?: null | string
|
||||
buttons?: ({
|
||||
/** Before 1.11.1 the field was `save` — still read, so old MongoDB data keeps working until re-saved. */
|
||||
save?: null | string
|
||||
/**
|
||||
* Before 1.11.1 the field was `save` — still read for old MongoDB data. Not in the schema any
|
||||
* more, so Payload doesn't flatten it: it comes back as the raw `{ pl, en }` map.
|
||||
*/
|
||||
save?: null | Record<string, string> | string
|
||||
savePreferences?: null | string
|
||||
} & Partial<Omit<ConsentTexts['buttons'], 'save'>>) | null
|
||||
categories?: Array<{ description?: null | string; key: string; title?: null | string }> | null
|
||||
cookies?: Array<{ category?: null | string; duration?: null | string; name?: null | string; provider?: null | string; purpose?: null | string }> | null
|
||||
detailLabels?: null | Partial<Record<keyof NonNullable<ConsentTexts['details']>, null | string>>
|
||||
eyebrow?: null | string
|
||||
message?: null | string
|
||||
policyVersion?: null | number
|
||||
@@ -146,10 +151,17 @@ export async function getConsentTexts({
|
||||
back: g.buttons?.back || FALLBACK.buttons.back,
|
||||
close: g.buttons?.close || FALLBACK.buttons.close,
|
||||
reject: g.buttons?.reject || FALLBACK.buttons.reject,
|
||||
save: g.buttons?.savePreferences || g.buttons?.save || FALLBACK.buttons.save,
|
||||
save: g.buttons?.savePreferences || resolveLocalized(g.buttons?.save, locale ?? '') || FALLBACK.buttons.save,
|
||||
settings: g.buttons?.settings || FALLBACK.buttons.settings,
|
||||
},
|
||||
categories,
|
||||
cookies: toCookieRows(g.cookies),
|
||||
details: {
|
||||
cookies: g.detailLabels?.cookies?.trim() || FALLBACK.details!.cookies,
|
||||
duration: g.detailLabels?.duration?.trim() || FALLBACK.details!.duration,
|
||||
provider: g.detailLabels?.provider?.trim() || FALLBACK.details!.provider,
|
||||
purpose: g.detailLabels?.purpose?.trim() || FALLBACK.details!.purpose,
|
||||
},
|
||||
message: g.message || FALLBACK.message,
|
||||
privacyLink,
|
||||
settingsTitle: g.settingsTitle || FALLBACK.settingsTitle,
|
||||
@@ -162,12 +174,19 @@ export async function getConsentTexts({
|
||||
}
|
||||
}
|
||||
|
||||
export type CookieTableRow = {
|
||||
category: ConsentCategory
|
||||
duration?: string
|
||||
name: string
|
||||
provider?: string
|
||||
purpose?: string
|
||||
export type { CookieTableRow } from './texts.js'
|
||||
|
||||
/** Named rows only; an unknown category falls back to necessary. */
|
||||
function toCookieRows(cookies: CookieSettingsData['cookies']): CookieTableRow[] {
|
||||
return (cookies ?? [])
|
||||
.filter((c) => typeof c.name === 'string' && c.name.trim())
|
||||
.map((c) => ({
|
||||
name: c.name!.trim(),
|
||||
category: (CONSENT_CATEGORIES as readonly string[]).includes(c.category ?? '') ? (c.category as ConsentCategory) : 'necessary',
|
||||
...(c.provider?.trim() ? { provider: c.provider.trim() } : {}),
|
||||
...(c.purpose?.trim() ? { purpose: c.purpose.trim() } : {}),
|
||||
...(c.duration?.trim() ? { duration: c.duration.trim() } : {}),
|
||||
}))
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -177,15 +196,7 @@ export type CookieTableRow = {
|
||||
export async function getCookieTable({ locale, payload }: { locale?: string; payload: BasePayload }): Promise<CookieTableRow[]> {
|
||||
try {
|
||||
const g = await getGlobal<CookieSettingsData>(payload, 'cookie-settings', { locale })
|
||||
return (g.cookies ?? [])
|
||||
.filter((c) => typeof c.name === 'string' && c.name.trim())
|
||||
.map((c) => ({
|
||||
name: c.name!.trim(),
|
||||
category: (CONSENT_CATEGORIES as readonly string[]).includes(c.category ?? '') ? (c.category as ConsentCategory) : 'necessary',
|
||||
...(c.provider?.trim() ? { provider: c.provider.trim() } : {}),
|
||||
...(c.purpose?.trim() ? { purpose: c.purpose.trim() } : {}),
|
||||
...(c.duration?.trim() ? { duration: c.duration.trim() } : {}),
|
||||
}))
|
||||
return toCookieRows(g.cookies)
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
|
||||
@@ -13,6 +13,20 @@ export type ConsentTexts = {
|
||||
settings: string
|
||||
}
|
||||
categories: Record<ConsentCategory, { description: string; title: string }>
|
||||
/**
|
||||
* Cookie Settings → Cookies in this language — listed per category in the
|
||||
* detailed settings window (<CookieBanner settings="detailed">). Optional so
|
||||
* hand-built texts keep compiling; getConsentTexts always fills it.
|
||||
*/
|
||||
cookies?: CookieTableRow[]
|
||||
/** Labels of the cookie list in the detailed settings window. No labels = no list. */
|
||||
details?: {
|
||||
/** Expander per category, e.g. "Cookies used" — the count is appended. */
|
||||
cookies: string
|
||||
duration: string
|
||||
provider: string
|
||||
purpose: string
|
||||
}
|
||||
/** Small label above the banner title (e.g. "Privacy & cookies"). Empty = not shown. */
|
||||
eyebrow?: string
|
||||
message: string
|
||||
@@ -26,3 +40,12 @@ export type ConsentTexts = {
|
||||
/** Policy version from the panel — a stored consent from another version asks again. */
|
||||
version?: number
|
||||
}
|
||||
|
||||
/** One row of Cookie Settings → Cookies, resolved to a single language. */
|
||||
export type CookieTableRow = {
|
||||
category: ConsentCategory
|
||||
duration?: string
|
||||
name: string
|
||||
provider?: string
|
||||
purpose?: string
|
||||
}
|
||||
|
||||
Vendored
+5
-3
@@ -74,9 +74,11 @@ export function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] {
|
||||
]
|
||||
|
||||
if (storage) {
|
||||
const r2Vars = ['R2_BUCKET', 'R2_ACCESS_KEY_ID', 'R2_SECRET_ACCESS_KEY', 'R2_ENDPOINT', 'R2_PUBLIC_URL']
|
||||
// Production: always. Development: only once any R2_* is set (all or nothing).
|
||||
const r2Required = process.env.NODE_ENV === 'production' || r2Vars.some((name) => Boolean(process.env[name]))
|
||||
const r2Credentials = ['R2_BUCKET', 'R2_ACCESS_KEY_ID', 'R2_SECRET_ACCESS_KEY', 'R2_ENDPOINT']
|
||||
// Production: always. Development: once any credential is set (all or nothing).
|
||||
// R2_PUBLIC_URL alone is the read-only media mode (buildR2Storage) — allowed in dev.
|
||||
const r2Required =
|
||||
process.env.NODE_ENV === 'production' || r2Credentials.some((name) => Boolean(process.env[name]))
|
||||
rules.push(
|
||||
{ name: 'R2_BUCKET', description: 'R2 bucket name', required: r2Required },
|
||||
{ name: 'R2_ACCESS_KEY_ID', description: 'R2 access key id', required: r2Required },
|
||||
|
||||
@@ -10,7 +10,7 @@ import { LocaleView } from '../pages/LocaleView.js'
|
||||
import { NotFoundLoader } from '../pages/NotFoundLoader.js'
|
||||
import { JsonLdGraph } from '../seo/JsonLdGraph.js'
|
||||
|
||||
type Helpers = Partial<Pick<ContentHelpers, 'getConstructionMode' | 'getSystemLinks'>> & Pick<
|
||||
type Helpers = Partial<Pick<ContentHelpers, 'getConstructionMode' | 'getHomeSlug' | 'getSystemLinks'>> & Pick<
|
||||
ContentHelpers,
|
||||
'generatePageMetadata' | 'generateStaticParams' | 'getConfiguredLocales' | 'getNotFoundPage' | 'getPageJsonLd' | 'i18n' | 'resolvePageRedirect' | 'resolveRoute'
|
||||
>
|
||||
@@ -26,6 +26,12 @@ export type PageRouteOptions = {
|
||||
blockProps?: (ctx: BlockPropsContext) => Promise<Record<string, unknown>> | Record<string, unknown>
|
||||
/** blockType → component (the project's registry). */
|
||||
blocks: BlockComponentMap
|
||||
/**
|
||||
* The homepage opened under its own slug (/pl/home): 'redirect' (default) — 308 to the
|
||||
* locale root, one URL per page (canonical already points there; Search Console reports
|
||||
* the alias as a duplicate otherwise). `false` — render it like any page.
|
||||
*/
|
||||
homeAlias?: 'redirect' | false
|
||||
/** Per-page JSON-LD (WebPage, breadcrumbs, FAQ…). Default true; options as getPageJsonLd. */
|
||||
jsonLd?: boolean | PageJsonLdOptions
|
||||
/** Field with the blocks. Default 'layout'. */
|
||||
@@ -76,7 +82,7 @@ type PageArgs = { params: Promise<{ locale?: string; slug?: string[] }> }
|
||||
* yourself with the same helpers (PROGRAMISTA §2.8) — nothing here is required.
|
||||
*/
|
||||
export function createPageRoute(helpers: Helpers, options: PageRouteOptions) {
|
||||
const { blockProps, blocks, jsonLd = true, layoutField = 'layout', notFound, onMissing = 'notFound', permanentRedirect, redirect, render } = options
|
||||
const { blockProps, blocks, homeAlias = 'redirect', jsonLd = true, layoutField = 'layout', notFound, onMissing = 'notFound', permanentRedirect, redirect, render } = options
|
||||
if (onMissing === 'redirectHome' && !redirect) {
|
||||
throw new Error("[ipal] createPageRoute: onMissing: 'redirectHome' needs `redirect` from 'next/navigation'.")
|
||||
}
|
||||
@@ -118,6 +124,14 @@ export function createPageRoute(helpers: Helpers, options: PageRouteOptions) {
|
||||
if (target) {return permanentRedirect(target)}
|
||||
return missing(locale, segments)
|
||||
}
|
||||
if (homeAlias === 'redirect' && route.type !== 'home' && segments.length && helpers.getHomeSlug) {
|
||||
const homeSlug = await helpers.getHomeSlug(locale)
|
||||
if (homeSlug && segments.join('/') === homeSlug) {
|
||||
const [home] = helpers.getSystemLinks ? await helpers.getSystemLinks(locale, ['homepage']) : []
|
||||
const multilingual = (helpers.i18n?.locales.length ?? 0) > 1
|
||||
return permanentRedirect(home?.href ?? (multilingual ? `/${locale}` : '/'))
|
||||
}
|
||||
}
|
||||
const doc = route.doc
|
||||
const extra = blockProps ? await blockProps({ doc, locale }) : {}
|
||||
const rendered = (
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { CollectionBeforeChangeHook } from 'payload'
|
||||
|
||||
import { blocksToMarkdown } from '../content/blocksToMarkdown.js'
|
||||
import { describeFromMarkdown } from './plainText.js'
|
||||
import { isAutoFillSkipped } from './skipAutoFill.js'
|
||||
|
||||
/**
|
||||
* Maps document fields to SEO meta fields for auto-fill.
|
||||
@@ -51,8 +52,8 @@ export function buildAutoFillMetaHook(mapping: AutoFillMapping = {}): Collection
|
||||
const contentField = mapping.content === undefined ? 'layout' : mapping.content
|
||||
const descriptionLength = mapping.descriptionLength ?? 155
|
||||
|
||||
return ({ data, originalDoc }) => {
|
||||
if (!data) {return data}
|
||||
return ({ context, data, originalDoc }) => {
|
||||
if (!data || isAutoFillSkipped(context)) {return data}
|
||||
|
||||
// plugin-seo stores meta as a group under `meta`
|
||||
const meta = (data.meta as Record<string, unknown> | undefined) ?? {}
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { Field, FieldHook, TextareaField } from 'payload'
|
||||
|
||||
import { blocksToMarkdown } from '../content/blocksToMarkdown.js'
|
||||
import { mdToPlain, truncate } from './plainText.js'
|
||||
import { isAutoFillSkipped } from './skipAutoFill.js'
|
||||
|
||||
type BuildSummaryFieldArgs = {
|
||||
/** Auto-fill from page content when the editor leaves it empty. Default true. */
|
||||
@@ -50,7 +51,8 @@ export function buildSummaryField(args: BuildSummaryFieldArgs = {}): Field {
|
||||
overrides = {},
|
||||
} = args
|
||||
|
||||
const autofillHook: FieldHook = ({ data, value }) => {
|
||||
const autofillHook: FieldHook = ({ context, data, value }) => {
|
||||
if (isAutoFillSkipped(context)) {return value}
|
||||
if (typeof value === 'string' && value.trim()) {return value} // never clobber a manual summary
|
||||
if (!data || typeof data !== 'object') {return value}
|
||||
const layout = (data as Record<string, unknown>)[layoutField]
|
||||
|
||||
@@ -49,6 +49,7 @@ export { collectSiteIndex } from './siteIndex.js'
|
||||
export type { CollectSiteIndexArgs, SiteIndexEntry } from './siteIndex.js'
|
||||
export { buildSitemapCss, DEFAULT_SITEMAP_CREDIT, SITEMAP_STYLE_PARAM } from './sitemapStyle.js'
|
||||
export type { SitemapStyleOptions } from './sitemapStyle.js'
|
||||
export { SKIP_AUTO_FILL } from './skipAutoFill.js'
|
||||
export { slugsAcrossLocales } from './slugsAcrossLocales.js'
|
||||
export type { SeoMeta, SeoOption } from './types.js'
|
||||
export { validateFaviconField } from './validateFavicon.js'
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* `payload.update({ …, context: { ipalSkipAutoFill: true } })` — the save fills nothing
|
||||
* automatically (meta title/description, AI summary). For data migrations and scripts that
|
||||
* must write exactly what they set, nothing generated on top. Same idea as Payload's
|
||||
* `context.disableRevalidate`.
|
||||
*/
|
||||
export const SKIP_AUTO_FILL = 'ipalSkipAutoFill'
|
||||
|
||||
export function isAutoFillSkipped(context: unknown): boolean {
|
||||
return Boolean(context && typeof context === 'object' && (context as Record<string, unknown>)[SKIP_AUTO_FILL])
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
import type { Plugin } from 'payload'
|
||||
import type { CollectionConfig, Plugin } from 'payload'
|
||||
|
||||
import { APIError } from 'payload'
|
||||
|
||||
type GenerateFileURL = (args: { filename: string; prefix?: string }) => string
|
||||
|
||||
@@ -16,6 +18,8 @@ export type S3StorageFactory = (options: {
|
||||
forcePathStyle: boolean
|
||||
region: string
|
||||
}
|
||||
/** false = registered but inactive: no S3 client, local disk, admin import map unchanged. */
|
||||
enabled?: boolean
|
||||
}) => Plugin
|
||||
|
||||
export type BuildR2StorageDeps = {
|
||||
@@ -58,17 +62,43 @@ export const buildR2Storage = (
|
||||
const accessKeyId = process.env.R2_ACCESS_KEY_ID
|
||||
const secretAccessKey = process.env.R2_SECRET_ACCESS_KEY
|
||||
|
||||
// Any missing → skip R2, fall back to local disk. Warn so it's not silent.
|
||||
const { s3Storage } = deps
|
||||
|
||||
// Any missing → local disk. The adapter is still REGISTERED (enabled: false) when the
|
||||
// project injects it: storage-s3 adds its admin client handler to the import map even
|
||||
// when disabled, so `pnpm dev` / `generate:importmap` without R2 env writes the same
|
||||
// importMap.js as production. Before 1.12.2 a no-op was returned here — an import map
|
||||
// generated in dev lacked S3ClientUploadHandler and the production admin rendered blank.
|
||||
if (!bucket || !endpoint || !accessKeyId || !secretAccessKey) {
|
||||
const readOnly = readOnlyPublicUrl({ accessKeyId, bucket, endpoint, secretAccessKey })
|
||||
const disabled: Plugin | undefined = s3Storage
|
||||
? s3Storage({
|
||||
bucket: bucket ?? '',
|
||||
collections: Object.fromEntries(collections.map((slug) => [slug, true as const])),
|
||||
config: {
|
||||
credentials: { accessKeyId: accessKeyId ?? '', secretAccessKey: secretAccessKey ?? '' },
|
||||
endpoint: endpoint ?? '',
|
||||
forcePathStyle: true,
|
||||
region: 'auto',
|
||||
},
|
||||
enabled: false,
|
||||
})
|
||||
: undefined
|
||||
return (config) => {
|
||||
// Only warn when SOME vars are set (partial config = likely a mistake).
|
||||
if (bucket || endpoint || accessKeyId || secretAccessKey) {
|
||||
if (readOnly) {
|
||||
console.warn(
|
||||
`[ipal] R2 storage: read-only media from ${readOnly} (R2_PUBLIC_URL without credentials) — ` +
|
||||
'uploads are disabled. Set all R2_* to upload, or none for local disk.',
|
||||
)
|
||||
} else if (bucket || endpoint || accessKeyId || secretAccessKey) {
|
||||
// Only warn when SOME vars are set (partial config = likely a mistake).
|
||||
console.warn(
|
||||
'[ipal] R2 storage: incomplete env (need R2_BUCKET, R2_ENDPOINT, ' +
|
||||
'R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY). Falling back to local disk.',
|
||||
)
|
||||
}
|
||||
return config
|
||||
const next = disabled ? disabled(config) : config
|
||||
return readOnly ? withReadOnlyMedia(next as Parameters<Plugin>[0], collections, readOnly) : next
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,7 +125,6 @@ export const buildR2Storage = (
|
||||
|
||||
// R2 env is complete → the adapter is required. Fail loudly at boot rather
|
||||
// than silently storing media on the container disk (lost on redeploy).
|
||||
const { s3Storage } = deps
|
||||
if (!s3Storage) {
|
||||
throw new Error(
|
||||
'[ipal] R2 storage: R2_* env is set but the S3 adapter was not injected. ' +
|
||||
@@ -121,3 +150,76 @@ export const buildR2Storage = (
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Read-only media: outside production, R2_PUBLIC_URL (absolute) with none of the
|
||||
* credentials → files are read from the public domain. For a local dev pointed at
|
||||
* a production database: images show, nothing can be uploaded to (or deleted from)
|
||||
* the real bucket. Returns the base URL, or null when the mode doesn't apply.
|
||||
*/
|
||||
function readOnlyPublicUrl(env: {
|
||||
accessKeyId?: string
|
||||
bucket?: string
|
||||
endpoint?: string
|
||||
secretAccessKey?: string
|
||||
}): null | string {
|
||||
if (process.env.NODE_ENV === 'production') {return null}
|
||||
if (env.accessKeyId || env.bucket || env.endpoint || env.secretAccessKey) {return null}
|
||||
const url = process.env.R2_PUBLIC_URL?.trim().replace(/\/$/, '')
|
||||
return url && /^https?:\/\/[^/\s]+/i.test(url) ? url : null
|
||||
}
|
||||
|
||||
type UploadDoc = {
|
||||
filename?: null | string
|
||||
sizes?: Record<string, { filename?: null | string; url?: null | string } | null>
|
||||
thumbnailURL?: null | string
|
||||
url?: null | string
|
||||
}
|
||||
|
||||
function withReadOnlyMedia(
|
||||
config: Parameters<Plugin>[0],
|
||||
collections: string[],
|
||||
publicUrl: string,
|
||||
): Parameters<Plugin>[0] {
|
||||
const fileUrl = (filename: string) => `${publicUrl}/${encodeURIComponent(filename)}`
|
||||
return {
|
||||
...config,
|
||||
collections: (config.collections ?? []).map((collection): CollectionConfig => {
|
||||
if (!collections.includes(collection.slug)) {return collection}
|
||||
return {
|
||||
...collection,
|
||||
hooks: {
|
||||
...collection.hooks,
|
||||
afterRead: [
|
||||
...(collection.hooks?.afterRead ?? []),
|
||||
({ doc }: { doc: UploadDoc }) => {
|
||||
if (!doc?.filename) {return doc}
|
||||
doc.url = fileUrl(doc.filename)
|
||||
if (doc.thumbnailURL) {
|
||||
const thumb = doc.sizes?.thumbnail?.filename
|
||||
doc.thumbnailURL = thumb ? fileUrl(thumb) : doc.url
|
||||
}
|
||||
for (const size of Object.values(doc.sizes ?? {})) {
|
||||
if (size?.filename) {size.url = fileUrl(size.filename)}
|
||||
}
|
||||
return doc
|
||||
},
|
||||
],
|
||||
beforeOperation: [
|
||||
...(collection.hooks?.beforeOperation ?? []),
|
||||
({ args, operation }) => {
|
||||
const req = (args as { req?: { file?: unknown } }).req
|
||||
if (operation === 'delete' || ((operation === 'create' || operation === 'update') && req?.file)) {
|
||||
throw new APIError(
|
||||
'Media is read-only here (R2_PUBLIC_URL without R2 credentials). Set all R2_* to upload or delete files.',
|
||||
403,
|
||||
)
|
||||
}
|
||||
return args
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { Config, Plugin } from 'payload'
|
||||
import type { IpalOptions, TotpPluginFactory } from './types.js'
|
||||
|
||||
import { buildCookieSettings } from './globals/CookieSettings/index.js'
|
||||
import { migrateCookieSettingsSaveButton } from './globals/CookieSettings/migrateSaveButton.js'
|
||||
import { buildNotifications } from './globals/Notifications/index.js'
|
||||
import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js'
|
||||
import { buildSiteSettings } from './globals/SiteSettings/index.js'
|
||||
@@ -303,6 +304,7 @@ export const ipalKit = (options: IpalOptions): Plugin => {
|
||||
const incomingOnInit = config.onInit
|
||||
config.onInit = async (payload) => {
|
||||
if (incomingOnInit) {await incomingOnInit(payload)}
|
||||
await migrateCookieSettingsSaveButton(payload)
|
||||
payload.logger.info('[ipal] Plugin initialized.')
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { BasePayload } from 'payload'
|
||||
|
||||
import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { migrateCookieSettingsSaveButton } from '../src/globals/CookieSettings/migrateSaveButton.js'
|
||||
import { getConsentTexts } from '../src/modules/consent/getConsentTexts.js'
|
||||
|
||||
function payloadWith(db: Record<string, unknown>, cookieSettings: Record<string, unknown> = {}) {
|
||||
return {
|
||||
db,
|
||||
findGlobal: vi.fn(async () => cookieSettings),
|
||||
logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn() },
|
||||
} as unknown as BasePayload
|
||||
}
|
||||
|
||||
describe('Cookie Settings buttons.save → savePreferences (1.12.2)', () => {
|
||||
test('MongoDB: copies the old value for every locale, only when the new field is missing', async () => {
|
||||
const updateOne = vi.fn(async () => ({ modifiedCount: 1 }))
|
||||
const payload = payloadWith({ name: 'mongoose', globals: { collection: { updateOne } } })
|
||||
await migrateCookieSettingsSaveButton(payload)
|
||||
expect(updateOne).toHaveBeenCalledWith(
|
||||
{ 'buttons.save': { $exists: true }, 'buttons.savePreferences': { $exists: false }, globalType: 'cookie-settings' },
|
||||
[{ $set: { 'buttons.savePreferences': '$buttons.save' } }],
|
||||
)
|
||||
expect(payload.logger.info).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('other adapters: nothing (the SQL migration renames the column)', async () => {
|
||||
const updateOne = vi.fn()
|
||||
await migrateCookieSettingsSaveButton(payloadWith({ name: 'sqlite', globals: { collection: { updateOne } } }))
|
||||
expect(updateOne).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('a failing update is logged, start continues', async () => {
|
||||
const payload = payloadWith({
|
||||
name: 'mongoose',
|
||||
globals: { collection: { updateOne: vi.fn(async () => { throw new Error('no rights') }) } },
|
||||
})
|
||||
await expect(migrateCookieSettingsSaveButton(payload)).resolves.toBeUndefined()
|
||||
expect(payload.logger.error).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('getConsentTexts: old field as the raw locale map (Mongo, not in the schema) → this locale', async () => {
|
||||
const payload = payloadWith({}, { buttons: { save: { de: 'Einstellungen speichern', pl: 'Zapisz ustawienia' } } })
|
||||
const config = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }, { code: 'de', label: 'DE' }] } as const
|
||||
const texts = await getConsentTexts({ config, locale: 'de', payload, privacyPolicy: false })
|
||||
expect(texts.buttons.save).toBe('Einstellungen speichern')
|
||||
})
|
||||
})
|
||||
@@ -30,6 +30,10 @@ describe('ipalEnvRules({ storage })', () => {
|
||||
expect(check({ ...base, NODE_ENV: 'development' })).not.toThrow()
|
||||
})
|
||||
|
||||
test('development: R2_PUBLIC_URL alone is the read-only media mode', () => {
|
||||
expect(check({ ...base, NODE_ENV: 'development', R2_PUBLIC_URL: 'https://media.acme.pl' })).not.toThrow()
|
||||
})
|
||||
|
||||
test('development: a partial R2 set is an error (all or nothing)', () => {
|
||||
expect(check({ ...base, NODE_ENV: 'development', R2_BUCKET: 'b' })).toThrow(/R2_ACCESS_KEY_ID is required/)
|
||||
})
|
||||
|
||||
@@ -351,6 +351,23 @@ describe('cookie table', () => {
|
||||
expect(await getCookieTable({ locale: 'pl', payload })).toEqual([
|
||||
{ name: '_ga', category: 'analytics', duration: '2 lata', provider: 'Google', purpose: 'Statystyki' },
|
||||
])
|
||||
|
||||
// the same rows feed the detailed settings window, with English labels until the panel has them
|
||||
const texts = await getConsentTexts({ config: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, locale: 'pl', payload, privacyPolicy: false })
|
||||
expect(texts.cookies).toEqual([{ name: '_ga', category: 'analytics', duration: '2 lata', provider: 'Google', purpose: 'Statystyki' }])
|
||||
expect(texts.details).toEqual({ cookies: 'Cookies used', duration: 'Duration', provider: 'Provider', purpose: 'Purpose' })
|
||||
|
||||
await payload.updateGlobal({
|
||||
slug: 'cookie-settings' as never,
|
||||
data: { detailLabels: { cookies: 'Używane ciasteczka', duration: 'Czas', provider: 'Dostawca', purpose: 'Cel' } } as never,
|
||||
locale: 'pl' as never,
|
||||
})
|
||||
expect((await getConsentTexts({ config: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, locale: 'pl', payload, privacyPolicy: false })).details).toEqual({
|
||||
cookies: 'Używane ciasteczka',
|
||||
duration: 'Czas',
|
||||
provider: 'Dostawca',
|
||||
purpose: 'Cel',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { createPageRoute } from '../src/modules/frontend/pageRoute.js'
|
||||
|
||||
const thrower = (code: string) => vi.fn((url?: string) => { throw new Error(`${code}${url ? ` ${url}` : ''}`) }) as unknown as (url?: string) => never
|
||||
|
||||
const helpers = (locales = ['pl', 'en']) =>
|
||||
({
|
||||
getHomeSlug: vi.fn(async () => 'home'),
|
||||
getPageJsonLd: vi.fn(async () => []),
|
||||
getSystemLinks: vi.fn(async (locale: string) => [{ href: `/${locale}`, role: 'homepage' }]),
|
||||
i18n: { defaultLocale: 'pl', locales: locales.map((code) => ({ code })) },
|
||||
resolvePageRedirect: vi.fn(async () => null),
|
||||
resolveRoute: vi.fn(async (_locale: string, segments: string[]) => ({
|
||||
type: segments.length ? 'page' : 'home',
|
||||
doc: { id: segments.length ? 'p1' : 'home', layout: [] },
|
||||
})),
|
||||
}) as never
|
||||
|
||||
const page = (segments: string[], locale = 'pl') => ({ params: Promise.resolve({ slug: segments, locale }) })
|
||||
const opts = { blocks: {}, notFound: thrower('NOT_FOUND'), permanentRedirect: thrower('308') }
|
||||
|
||||
describe('createPageRoute homeAlias (1.12.2)', () => {
|
||||
test('/pl/home → 308 /pl', async () => {
|
||||
await expect(createPageRoute(helpers(), opts).Page(page(['home']))).rejects.toThrow('308 /pl')
|
||||
})
|
||||
|
||||
test('the root and other pages render', async () => {
|
||||
await expect(createPageRoute(helpers(), opts).Page(page([]))).resolves.toBeTruthy()
|
||||
await expect(createPageRoute(helpers(), opts).Page(page(['kontakt']))).resolves.toBeTruthy()
|
||||
})
|
||||
|
||||
test('homeAlias: false renders the alias', async () => {
|
||||
await expect(createPageRoute(helpers(), { ...opts, homeAlias: false }).Page(page(['home']))).resolves.toBeTruthy()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { FieldHook } from 'payload'
|
||||
|
||||
import { describe, expect, test } from 'vitest'
|
||||
|
||||
import { buildAutoFillMetaHook } from '../src/modules/seo/autoFillMeta.js'
|
||||
import { buildSummaryField } from '../src/modules/seo/buildSummaryField.js'
|
||||
import { SKIP_AUTO_FILL } from '../src/modules/seo/skipAutoFill.js'
|
||||
|
||||
const layout = [{ blockType: 'content', body: 'Rekrutujemy pracowników do pracy w Holandii od ponad dziesięciu lat.' }]
|
||||
|
||||
describe('context.ipalSkipAutoFill (1.12.2)', () => {
|
||||
const summaryHook = (buildSummaryField() as { hooks: { beforeChange: FieldHook[] } }).hooks.beforeChange[0]
|
||||
const metaHook = buildAutoFillMetaHook()
|
||||
const run = (context: Record<string, unknown>) => ({
|
||||
meta: (metaHook({ context, data: { layout, meta: {}, title: 'Kontakt' } } as never) as { meta: Record<string, unknown> }).meta,
|
||||
summary: summaryHook({ context, data: { layout }, value: undefined } as never),
|
||||
})
|
||||
|
||||
test('default: summary and meta are generated', () => {
|
||||
const { meta, summary } = run({})
|
||||
expect(summary).toMatch(/Rekrutujemy/)
|
||||
expect(meta.title).toBe('Kontakt')
|
||||
})
|
||||
|
||||
test('skipped: nothing generated', () => {
|
||||
const { meta, summary } = run({ [SKIP_AUTO_FILL]: true })
|
||||
expect(summary).toBeUndefined()
|
||||
expect(meta).toEqual({})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,101 @@
|
||||
import type { Config } from 'payload'
|
||||
|
||||
import { s3Storage } from '@payloadcms/storage-s3'
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { buildR2Storage } from '../src/modules/storage/buildR2Storage.js'
|
||||
|
||||
const r2 = {
|
||||
R2_ACCESS_KEY_ID: 'k',
|
||||
R2_BUCKET: 'b',
|
||||
R2_ENDPOINT: 'https://acc.r2.cloudflarestorage.com',
|
||||
R2_PUBLIC_URL: 'https://media.acme.pl',
|
||||
R2_SECRET_ACCESS_KEY: 's',
|
||||
}
|
||||
const HANDLER = '@payloadcms/storage-s3/client#S3ClientUploadHandler'
|
||||
|
||||
function stub(env: Record<string, string>) {
|
||||
vi.unstubAllEnvs()
|
||||
for (const key of Object.keys(r2)) {vi.stubEnv(key, '')}
|
||||
for (const [k, v] of Object.entries(env)) {vi.stubEnv(k, v)}
|
||||
}
|
||||
|
||||
const baseConfig = (): Config =>
|
||||
({ collections: [{ slug: 'media', fields: [], upload: true }] }) as unknown as Config
|
||||
|
||||
/** Admin component paths the import map is generated from. */
|
||||
function adminDependencies(config: Config): string[] {
|
||||
const deps = (config.admin?.dependencies ?? {}) as Record<string, { path?: string }>
|
||||
return Object.values(deps).map((d) => d.path ?? '')
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('buildR2Storage — import map independent of env (1.12.2)', () => {
|
||||
test('no R2 env: storage-s3 registered disabled, its client handler still in admin dependencies', async () => {
|
||||
stub({ NODE_ENV: 'development' })
|
||||
const config = await buildR2Storage(['media'], { s3Storage })(baseConfig())
|
||||
expect(adminDependencies(config)).toContain(HANDLER)
|
||||
// still local disk: no adapter, no disableLocalStorage
|
||||
const media = config.collections?.find((c) => c.slug === 'media')
|
||||
expect((media?.upload as { disableLocalStorage?: boolean }).disableLocalStorage).toBeUndefined()
|
||||
})
|
||||
|
||||
test('full R2 env: same handler (the import maps match)', async () => {
|
||||
stub({ ...r2, NODE_ENV: 'production' })
|
||||
const config = await buildR2Storage(['media'], { s3Storage })(baseConfig())
|
||||
expect(adminDependencies(config)).toContain(HANDLER)
|
||||
})
|
||||
|
||||
test('no adapter injected and no R2 env: plain passthrough (local-disk projects)', async () => {
|
||||
stub({ NODE_ENV: 'development' })
|
||||
const config = await buildR2Storage(['media'])(baseConfig())
|
||||
expect(adminDependencies(config)).not.toContain(HANDLER)
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildR2Storage — read-only media (R2_PUBLIC_URL only, outside production)', () => {
|
||||
type Hooks = {
|
||||
afterRead: ((a: { doc: Record<string, unknown> }) => Record<string, unknown>)[]
|
||||
beforeOperation: ((a: { args: { req?: { file?: unknown } }; operation: string }) => unknown)[]
|
||||
}
|
||||
async function mediaHooks(env: Record<string, string>): Promise<Hooks | undefined> {
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
stub(env)
|
||||
const config = await buildR2Storage(['media'], { s3Storage })(baseConfig())
|
||||
return config.collections?.find((c) => c.slug === 'media')?.hooks as unknown as Hooks | undefined
|
||||
}
|
||||
|
||||
test('URLs point at the public domain, sizes included', async () => {
|
||||
const hooks = await mediaHooks({ NODE_ENV: 'development', R2_PUBLIC_URL: 'https://media.acme.pl/' })
|
||||
const doc = hooks!.afterRead[0]({
|
||||
doc: {
|
||||
filename: 'logo plik.png',
|
||||
sizes: { thumbnail: { filename: 'logo-400x300.png', url: '/api/media/file/logo-400x300.png' } },
|
||||
thumbnailURL: '/api/media/file/logo-400x300.png',
|
||||
url: '/api/media/file/logo plik.png',
|
||||
},
|
||||
})
|
||||
expect(doc.url).toBe('https://media.acme.pl/logo%20plik.png')
|
||||
expect(doc.thumbnailURL).toBe('https://media.acme.pl/logo-400x300.png')
|
||||
expect((doc.sizes as Record<string, { url: string }>).thumbnail.url).toBe('https://media.acme.pl/logo-400x300.png')
|
||||
})
|
||||
|
||||
test('uploads and deletes are refused, metadata edits pass', async () => {
|
||||
const hooks = await mediaHooks({ NODE_ENV: 'development', R2_PUBLIC_URL: 'https://media.acme.pl' })
|
||||
const guard = hooks!.beforeOperation[0]
|
||||
expect(() => guard({ args: { req: { file: {} } }, operation: 'create' })).toThrow(/read-only/)
|
||||
expect(() => guard({ args: { req: {} }, operation: 'delete' })).toThrow(/read-only/)
|
||||
expect(() => guard({ args: { req: {} }, operation: 'update' })).not.toThrow()
|
||||
})
|
||||
|
||||
test('not in production, not with credentials, not with a relative URL', async () => {
|
||||
expect(await mediaHooks({ NODE_ENV: 'production', R2_PUBLIC_URL: 'https://media.acme.pl' })).toBeUndefined()
|
||||
expect(await mediaHooks({ NODE_ENV: 'development', R2_PUBLIC_URL: '/media' })).toBeUndefined()
|
||||
const partial = await mediaHooks({ NODE_ENV: 'development', R2_BUCKET: 'b', R2_PUBLIC_URL: 'https://media.acme.pl' })
|
||||
expect(partial).toBeUndefined()
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user