Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1413e96731 | ||
|
|
e1431a7c49 |
@@ -8,6 +8,45 @@ 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.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
|
||||
|
||||
@@ -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`)
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -207,7 +207,7 @@ Teksty z panelu (**Cookie Settings**, per język) — puste pole = element się
|
||||
| `settingsDescription` | opis pod tytułem ustawień |
|
||||
| `alwaysActiveLabel` | znacznik przy „Niezbędne” zamiast wyłączonego przełącznika |
|
||||
| `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.
|
||||
|
||||
|
||||
@@ -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ŚĆ
|
||||
|
||||
@@ -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.2",
|
||||
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -40,8 +40,11 @@ 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
|
||||
@@ -146,7 +149,7 @@ 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,
|
||||
|
||||
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/)
|
||||
})
|
||||
|
||||
@@ -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