From f809526f1d81a6577ccfab8f68a31589e08c8ee3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Mon, 19 Oct 2026 19:38:28 +0200 Subject: [PATCH] Page-filled form fields, links to entries, entry JSON-LD, R2-optional dev MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Forms: `values` on RenderForm / BuilderForm / useBuilderForm fills fields the page knows (chosen product variant, category) — read-only , in the SSR HTML, sent and validated like any field. prepareBuilderForm (/rsc) is the server half of RenderForm for client components whose values change in the browser; publicForm is exported so projects stop copying it. Links: buildLinkField({ relationTo: ['pages', 'categories', …] }) — a polymorphic relation; resolveLinkHref builds /{locale}/{archive}/{entry} from `archives`, which getLinkOptions in createContentHelpers fills from Site Settings. SEO: pageJsonLd.entries — the main JSON-LD node per content collection instead of BlogPosting; buildProductJsonLd emits an Offer only for a real price from the panel. Pages: createPageRoute / createNotFoundPage pass isFirst to blocks, so the first section carries the page's only h1. Fixes: ipalEnvRules({ storage: true }) requires R2_* in production only (development: optional, all or none); buildImagesConfig allows the app's own media on localhost outside production. Docs, CHANGELOG, PROGRAMISTA §6 (34–37), ipal-form and ipal-upgrade skills. Tests: builderForm, links, drafts (entries + archives), seo, media, env. Co-Authored-By: Claude Opus 5.5 --- docs/CHANGELOG.md | 24 ++++++ docs/agent/AGENT.md | 3 + docs/agent/skills/ipal-form/SKILL.md | 3 + docs/agent/skills/ipal-upgrade/SKILL.md | 5 ++ docs/dev/PROGRAMISTA.md | 4 + docs/env.md | 1 + docs/forms.md | 26 ++++++ docs/links.md | 9 +++ docs/pages.md | 3 + docs/seo.md | 12 +++ docs/storage.md | 5 +- src/exports/rsc.ts | 4 +- src/index.ts | 4 +- src/modules/env/ipalEnvRules.ts | 19 +++-- src/modules/forms/BuilderForm.tsx | 17 +++- src/modules/forms/RenderForm.tsx | 85 ++++++++++++++++---- src/modules/forms/useBuilderForm.ts | 29 ++++++- src/modules/frontend/createContentHelpers.ts | 46 ++++++++++- src/modules/frontend/pageRoute.tsx | 10 ++- src/modules/links/buildLinkField.ts | 14 ++-- src/modules/links/resolveLinkHref.ts | 25 +++++- src/modules/seo/buildProductJsonLd.ts | 69 ++++++++++++++++ src/modules/seo/index.ts | 1 + src/modules/storage/buildImagesConfig.ts | 29 ++++++- test/builderForm.test.ts | 50 +++++++++++- test/drafts.test.ts | 26 ++++++ test/env.test.ts | 36 +++++++++ test/integration.test.ts | 4 + test/links.test.ts | 18 +++++ test/media.test.ts | 11 ++- test/seo.test.ts | 13 +++ 31 files changed, 551 insertions(+), 54 deletions(-) create mode 100644 src/modules/seo/buildProductJsonLd.ts create mode 100644 test/env.test.ts diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 42c60d0..b13169b 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -8,6 +8,30 @@ 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.11.0 + +### Nowe +- **Pola formularza wypełniane przez stronę** — `values` w `RenderForm`, `BuilderForm` i `useBuilderForm` + (`{ subject: 'Pierścionek · białe złoto · 0,70 ct' }`): pole tylko do odczytu (`classNames.fixed`), w SSR, + wysyłane i walidowane jak każde inne. `prepareBuilderForm` (`/rsc`) — serwerowa połowa `RenderForm` dla + komponentu klienckiego ze zmiennymi wartościami (konfigurator); `publicForm` eksportowany. Koniec kopii `publicForm` w projektach. +- **Linki do wpisów kolekcji** — `buildLinkField({ relationTo: ['pages', 'categories', 'products'] })`; + `resolveLinkHref` / `resolveLink` / `resolveNav` budują `/{locale}/{archiwum}/{wpis}`, `getLinkOptions` podaje archiwa z Site Settings. +- **JSON-LD wpisów, które nie są artykułami** — `pageJsonLd.entries` (węzeł per kolekcja) i `buildProductJsonLd` + (`Offer` tylko z prawdziwą ceną). +- **`isFirst`** dla bloków z `createPageRoute` / `createNotFoundPage` — pierwsza sekcja niesie jedyny `h1`. + +### Poprawki +- `ipalEnvRules({ storage: true })`: `R2_*` wymagane na produkcji; w dev opcjonalne (media na dysku), ale wszystkie albo żadne. + Wcześniej dev bez R2 nie startował, więc projekty warunkowały `storage` same. +- `buildImagesConfig()`: poza produkcją dopuszcza media serwowane przez aplikację (`/api/media/file/**` na + `NEXT_PUBLIC_SERVER_URL`) i localhost (`dangerouslyAllowLocalIP`) — bez R2 obrazy w dev nie dawały 500. + +### Wymaga zmian w projekcie +- Usuń obejścia z PROGRAMISTA §6 poz. 34–37 (kopie `publicForm`, ręczne remotePatterns dla localhost, + warunkowe `storage`, własny graf JSON-LD wpisów). +- Zmiana `relationTo` linku na tablicę zmienia kształt danych istniejących linków — migracja (ipal-migrate-fields). + ## 1.10.1 ### Poprawki diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index 44dd185..65ccf76 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -780,6 +780,7 @@ projekcie → **ipal-plugin-gap**, nie kopia. | Potrzeba | Użyj | Doc | |---|---|---| | Link / CTA / plik do pobrania | `buildLinkField`, `buildLinksField` | links.md | +| Link do kategorii / produktu / wpisu | `buildLinkField({ relationTo: ['pages', 'categories'] })` — adres z archiwum | links.md | | Nagłówek i ustawienia sekcji | `buildSectionHeaderField`, `buildSectionSettingsField({ backgrounds })` | blocks.md | | Czytelne wiersze tablic | `rowLabel(['heading'], 'Feature')` (+ `generate:importmap`) | links.md | | Slug / noindex / opis dla AI | `buildSlugField`, `buildNoindexField`, `buildSummaryField` | slug.md, seo.md | @@ -804,6 +805,7 @@ projekcie → **ipal-plugin-gap**, nie kopia. | Formularz z panelu w bloku (kroki, radio, listy, daty) | `` (`/rsc`) | forms.md | | Wygląd formularzy | `formClasses.ts` (`BuilderFormClassNames`) — raz na projekt | forms.md | | Nietypowy markup formularza | `BuilderForm renderField` / `useBuilderForm` (`/client`) | forms.md | +| Pole wypełniane przez stronę (wariant produktu, kategoria) | `RenderForm values` / `prepareBuilderForm` + `BuilderForm values` | forms.md | | Wysyłka | `createSubmitAction({ getCachedPayload, headers })` (`/server`) | forms.md | | Teksty komunikatów i przycisków kroków | Notifications → `getFormTexts(locale)` | notifications.md | | Formularz w bazie | seed `ipal-form/resources/seed-form.template.ts` | forms.md | @@ -817,6 +819,7 @@ projekcie → **ipal-plugin-gap**, nie kopia. | Metadata, kanoniczne, hreflang, OG, X | `generatePageMetadata` (`createPageRoute` robi to sam) | seo.md | | sitemap / robots / manifest | `sitemapRoute`, `robots`, `manifest` | seo.md | | JSON-LD | `getSiteShell().jsonLd`, `getPageJsonLd`, `build*JsonLd`, `formatOpeningHours`, `sameAsUrls`, `` | seo.md | +| JSON-LD produktu / kategorii (wpis, który nie jest artykułem) | `pageJsonLd.entries` + `buildProductJsonLd` | seo.md | | llms.txt / llms-full / Markdown / MCP | `llmsRoute`, `llmsFullRoute`, `markdownRoute`, `mcpGET`/`mcpPOST`; `markdownAlternate: true`; `createProxy({ markdown: true })` | seo.md, content.md, mcp.md | | IndexNow | `ipalKit({ indexNow: true })` + `indexNowKeyRoute` | seo.md | | Wyszukiwarka | `createSearchRoute` | content.md | diff --git a/docs/agent/skills/ipal-form/SKILL.md b/docs/agent/skills/ipal-form/SKILL.md index 9aa6acb..b4501b0 100644 --- a/docs/agent/skills/ipal-form/SKILL.md +++ b/docs/agent/skills/ipal-form/SKILL.md @@ -68,6 +68,9 @@ własny typ pola, suwak): nie kopiuj silnika — w kolejności: 2. własny komponent na `useBuilderForm` — pełna kontrola nad markupem, ta sama logika (`resources/CustomForm.example.tsx`): `steps`, `step`, `next/back/goTo`, `submit`, `getInputProps / getTextareaProps / getSelectProps / getOptionProps`, `errors`, `TurnstileWidget`. +**Pole wypełniane przez stronę** (wybrany wariant produktu, kategoria, oferta): w panelu zwykłe pole tekstowe +(np. `subject`), w kodzie `RenderForm values={{ subject }}`; wartość zmieniana w przeglądarce → +`prepareBuilderForm` (serwer) + `` (klient). Nigdy kopia `publicForm` w projekcie (forms.md). Własny typ pola w panelu: `forms.fields: { mojTyp: { slug, fields } }` (blok form-buildera) + `renderField`; serwer przyjmie go jako tekst — potrzebujesz innej walidacji → **ipal-plugin-gap**. diff --git a/docs/agent/skills/ipal-upgrade/SKILL.md b/docs/agent/skills/ipal-upgrade/SKILL.md index b17f40c..df0dd81 100644 --- a/docs/agent/skills/ipal-upgrade/SKILL.md +++ b/docs/agent/skills/ipal-upgrade/SKILL.md @@ -38,6 +38,11 @@ własny `FormRenderer` przekazywał do HTML zakładkę Emails (adresy firmy) → przeglądarce (formularz: wysyłka + mail; strona: 200, 404, metadata). Postgres: `migrate:create` (nowe typy pól formularza i teksty w Notifications). +**→ 1.11.0 (PROGRAMISTA §6, poz. 34–37):** usuń obejścia — kopię `publicForm` (→ `RenderForm values` / +`prepareBuilderForm`), ręczne `remotePatterns`/`dangerouslyAllowLocalIP` (→ `buildImagesConfig()`), warunkowe +`storage` w `ipalEnvRules`, własny graf JSON-LD produktów (→ `pageJsonLd.entries` + `buildProductJsonLd`), +własny RenderBlocks dla `h1` (→ `isFirst`). Linki do wpisów: `buildLinkField({ relationTo: [...] })` z migracją danych. + ## 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. diff --git a/docs/dev/PROGRAMISTA.md b/docs/dev/PROGRAMISTA.md index 1b7c6cd..ff8fc88 100644 --- a/docs/dev/PROGRAMISTA.md +++ b/docs/dev/PROGRAMISTA.md @@ -545,6 +545,10 @@ Rób po jednej pozycji, buduj, sprawdzaj. Kolejność wg wagi: | 30 | **1.9.2** — layout składany ręcznie (ConsentProvider, TurnstileProvider, Analytics, JsonLdGraph, MediaPreconnect) | `` — te same opcje (banner, analytics, jsonLd, logEndpoint) | PROGRAMISTA §2.8 | | 31 | **1.9.2** — strona catch-all i `not-found.tsx` pisane ręcznie | `createPageRoute(content, {…})` / `createNotFoundPage(content, {…})` z `/rsc`; `revalidate` zostaje literałem | pages.md | | 32 | **1.9.2** — trasy llms/md/mcp/health/indexnow/manifest z konfiguracją w każdym pliku | re-eksport z `lib/content` (`llmsRoute`, `llmsFullRoute`, `markdownRoute`, `mcpGET`/`mcpPOST`, `healthRoute`, `indexNowKeyRoute`, `manifest`); `summaryField`, `mcp` raz w `createContentHelpers` | PROGRAMISTA §2.7 | +| 34 | **1.11.0** — kopia `publicForm`, własny renderer pola z wariantem / kontekstem | `RenderForm values` albo `prepareBuilderForm` + ``; usuń kopię | forms.md | +| 35 | **1.11.0** — dodatkowe relacje „kategorie” obok linków, linki do wpisów jako URL | `buildLinkField({ relationTo: ['pages', 'categories'] })` (migracja danych linków) | links.md | +| 36 | **1.11.0** — JSON-LD produktu / kategorii składany w projekcie, `jsonLd: false` | `pageJsonLd.entries` + `buildProductJsonLd`, z powrotem `jsonLd` w `createPageRoute` | seo.md | +| 37 | **1.11.0** — własny RenderBlocks w trasie strony tylko dla `h1` pierwszej sekcji; `storage` w `ipalEnvRules` warunkowany NODE_ENV; ręczne `remotePatterns` / `dangerouslyAllowLocalIP` dla localhost | `isFirst` z `createPageRoute`; `ipalEnvRules({ storage: true })`; `buildImagesConfig()` | pages.md, env.md, storage.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 diff --git a/docs/env.md b/docs/env.md index 67b9b63..c916c10 100644 --- a/docs/env.md +++ b/docs/env.md @@ -49,6 +49,7 @@ używasz). ```ts ipalEnvRules({ storage?: boolean, // R2_* (R2_BUCKET, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, R2_ENDPOINT, R2_PUBLIC_URL) + // produkcja: wymagane; dev: opcjonalne (media na dysku), ale wszystkie albo żadne (1.11.0) emailGraph?: boolean, // GRAPH_* (GRAPH_TENANT_ID, GRAPH_CLIENT_ID, GRAPH_CLIENT_SECRET, GRAPH_SENDER) turnstile?: boolean | { siteKeyVar?: string; secretVar?: string }, serverUrlVar?: string, // domyślnie 'NEXT_PUBLIC_SERVER_URL' diff --git a/docs/forms.md b/docs/forms.md index b62657a..eff27af 100644 --- a/docs/forms.md +++ b/docs/forms.md @@ -117,6 +117,32 @@ po przecinku (pusto = gdy tamto pole jest wypełnione / zaznaczone). Puste `fiel - Nowa grupa = kolumny `show_when_field` / `show_when_values` w tabelach bloków formularzy → po aktualizacji wygeneruj migrację (`payload migrate:create`). +### Wartości pól ze strony (`values`, 1.11.0) +Strona zna wartość pola, której nie wpisuje odwiedzający — wybrany wariant produktu, kategorię, ofertę. +Redaktor dodaje w formularzu zwykłe pole tekstowe (np. `subject`, „Dotyczy”), a strona je wypełnia: + +```tsx +// wartość znana na serwerze (kategoria „wkrótce”) + +``` +Pole z `values` jest pokazane tylko do odczytu (``, klasa `classNames.fixed`, `data-ipal="form-fixed"`), +wysyłane jak każde inne i walidowane przez serwer według definicji z panelu. Nazwy spoza formularza są pomijane. +Wartość jest w pierwszym HTML (SSR), nie dopiero po hydracji. + +Wartość zmieniana w przeglądarce (konfigurator): serwer przygotowuje formularz `prepareBuilderForm` (`/rsc`) — +publiczną część (`publicForm`, bez zakładki Emails), wyrenderowane bloki message i potwierdzenie, akcję przypiętą +do formularza i języka, cel przekierowania — a komponent kliencki renderuje `BuilderForm` z aktualnym `values`: + +```tsx +// serwer +const form = prepareBuilderForm({ form: catalog.inquiryForm, action: sendForm, locale }) + +// klient ('use client') + +``` +`publicForm(form)` (`/rsc`) — sama publiczna część dokumentu, gdy budujesz własny przekaz do klienta. Nigdy nie +przekazuj do przeglądarki surowego dokumentu formularza. + ### Formularz nietypowy — bez kopiowania silnika 1. `renderField` (BuilderForm w pliku `'use client'`) — podmienia wybrane pola: `renderField={({ field, defaultRender }) => field.name === 'budget' ? : undefined}`. diff --git a/docs/links.md b/docs/links.md index d57148b..a58fac1 100644 --- a/docs/links.md +++ b/docs/links.md @@ -55,6 +55,15 @@ Wartość linku: `type` (`internal` strona · `external` URL, `mailto:`, `tel:`, Plik do pobrania to link typu `file` — **nie** osobne pole `pdfUrl`. +## Linki do wpisów kolekcji (1.11.0) +Strona, kategoria, produkt — jedno pole: `buildLinkField({ relationTo: ['pages', 'categories', 'products'] })` +(polimorficzna relacja; jedna kolekcja = jak dotąd). Wpis kolekcji z `content` rozwiązuje się do +`/{locale}/{strona-archiwum}/{wpis}` — `resolveLink` / `resolveNav` / `getLinkOptions` z `lib/content` +same biorą archiwa z Site Settings (`archives: { categories: 'kategorie' }`). Bez lib/content: +`resolveLinkHref(link, { config, locale, archives, pagesSlug })`. Wpis bez przypisanego archiwum → `null` +(link się nie renderuje). Zmiana `relationTo` na tablicę zmienia kształt danych (`page` → `{ relationTo, value }`): +istniejące linki trzeba przenieść (ipal-migrate-fields). + ## href ```ts diff --git a/docs/pages.md b/docs/pages.md index 7169085..719e824 100644 --- a/docs/pages.md +++ b/docs/pages.md @@ -77,6 +77,9 @@ export default createNotFoundPage(content, { ``` Robi dokładnie to, co pełny plik poniżej (widok dla każdego języka + `LocaleView`, bez `headers()`). +Każdy blok strony dostaje `locale`, wynik `blockProps` i **`isFirst`** (1.11.0) — `true` dla pierwszej sekcji: +jej nagłówek jest jedynym `h1` strony (``), pozostałe dają `h2`. + Strona catch-all z tymi samymi helperami: `createPageRoute(content, { blocks, notFound, permanentRedirect, blockProps, render, jsonLd })` — PROGRAMISTA §2.8. `render` daje własny widok dla archiwum lub wpisu (`route.type`: `page | home | archive | entry`), reszta zostaje domyślna. diff --git a/docs/seo.md b/docs/seo.md index 0da9488..c3b4da4 100644 --- a/docs/seo.md +++ b/docs/seo.md @@ -1177,6 +1177,18 @@ Dopełnia Markdown/llms: asystent łatwiej wyciąga kluczową treść strony. WebPage / CollectionPage / BlogPosting (język, `dateModified`, obraz), BreadcrumbList z prawdziwej trasy (tytuły stron z panelu), FAQPage, gdy projekt zmapuje swój blok FAQ. W `[[...slug]]/page.tsx`: ``. +- **Wpisy, które nie są artykułami** (1.11.0): `pageJsonLd.entries` — główny węzeł per kolekcja zamiast + `BlogPosting`; okruszki i FAQ zostają z pluginu. Kontekst: `{ doc, url, image, description, siteName, archive, locale }`. + ```ts + createContentHelpers({ pageJsonLd: { entries: { + products: ({ doc, url, image, siteName }) => buildProductJsonLd({ name: String(doc.title), sku: String(doc.sku), url, image, brand: siteName, + price: doc.price?.amount ? { amount: doc.price.amount, currency: doc.price.currency, kind: 'from' } : null }), + categories: ({ doc, url, description }) => buildWebPageJsonLd({ type: 'CollectionPage', name: String(doc.title), url, description }), + } } }) + ``` + **`buildProductJsonLd({ name, url, sku, description, image, category, brand, price, availability })`** — Product; + `Offer` tylko z prawdziwą ceną z panelu (`kind: 'exact'` → `price`, `'from'` → `minPrice`); produkt „na zapytanie” + (bez ceny) nie dostaje `Offer` — szacowana cena w danych strukturalnych wprowadza w błąd. - **`buildNavigationJsonLd({ items: header.navItems, baseUrl, locale, config, homeSlug })`** — nawigacja z globala nagłówka (linki stron per język, tylko własna domena, bez duplikatów). Inny kształt globala: `getLink` / `getChildren`. diff --git a/docs/storage.md b/docs/storage.md index 04c7d3e..0f58f75 100644 --- a/docs/storage.md +++ b/docs/storage.md @@ -339,6 +339,9 @@ env, komponent podąża automatycznie. - `videoProps(resource, { mode: 'background' | 'player', poster, reducedMotion })`. - `buildMediaPlaceholderHook()` + `buildMediaPlaceholderField()` w Media — podgląd liczony przy uploadzie przez `sharp` z configu. Postgres: `migrate:create`. -- `buildImagesConfig()` → `next.config.ts images` (AVIF/WebP, `remotePatterns` z `R2_PUBLIC_URL`). +- `buildImagesConfig()` → `next.config.ts images` (AVIF/WebP, `remotePatterns` z `R2_PUBLIC_URL`). Poza produkcją + (1.11.0) także media serwowane przez aplikację — `/api/media/file/**` na `NEXT_PUBLIC_SERVER_URL` (dysk lokalny, + bez R2) — i `dangerouslyAllowLocalIP` dla localhost (Next 16 inaczej odrzuca prywatne IP). Opcje: `serverUrl`, + `production`, `publicUrl`, `extraHosts`. - `` z `/client` — iframe po kliknięciu. - `buildUploadSecurityHeaders()` → sandbox CSP dla `/api/media/file/*` (SVG z uploadu bez skryptów). diff --git a/src/exports/rsc.ts b/src/exports/rsc.ts index 4e84a24..92d8f79 100644 --- a/src/exports/rsc.ts +++ b/src/exports/rsc.ts @@ -14,8 +14,8 @@ export type { } from '../modules/blocks/index.js' export { CookieTable } from '../modules/consent/CookieTable.js' export type { CookieTableLabels } from '../modules/consent/CookieTable.js' -export { RenderForm } from '../modules/forms/RenderForm.js' -export type { RenderFormProps, SendFormAction } from '../modules/forms/RenderForm.js' +export { prepareBuilderForm, publicForm, RenderForm } from '../modules/forms/RenderForm.js' +export type { PrepareBuilderFormArgs, PreparedBuilderForm, RenderFormProps, SendFormAction } from '../modules/forms/RenderForm.js' // Layout wiring + catch-all page + 404 from lib/content helpers (optional — the // pieces stay available for a project that composes them itself). export { createNotFoundPage, createPageRoute } from '../modules/frontend/pageRoute.js' diff --git a/src/index.ts b/src/index.ts index 3b0efff..90fe984 100644 --- a/src/index.ts +++ b/src/index.ts @@ -108,7 +108,7 @@ export { required, } from './modules/forms/validators.js' export type { Rule } from './modules/forms/validators.js' -export type { ContentHelpers, PageJsonLdOptions, SiteShell } from './modules/frontend/createContentHelpers.js' +export type { ContentHelpers, EntryJsonLdContext, PageJsonLdOptions, SiteShell } from './modules/frontend/createContentHelpers.js' export { createContentHelpers } from './modules/frontend/index.js' // Healthcheck route (Coolify/Docker liveness with a real DB round-trip). export { createHealthRoute } from './modules/health/index.js' @@ -218,7 +218,7 @@ export { buildSummaryField } from './modules/seo/index.js' export { buildBreadcrumbJsonLd, buildNavigationJsonLd, buildSiteNavigationJsonLd, buildWebSiteJsonLd } from './modules/seo/index.js' // Local SEO structured data — LocalBusiness (map pack), Service (offering), FAQPage. export { buildFaqJsonLd, buildLocalBusinessJsonLd, buildServiceJsonLd } from './modules/seo/index.js' -export { buildArticleJsonLd, buildWebPageJsonLd, formatOpeningHours } from './modules/seo/index.js' +export { buildArticleJsonLd, buildProductJsonLd, buildWebPageJsonLd, formatOpeningHours } from './modules/seo/index.js' export { buildLlmsTxt } from './modules/seo/index.js' export { buildSitemapCss, buildSitemapXml, DEFAULT_SITEMAP_CREDIT, SITEMAP_STYLE_PARAM } from './modules/seo/index.js' export type { SitemapRouteOptions, SitemapStyleOptions } from './modules/seo/index.js' diff --git a/src/modules/env/ipalEnvRules.ts b/src/modules/env/ipalEnvRules.ts index aece439..8071f5d 100644 --- a/src/modules/env/ipalEnvRules.ts +++ b/src/modules/env/ipalEnvRules.ts @@ -16,7 +16,12 @@ export type IpalEnvFeatures = { secretVar?: string /** Override the site-URL var. Default 'NEXT_PUBLIC_SERVER_URL'. */ serverUrlVar?: string - /** R2 object storage (buildR2Storage). Adds the R2_* vars. */ + /** + * R2 object storage (buildR2Storage). Adds the R2_* vars — required in + * production (media on a container disk vanish on redeploy). Outside + * production they're optional (media go to the local disk), but a partial + * set is an error: buildR2Storage needs all of them. + */ storage?: boolean /** * Cloudflare Turnstile. true uses the common var names @@ -69,14 +74,18 @@ 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])) rules.push( - { name: 'R2_BUCKET', description: 'R2 bucket name' }, - { name: 'R2_ACCESS_KEY_ID', description: 'R2 access key id' }, - { name: 'R2_SECRET_ACCESS_KEY', description: 'R2 secret access key' }, - { name: 'R2_ENDPOINT', description: 'R2 S3 API endpoint URL', kind: 'url' }, + { name: 'R2_BUCKET', description: 'R2 bucket name', required: r2Required }, + { name: 'R2_ACCESS_KEY_ID', description: 'R2 access key id', required: r2Required }, + { name: 'R2_SECRET_ACCESS_KEY', description: 'R2 secret access key', required: r2Required }, + { name: 'R2_ENDPOINT', description: 'R2 S3 API endpoint URL', kind: 'url', required: r2Required }, { name: 'R2_PUBLIC_URL', description: 'Public base URL media is served from (custom domain of the bucket)', + required: r2Required, // Production: absolute URL (https://media.example.com). Outside production a // site-relative path ('/media') is accepted — buildR2Storage prefixes it with // NEXT_PUBLIC_SERVER_URL (e.g. a dev rewrite /media → bucket). diff --git a/src/modules/forms/BuilderForm.tsx b/src/modules/forms/BuilderForm.tsx index 01af198..c387429 100644 --- a/src/modules/forms/BuilderForm.tsx +++ b/src/modules/forms/BuilderForm.tsx @@ -18,7 +18,7 @@ import { useBuilderForm } from './useBuilderForm.js' export type BuilderFormClassNames = Partial< Record< | 'actions' | 'back' | 'checkbox' | 'checkboxLabel' | 'choice' | 'choiceInput' | 'choiceLabel' | 'choices' - | 'error' | 'field' | 'fieldFull' | 'fieldHalf' | 'fields' | 'form' | 'formError' | 'input' | 'label' + | 'error' | 'field' | 'fieldFull' | 'fieldHalf' | 'fields' | 'fixed' | 'form' | 'formError' | 'input' | 'label' | 'legend' | 'message' | 'next' | 'progress' | 'required' | 'select' | 'step' | 'stepDescription' | 'stepTitle' | 'submit' | 'success' | 'textarea' | 'turnstile', string @@ -51,6 +51,9 @@ export type BuilderFormProps = { turnstileTheme?: 'auto' | 'dark' | 'light' } & UseBuilderFormOptions +/** A page-supplied value (always a string from `values`) as text. */ +const fixedText = (value: unknown) => (typeof value === 'string' ? value : '') + const cx = (...c: (false | null | string | undefined)[]) => c.filter(Boolean).join(' ') || undefined /** @@ -108,6 +111,18 @@ export function BuilderForm({ const defaultField = (field: BuilderField, index: number): ReactNode => { if (field.blockType === 'message') {return
{messages[index]}
} + if (f.isFixed(field)) { + // Filled by the page (`values`): visible, not editable, sent with the form. + const id = f.fieldId(field) + return ( + <> + {field.label} + + {fixedText(f.values[field.name ?? ''])} + + + ) + } switch (field.blockType) { case 'checkbox': { const props = f.getInputProps(field) diff --git a/src/modules/forms/RenderForm.tsx b/src/modules/forms/RenderForm.tsx index ce4acde..313b776 100644 --- a/src/modules/forms/RenderForm.tsx +++ b/src/modules/forms/RenderForm.tsx @@ -38,11 +38,13 @@ export type RenderFormProps = { /** Notifications → form texts in this locale (getNotificationTexts(...).form). */ texts: BuilderFormTexts turnstileTheme?: 'auto' | 'dark' | 'light' + /** Values of fields the page already knows, by field name — read-only for the visitor, sent with the form. */ + values?: Record } /** Only what the browser needs. The Local API reads with overrideAccess, so the * document still carries Emails (recipient addresses) — those never leave the server. */ -function publicForm(form: BuilderFormDoc): BuilderFormDoc { +export function publicForm(form: BuilderFormDoc): BuilderFormDoc { return { id: form.id, analytics: form.analytics, @@ -54,27 +56,42 @@ function publicForm(form: BuilderFormDoc): BuilderFormDoc { } } +export type PrepareBuilderFormArgs = Pick< + RenderFormProps, + 'action' | 'converters' | 'form' | 'linkOptions' | 'locale' | 'richTextClassName' +> + +/** What the browser gets for a panel form — spread it into (plus texts, classNames, values). */ +export type PreparedBuilderForm = { + action: (values: Record, turnstileToken?: string) => Promise + confirmation: ReactNode + form: BuilderFormDoc + messages: Record + redirectHref: null | string +} + /** - * A panel form inside a block, in one line — server part of BuilderForm: + * The server half of RenderForm without the markup: the public part of the form, + * rendered message blocks and confirmation, the action bound to form + locale, + * the redirect target. For a client component that renders itself — + * e.g. with `values` that change in the browser (a product configurator): * - * + * // server + * const prepared = prepareBuilderForm({ form, action: sendForm, locale }) + * + * // client + * * - * Renders `message` blocks and the confirmation with RenderRichText, binds the - * action to the form and locale, resolves the redirect target, and passes the - * client only the public part of the form (never the Emails tab). + * Returns null for an unpopulated form (an id or nothing). */ -export function RenderForm({ +export function prepareBuilderForm({ action, - classNames, converters, form, linkOptions, locale, - requiredMark, richTextClassName, - texts, - turnstileTheme, -}: RenderFormProps) { +}: PrepareBuilderFormArgs): null | PreparedBuilderForm { if (!form || typeof form !== 'object') {return null} // never a placeholder form const rich = (data: unknown) => @@ -93,17 +110,51 @@ export function RenderForm({ : safeHref(form.redirect?.url) : null + return { + action: action.bind(null, String(form.id), locale), + confirmation: rich(form.confirmationMessage), + form: publicForm(form), + messages, + redirectHref, + } +} + +/** + * A panel form inside a block, in one line — server part of BuilderForm: + * + * + * + * Renders `message` blocks and the confirmation with RenderRichText, binds the + * action to the form and locale, resolves the redirect target, and passes the + * client only the public part of the form (never the Emails tab). + * + * `values` fill fields the page already knows (`{ subject: 'Brooches' }`): shown + * read-only and sent with the submission. Values that change in the browser: + * prepareBuilderForm + . + */ +export function RenderForm({ + action, + classNames, + converters, + form, + linkOptions, + locale, + requiredMark, + richTextClassName, + texts, + turnstileTheme, + values, +}: RenderFormProps) { + const prepared = prepareBuilderForm({ action, converters, form, linkOptions, locale, richTextClassName }) + if (!prepared) {return null} return ( ) } diff --git a/src/modules/forms/useBuilderForm.ts b/src/modules/forms/useBuilderForm.ts index 75b1adf..c3fec2d 100644 --- a/src/modules/forms/useBuilderForm.ts +++ b/src/modules/forms/useBuilderForm.ts @@ -23,6 +23,12 @@ export type UseBuilderFormOptions = { /** Redirect target resolved on the server (RenderForm). Falls back to the form's custom URL. */ redirectHref?: null | string texts: BuilderFormTexts + /** + * Fields the page fills, by name (e.g. `{ subject: 'Ring · white gold · 0.70 ct' }`): + * kept in sync when the prop changes, read-only in BuilderForm, sent like any + * field. Names not in the form are ignored (the server rejects unknown fields). + */ + values?: Record } /** @@ -40,7 +46,7 @@ export type UseBuilderFormOptions = { * * */ -export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref, texts }: UseBuilderFormOptions) { +export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref, texts, values: pageValues }: UseBuilderFormOptions) { const fields = useMemo(() => form.fields ?? [], [form.fields]) // Fields behind a failed "Show only when" are neither shown, validated nor sent. const visibleInputs = useCallback((values: Record) => inputFields(visibleFields(fields, values)), [fields]) @@ -65,7 +71,11 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref const f = useForm>({ errorFallback: texts.error, - initialValues: initialBuilderValues(fields), + // Page values are in the first render too — server HTML shows them before hydration. + initialValues: { + ...initialBuilderValues(fields), + ...Object.fromEntries(Object.entries(pageValues ?? {}).filter(([name]) => fields.some((field) => field.name === name))), + }, onSuccess: (_result, values) => { formAnalyticsOnSuccess(form.analytics)(_result, values) onSuccess?.(values) @@ -78,7 +88,19 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref submitAction, validate, }) - const { setErrors, setTurnstileToken } = f + const { setErrors, setField, setTurnstileToken } = f + + // Page-supplied values follow the prop (a configurator changes them in the browser). + const fixedNames = useMemo( + () => new Set(Object.keys(pageValues ?? {}).filter((name) => fields.some((field) => field.name === name))), + [pageValues, fields], + ) + const fixedKey = JSON.stringify(pageValues ?? {}) + useEffect(() => { + for (const name of fixedNames) {setField(name, pageValues?.[name] ?? '')} + }, [fixedKey, fixedNames, setField]) + /** True for a field whose value comes from the page (`values`) — show it, don't let the visitor edit it. */ + const isFixed = useCallback((field: BuilderField) => Boolean(field.name && fixedNames.has(field.name)), [fixedNames]) // Steps follow the answers: a Step whose condition fails drops out, later steps renumber. const steps = useMemo(() => { const shown = new Set(visibleFields(fields, f.values)) @@ -258,6 +280,7 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref getTextareaProps, goTo, isFirst, + isFixed, isLast, next, /** Message the server returned on success (Notifications → success). */ diff --git a/src/modules/frontend/createContentHelpers.ts b/src/modules/frontend/createContentHelpers.ts index 8126bf1..d5f52c8 100644 --- a/src/modules/frontend/createContentHelpers.ts +++ b/src/modules/frontend/createContentHelpers.ts @@ -19,6 +19,7 @@ import { createMarkdownRoute } from '../content/createMarkdownRenderer.js' import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js' import { MARKDOWN_PREFIX, markdownHref } from '../content/markdownNegotiation.js' import { resolveRedirect as resolveRedirectRaw } from '../content/resolveRedirect.js' +import { archiveFieldName } from '../content/types.js' import { createHealthRoute } from '../health/createHealthRoute.js' import { homeSlugFrom, resolveLink as resolveLinkRaw, resolveNav as resolveNavRaw, resolveSystemLinks } from '../links/resolveNav.js' import { createMcpRoute } from '../mcp/createMcpRoute.js' @@ -94,9 +95,30 @@ type CreateContentHelpersArgs = { summaryField?: string } +/** What an entry's own JSON-LD builder gets (PageJsonLdOptions.entries). */ +export type EntryJsonLdContext = { + /** Archive page of the entry (title, slug). */ + archive: Record + /** Meta description (SEO tab or the site's description). */ + description?: string + doc: Record + /** Absolute share-image URL. */ + image?: string + locale: string + siteName?: string + /** Absolute canonical URL of the entry. */ + url: string +} + export type PageJsonLdOptions = { /** BreadcrumbList (home › archive › page) from the real route. Default true. */ breadcrumbs?: boolean + /** + * The main node per content collection, instead of the article (`entryType`): + * `{ products: (ctx) => buildProductJsonLd({…}), categories: (ctx) => buildWebPageJsonLd({ type: 'CollectionPage', … }) }`. + * Return null to emit no main node. Breadcrumbs and FAQ still follow. + */ + entries?: Record null | Record> /** schema.org type of archive entries. Default 'BlogPosting'. */ entryType?: 'Article' | 'BlogPosting' | 'NewsArticle' /** @@ -270,7 +292,10 @@ export function createContentHelpers({ const image = meta.openGraph?.images?.[0]?.url const nodes: (null | Record)[] = [] - if (route.type === 'entry') { + const entryNode = route.type === 'entry' ? opts.entries?.[route.collection] : undefined + if (route.type === 'entry' && entryNode) { + nodes.push(entryNode({ archive: route.archive, description: meta.description, doc, image, locale, siteName, url })) + } else if (route.type === 'entry') { nodes.push( buildArticleJsonLd({ type: opts.entryType ?? 'BlogPosting', @@ -572,8 +597,23 @@ export function createContentHelpers({ /** Options for resolveLinkHref / resolveLink / RenderForm `linkOptions` in this locale. */ const getLinkOptions = async (locale: string): Promise => { - const homeSlug = await getHomeSlug(locale) - return { config: needI18n('getLinkOptions'), locale, ...(homeSlug ? { homeSlug } : {}) } + const settings = await getSettings(locale) + const homeSlug = homeSlugFrom(settings) + // Archive page per content collection → links to entries (categories, products…) resolve too. + const archives = Object.fromEntries( + (content?.collections ?? []).flatMap(({ slug }) => { + const archive = (settings as Record)[archiveFieldName(slug)] + const archiveSlug = archive && typeof archive === 'object' ? (archive as { slug?: unknown }).slug : undefined + return typeof archiveSlug === 'string' && archiveSlug ? [[slug, archiveSlug]] : [] + }), + ) + return { + config: needI18n('getLinkOptions'), + locale, + pagesSlug, + ...(homeSlug ? { homeSlug } : {}), + ...(Object.keys(archives).length ? { archives } : {}), + } } /** diff --git a/src/modules/frontend/pageRoute.tsx b/src/modules/frontend/pageRoute.tsx index 1b66b2b..2bc5584 100644 --- a/src/modules/frontend/pageRoute.tsx +++ b/src/modules/frontend/pageRoute.tsx @@ -17,7 +17,11 @@ type Helpers = Partial> & Pick< type BlockPropsContext = { doc: Record; locale: string } export type PageRouteOptions = { - /** Props for every block on top of `locale`, computed once per page — e.g. `{ formTexts, sendForm }` for form blocks. */ + /** + * Props for every block on top of `locale` and `isFirst` (true for the first + * section — its heading is the page's only h1), computed once per page — + * e.g. `{ formTexts, sendForm }` for form blocks. + */ blockProps?: (ctx: BlockPropsContext) => Promise> | Record /** blockType → component (the project's registry). */ blocks: BlockComponentMap @@ -97,7 +101,7 @@ export function createPageRoute(helpers: Helpers, options: PageRouteOptions) { ({ locale, ...extra })} + enhanceProps={({ index }) => ({ locale, ...extra, isFirst: index === 0 })} /> ) const custom = render ? await render({ blocks: rendered, locale, route, segments }) : undefined @@ -142,7 +146,7 @@ export function createNotFoundPage(helpers: Helpers, options: NotFoundPageOption const fb = typeof fallback === 'function' ? fallback(locale) : fallback if (!doc || !layout?.length) {return [locale, fb] as const} const extra = blockProps ? await blockProps({ doc, locale }) : {} - return [locale, ({ locale, ...extra })} key={locale} />] as const + return [locale, ({ locale, ...extra, isFirst: index === 0 })} key={locale} />] as const }), ), ) diff --git a/src/modules/links/buildLinkField.ts b/src/modules/links/buildLinkField.ts index eb2ffaf..1392e87 100644 --- a/src/modules/links/buildLinkField.ts +++ b/src/modules/links/buildLinkField.ts @@ -20,7 +20,7 @@ export type BuildLinkFieldOptions = { /** Field name. Default 'link'. */ name?: string /** Collection the "Page" option points at. Default 'pages'. */ - relationTo?: string + relationTo?: readonly string[] | string required?: boolean /** Upload collection for "File" links (PDF, documents). Default 'media'. */ uploadTo?: string @@ -50,6 +50,7 @@ export function buildLinkField({ required = false, uploadTo = 'media', }: BuildLinkFieldOptions = {}): GroupField { + const pageAdmin = { condition: (_: unknown, s: SiblingWithType) => s?.type === 'internal' } const fields: Field[] = [ { type: 'row', @@ -73,13 +74,10 @@ export function buildLinkField({ }, ], }, - { - name: 'page', - type: 'relationship', - admin: { condition: (_: unknown, s: SiblingWithType) => s?.type === 'internal' }, - relationTo, - required, - }, + // One collection → plain relation; several (pages + content entries) → polymorphic. + typeof relationTo === 'string' + ? { name: 'page', type: 'relationship', admin: pageAdmin, relationTo, required } + : { name: 'page', type: 'relationship', admin: pageAdmin, relationTo: [...relationTo], required }, { name: 'url', type: 'text', diff --git a/src/modules/links/resolveLinkHref.ts b/src/modules/links/resolveLinkHref.ts index 10e27c6..bf4e74a 100644 --- a/src/modules/links/resolveLinkHref.ts +++ b/src/modules/links/resolveLinkHref.ts @@ -1,5 +1,6 @@ import type { I18nConfig } from '../i18n/index.js' +import { buildEntryPath } from '../content/paths.js' import { buildLocalizedPath } from '../i18n/index.js' /** @@ -32,6 +33,12 @@ export type LinkValue = { } export type ResolveLinkHrefOptions = { + /** + * Archive page slug per content collection in this locale (`{ categories: 'kategorie' }`) — + * links to entries (buildLinkField({ relationTo: ['pages', 'categories'] })) become + * /{locale}/{archive}/{entry}. getLinkOptions in lib/content fills it from Site Settings. + */ + archives?: Record config: I18nConfig /** * Slug(s) of the homepage so it collapses to /{locale}. A per-locale map or a @@ -39,6 +46,8 @@ export type ResolveLinkHrefOptions = { */ homeSlug?: Record | string locale: string + /** The pages collection — links to it are page paths, other collections are entries. Default 'pages'. */ + pagesSlug?: string } /** @@ -54,7 +63,7 @@ export type ResolveLinkHrefOptions = { */ export function resolveLinkHref( link: LinkValue | null | undefined, - { config, homeSlug, locale }: ResolveLinkHrefOptions, + { archives, config, homeSlug, locale, pagesSlug = 'pages' }: ResolveLinkHrefOptions, ): null | string { if (!link) {return null} @@ -69,12 +78,22 @@ export function resolveLinkHref( return null } - // internal (default) - const page = link.page + // internal (default) — a page, or (polymorphic relation) an entry of a content collection + let page = link.page + let collection = pagesSlug + if (page && typeof page === 'object' && 'relationTo' in page && 'value' in page) { + collection = String((page as { relationTo: unknown }).relationTo) + page = (page as { value: unknown }).value + } if (!page || typeof page !== 'object') {return null} const slug = (page as { slug?: unknown }).slug if (typeof slug !== 'string' || !slug) {return null} + if (collection !== pagesSlug) { + const archiveSlug = archives?.[collection] + return archiveSlug ? buildEntryPath({ archiveSlug, entrySlug: slug, locale }) : null + } + return ( buildLocalizedPath({ config, diff --git a/src/modules/seo/buildProductJsonLd.ts b/src/modules/seo/buildProductJsonLd.ts new file mode 100644 index 0000000..e041d7e --- /dev/null +++ b/src/modules/seo/buildProductJsonLd.ts @@ -0,0 +1,69 @@ +type ProductPrice = { + amount: number + currency: string + /** 'exact' → Offer.price; 'from' → minPrice (a starting price, not a promise). */ + kind?: 'exact' | 'from' +} + +type ProductJsonLdArgs = { + /** schema.org availability, e.g. 'MadeToOrder', 'InStock'. Default 'InStock' when a price is given. */ + availability?: string + brand?: string + category?: string + description?: string + /** Absolute image URL. */ + image?: string + name: string + /** Only a real price from the panel — no price (on request) → no Offer at all. */ + price?: null | ProductPrice + sku?: string + /** Absolute URL of the product page (also its @id). */ + url: string +} + +/** + * schema.org Product for a catalog entry: name, SKU, image, category, brand and — + * only when the panel has one — an Offer. A product "on request" gets no Offer: + * an invented or estimated price in structured data misleads search results. + * + * createContentHelpers({ pageJsonLd: { entries: { + * products: ({ doc, url, image }) => buildProductJsonLd({ name: doc.title, sku: doc.sku, url, image, … }), + * } } }) + */ +export function buildProductJsonLd({ + name, + availability, + brand, + category, + description, + image, + price, + sku, + url, +}: ProductJsonLdArgs): Record { + const offer = + price && Number.isFinite(price.amount) && price.currency + ? { + '@type': 'Offer', + availability: `https://schema.org/${availability ?? 'InStock'}`, + priceCurrency: price.currency, + url, + ...(price.kind === 'from' + ? { priceSpecification: { '@type': 'PriceSpecification', minPrice: price.amount, priceCurrency: price.currency } } + : { price: price.amount }), + } + : undefined + return { + name, + '@context': 'https://schema.org', + '@id': url, + '@type': 'Product', + url, + ...(sku ? { sku } : {}), + ...(description ? { description } : {}), + ...(image ? { image } : {}), + ...(category ? { category } : {}), + ...(brand ? { brand: { name: brand, '@type': 'Brand' } } : {}), + ...(offer ? { offers: offer } : {}), + } +} diff --git a/src/modules/seo/index.ts b/src/modules/seo/index.ts index f2d51a9..7adf86a 100644 --- a/src/modules/seo/index.ts +++ b/src/modules/seo/index.ts @@ -11,6 +11,7 @@ export { buildMetadata } from './buildMetadata.js' export type { PageMetadata } from './buildMetadata.js' export { buildNoindexField } from './buildNoindexField.js' export { buildOrganizationJsonLd, sameAsUrls } from './buildOrganizationJsonLd.js' +export { buildProductJsonLd } from './buildProductJsonLd.js' export { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, buildRobots } from './buildRobots.js' export type { RobotsOptions, RobotsRules } from './buildRobots.js' export { buildServiceJsonLd } from './buildServiceJsonLd.js' diff --git a/src/modules/storage/buildImagesConfig.ts b/src/modules/storage/buildImagesConfig.ts index 8effe76..5727617 100644 --- a/src/modules/storage/buildImagesConfig.ts +++ b/src/modules/storage/buildImagesConfig.ts @@ -1,6 +1,8 @@ type RemotePattern = { hostname: string; pathname?: string; port?: string; protocol?: 'http' | 'https' } export type ImagesConfig = { + /** Development only: lets next/image optimize files served by the app itself on localhost. */ + dangerouslyAllowLocalIP?: boolean formats: ('image/avif' | 'image/webp')[] minimumCacheTTL: number remotePatterns: RemotePattern[] @@ -11,15 +13,20 @@ export type ImagesConfig = { * - AVIF first, WebP fallback — ~20–50 % smaller than JPEG at the same quality; * - remotePatterns for the media domain (R2_PUBLIC_URL) so next/image may * optimize R2 files — otherwise it refuses them; - * - optimized images cached for 31 days (uploads get new names when replaced). + * - optimized images cached for 31 days (uploads get new names when replaced); + * - outside production, media served by the app itself (`/api/media/file/**` on + * NEXT_PUBLIC_SERVER_URL — local disk, no R2), including localhost, which + * Next 16 otherwise refuses as a private IP. * * import { buildImagesConfig } from '@intecion/ipal-kit' * export default withPayload({ images: { ...buildImagesConfig(), /* your overrides *\/ } }) */ export function buildImagesConfig({ extraHosts = [], + production = process.env.NODE_ENV === 'production', publicUrl = process.env.R2_PUBLIC_URL, -}: { extraHosts?: string[]; publicUrl?: string } = {}): ImagesConfig { + serverUrl = process.env.NEXT_PUBLIC_SERVER_URL, +}: { extraHosts?: string[]; production?: boolean; publicUrl?: string; serverUrl?: string } = {}): ImagesConfig { const remotePatterns: RemotePattern[] = [] if (publicUrl && /^https?:\/\//i.test(publicUrl)) { const u = new URL(publicUrl) @@ -31,5 +38,21 @@ export function buildImagesConfig({ }) } for (const host of extraHosts) {remotePatterns.push({ hostname: host, protocol: 'https' })} - return { formats: ['image/avif', 'image/webp'], minimumCacheTTL: 60 * 60 * 24 * 31, remotePatterns } + let localMedia = false + if (!production && serverUrl && /^https?:\/\//i.test(serverUrl)) { + const u = new URL(serverUrl) + remotePatterns.push({ + hostname: u.hostname, + protocol: u.protocol.replace(':', '') as 'http' | 'https', + ...(u.port ? { port: u.port } : {}), + pathname: '/api/media/file/**', + }) + localMedia = /^(?:localhost|127\.|10\.|192\.168\.|\[::1\])/.test(u.hostname) + } + return { + formats: ['image/avif', 'image/webp'], + minimumCacheTTL: 60 * 60 * 24 * 31, + remotePatterns, + ...(localMedia ? { dangerouslyAllowLocalIP: true } : {}), + } } diff --git a/test/builderForm.test.ts b/test/builderForm.test.ts index 8bd0136..350e102 100644 --- a/test/builderForm.test.ts +++ b/test/builderForm.test.ts @@ -6,7 +6,7 @@ import type { BuilderField, BuilderFormDoc } from '../src/modules/forms/builderT import { BuilderForm } from '../src/modules/forms/BuilderForm.js' import { autoCompleteFor, initialBuilderValues, splitSteps, stepOfField, validateBuilderFields } from '../src/modules/forms/builderLogic.js' -import { RenderForm } from '../src/modules/forms/RenderForm.js' +import { prepareBuilderForm, publicForm, RenderForm } from '../src/modules/forms/RenderForm.js' vi.mock('server-only', () => ({})) @@ -131,3 +131,51 @@ describe('RenderForm', () => { expect(RenderForm({ action: async () => ({ message: '', success: true }), form: 5, locale: 'pl', texts })).toBeNull() }) }) + +describe('page values (values prop) and prepareBuilderForm', () => { + const withSubject: BuilderFormDoc = { + id: 9, + fields: [ + { name: 'subject', blockType: 'text', label: 'Dotyczy' }, + { name: 'email', blockType: 'email', label: 'E-mail', required: true }, + ], + submitButtonLabel: 'Wyślij', + } + + test('a field filled by the page is read-only output in the first HTML, others stay inputs', () => { + const html = renderToStaticMarkup( + createElement(BuilderForm, { + action: async () => ({ message: 'ok', success: true }), + classNames: { fixed: 'fx' }, + form: withSubject, + texts, + values: { subject: 'Pierścionek · białe złoto', unknown: 'x' }, + }), + ) + expect(html).toContain(']*name="subject"/) + expect(html).toMatch(/]*name="email"/) + expect(html).not.toContain('unknown') + }) + + test('RenderForm passes values through', () => { + const action = async () => ({ message: 'ok', success: true }) + const html = renderToStaticMarkup( + createElement(RenderForm, { action, form: withSubject, locale: 'pl', texts, values: { subject: 'Broszki' } }), + ) + expect(html).toContain('Broszki') + }) + + test('prepareBuilderForm: public part only, bound action, null for an id', () => { + const doc = { ...withSubject, emails: [{ emailTo: 'firma@example.com' }] } as BuilderFormDoc + const action = vi.fn(async () => ({ message: 'ok', success: true })) + const prepared = prepareBuilderForm({ action, form: doc, locale: 'pl' }) + expect(JSON.stringify(prepared?.form)).not.toContain('firma@example.com') + expect(prepared?.form).toEqual(publicForm(doc)) + void prepared?.action({ email: 'a@b.pl' }) + expect(action).toHaveBeenCalledWith('9', 'pl', { email: 'a@b.pl' }) + expect(prepareBuilderForm({ action, form: '9', locale: 'pl' })).toBeNull() + }) +}) diff --git a/test/drafts.test.ts b/test/drafts.test.ts index 4579881..dbb8299 100644 --- a/test/drafts.test.ts +++ b/test/drafts.test.ts @@ -87,3 +87,29 @@ describe('noindex protection', () => { expect(updated.noindex).toBe(true) }) }) + +describe('content entries: own JSON-LD and links', () => { + test('pageJsonLd.entries replaces the article node; link options know the archives', async () => { + const { createContentHelpers } = await import('../src/modules/frontend/createContentHelpers.js') + const { buildProductJsonLd } = await import('../src/modules/seo/buildProductJsonLd.js') + const archive = await payload.create({ collection: 'pages' as never, data: { slug: 'wyroby', _status: 'published', title: 'Wyroby' } as never }) + await payload.updateGlobal({ slug: 'site-settings' as never, data: { postsArchive: archive.id, siteName: 'Acme' } as never }) + await payload.create({ collection: 'posts' as never, data: { slug: 'pierscionek', _status: 'published', title: 'Pierścionek' } as never }) + const h = createContentHelpers({ + baseUrl: 'https://acme.pl', + config: payload.config, + content: { collections: [{ slug: 'posts' }] }, + i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, + pageJsonLd: { + entries: { posts: ({ doc, siteName, url }) => buildProductJsonLd({ name: String(doc.title), brand: siteName, url }) }, + }, + }) + const nodes = await h.getPageJsonLd('pl', ['wyroby', 'pierscionek']) + expect(nodes.map((n) => n['@type'])).toEqual(['Product', 'BreadcrumbList']) + expect(nodes[0]).toMatchObject({ name: 'Pierścionek', brand: { name: 'Acme' } }) + expect(nodes[0]).not.toHaveProperty('offers') + const options = await h.getLinkOptions('pl') + expect(options.archives).toEqual({ posts: 'wyroby' }) + expect(await h.resolveLink({ type: 'internal', label: 'x', page: { relationTo: 'posts', value: { slug: 'pierscionek' } } }, 'pl')).toMatchObject({ href: '/pl/wyroby/pierscionek' }) + }) +}) diff --git a/test/env.test.ts b/test/env.test.ts new file mode 100644 index 0000000..1a7861b --- /dev/null +++ b/test/env.test.ts @@ -0,0 +1,36 @@ +import { afterEach, describe, expect, test, vi } from 'vitest' + +import { assertEnv } from '../src/modules/env/assertEnv.js' +import { ipalEnvRules } from '../src/modules/env/ipalEnvRules.js' + +const base = { DATABASE_URI: 'mongodb://db/x', NEXT_PUBLIC_SERVER_URL: 'http://localhost:3000', PAYLOAD_SECRET: 's' } +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', +} + +function check(env: Record) { + vi.unstubAllEnvs() + for (const [k, v] of Object.entries(env)) {vi.stubEnv(k, v)} + return () => assertEnv(ipalEnvRules({ storage: true }), { env }) +} + +afterEach(() => vi.unstubAllEnvs()) + +describe('ipalEnvRules({ storage })', () => { + test('production: every R2_* is required', () => { + expect(check({ ...base, NODE_ENV: 'production' })).toThrow(/R2_BUCKET is required/) + expect(check({ ...base, ...r2, NODE_ENV: 'production' })).not.toThrow() + }) + + test('development: no R2 at all is fine (local disk)', () => { + expect(check({ ...base, NODE_ENV: 'development' })).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/) + }) +}) diff --git a/test/integration.test.ts b/test/integration.test.ts index 381be12..9abc120 100644 --- a/test/integration.test.ts +++ b/test/integration.test.ts @@ -239,6 +239,10 @@ describe('one-call helpers — layout, page, GEO routes', () => { const route = createPageRoute(h(), { blocks: {}, notFound, permanentRedirect }) const el = (await route.Page({ params: Promise.resolve({ slug: ['uslugi'] }) })) as { props: { children: unknown[] } } expect(JSON.stringify(el.props.children[0])).toContain('Usługi') + // Blocks get the locale and whether they are the first section (the page's h1). + const blocksEl = el.props.children[1] as { props: { enhanceProps: (a: { allBlocks: never[]; block: never; index: number }) => Record } } + expect(blocksEl.props.enhanceProps({ allBlocks: [], block: {} as never, index: 0 })).toMatchObject({ isFirst: true, locale: 'pl' }) + expect(blocksEl.props.enhanceProps({ allBlocks: [], block: {} as never, index: 1 }).isFirst).toBe(false) await expect(route.Page({ params: Promise.resolve({ slug: ['nie-ma'] }) })).rejects.toThrow('NEXT_NOT_FOUND') expect((await route.generateMetadata({ params: Promise.resolve({ slug: ['uslugi'] }) })).alternates?.canonical).toBe('https://acme.pl/uslugi') }) diff --git a/test/links.test.ts b/test/links.test.ts index cdbe4af..602fff3 100644 --- a/test/links.test.ts +++ b/test/links.test.ts @@ -1,6 +1,8 @@ import { describe, expect, test } from 'vitest' import { buildSectionHeaderField, buildSectionSettingsField } from '../src/modules/blocks/sectionFields.js' +import { buildLinkField } from '../src/modules/links/buildLinkField.js' +import { resolveLinkHref } from '../src/modules/links/resolveLinkHref.js' import { homeSlugFrom, resolveLink, resolveNav } from '../src/modules/links/resolveNav.js' const config = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }, { code: 'en', label: 'EN' }] } as const @@ -104,3 +106,19 @@ describe('resolveSystemLinks', () => { expect(resolveSystemLinks(null, opts)).toEqual([]) }) }) + +describe('links to content entries (polymorphic page relation)', () => { + test('buildLinkField with several collections makes a polymorphic relation', () => { + const field = buildLinkField({ relationTo: ['pages', 'categories'] }) + const page = JSON.stringify(field.fields) + expect(page).toContain('"relationTo":["pages","categories"]') + }) + + test('an entry resolves under its archive page; a page stays a page; no archive → null', () => { + const entry = { type: 'internal' as const, page: { relationTo: 'categories', value: { slug: 'pierscionki' } } } + const archives = { categories: 'kategorie' } + expect(resolveLinkHref(entry, { archives, config, locale: 'pl' })).toBe('/pl/kategorie/pierscionki') + expect(resolveLinkHref({ type: 'internal', page: { relationTo: 'pages', value: { slug: 'kontakt' } } }, { archives, config, locale: 'pl' })).toBe('/pl/kontakt') + expect(resolveLinkHref(entry, { config, locale: 'pl' })).toBeNull() + }) +}) diff --git a/test/media.test.ts b/test/media.test.ts index ae7538d..1e1e85e 100644 --- a/test/media.test.ts +++ b/test/media.test.ts @@ -57,12 +57,19 @@ describe('videoProps', () => { describe('buildImagesConfig', () => { test('AVIF/WebP and the R2 domain', () => { - expect(buildImagesConfig({ publicUrl: 'https://media.acme.pl/' })).toEqual({ + expect(buildImagesConfig({ production: true, publicUrl: 'https://media.acme.pl/', serverUrl: 'https://acme.pl' })).toEqual({ formats: ['image/avif', 'image/webp'], minimumCacheTTL: 2678400, remotePatterns: [{ hostname: 'media.acme.pl', pathname: '/**', protocol: 'https' }], }) - expect(buildImagesConfig({ publicUrl: '/media' }).remotePatterns).toEqual([]) + expect(buildImagesConfig({ production: true, publicUrl: '/media' }).remotePatterns).toEqual([]) + }) + + test('development without R2: the app\'s own media on localhost (private IP allowed)', () => { + const config = buildImagesConfig({ production: false, publicUrl: undefined, serverUrl: 'http://localhost:3000' }) + expect(config.remotePatterns).toEqual([{ hostname: 'localhost', pathname: '/api/media/file/**', port: '3000', protocol: 'http' }]) + expect(config.dangerouslyAllowLocalIP).toBe(true) + expect(buildImagesConfig({ production: false, serverUrl: 'https://staging.acme.pl' }).dangerouslyAllowLocalIP).toBeUndefined() }) }) diff --git a/test/seo.test.ts b/test/seo.test.ts index 85fa490..7f69a4c 100644 --- a/test/seo.test.ts +++ b/test/seo.test.ts @@ -288,3 +288,16 @@ describe('createPageMetadata — siteDescription fallback', () => { expect(metadata.description).toBeUndefined() }) }) + +describe('buildProductJsonLd', () => { + test('an Offer only for a real price; "from" is a minimum, not a price', async () => { + const { buildProductJsonLd } = await import('../src/modules/seo/buildProductJsonLd.js') + const base = { name: 'Pierścionek', url: 'https://acme.pl/pl/wyroby/p' } + expect(buildProductJsonLd(base)).not.toHaveProperty('offers') + expect(buildProductJsonLd({ ...base, price: { amount: 6900, currency: 'PLN', kind: 'exact' } }).offers).toMatchObject({ price: 6900, priceCurrency: 'PLN' }) + expect(buildProductJsonLd({ ...base, availability: 'MadeToOrder', price: { amount: 6900, currency: 'PLN', kind: 'from' } }).offers).toMatchObject({ + availability: 'https://schema.org/MadeToOrder', + priceSpecification: { minPrice: 6900 }, + }) + }) +})