Merge pull request: packages and banners from the CMS, host injection, translation files and the contact form (#19)
Continuous Integration / check (push) Successful in 1m58s
Continuous Integration / build-test (push) Successful in 4m12s
Continuous Integration / deploy-test (push) Successful in 1m13s
Continuous Integration / lighthouse (push) Successful in 9m0s
Continuous Integration / deploy-production (push) Skipped

This commit was merged in pull request #19.
This commit is contained in:
2026-11-16 14:17:13 +01:00
235 changed files with 10366 additions and 1835 deletions
+69 -3
View File
@@ -3,6 +3,7 @@ name: Continuous Integration
# Branchstrategie (zie aidlc-docs/.../operations/deployment/deployment-plan.md):
# - Pull request → controles, geen deploy
# - Merge/push naar master → controles + automatisch naar test
# - Elke nacht (schedule) → controles + naar test, met de pakketten uit het CMS
# - Handmatig, elke branch → controles + naar test als 'Deploy to Test' aan staat
# - Handmatig, release/* → controles + naar productie als 'Deploy to Production' aan staat
on:
@@ -20,6 +21,12 @@ on:
types: [opened, synchronize, reopened]
push:
branches: [master]
# Elke nacht een testbuild, zodat een wijziging van de pakketten in het CMS
# op de testsite komt (de build haalt ze op). Alleen test, nooit productie.
# 03:15 UTC (04:15 of 05:15 Nederlandse tijd), buiten kantooruren en niet op
# een heel uur. Gitea draait schedules alleen vanaf de standaardbranch.
schedule:
- cron: '15 3 * * *'
# Alleen bij pull requests een verouderde run afbreken; een deploy wordt nooit
# halverwege gestopt.
@@ -84,6 +91,9 @@ jobs:
run: pnpm test
# Sentry toont bij elke fout uit welke commit de build komt
# Dit artefact (dist) is ook wat naar productie gaat: bewust zonder
# OFFERINGS_URL, dus met de gecommitte pakketlijst. De testbuild met de
# pakketten uit het CMS is job build-test.
- name: Build
run: pnpm build
env:
@@ -102,13 +112,68 @@ jobs:
path: web/dist/client/
retention-days: 7
# De build voor de testsite: zelfde code als dist, maar met de pakketten uit
# het CMS van de testomgeving (OFFERINGS_URL uit de repo-variabele
# ASF_OFFERINGS_URL_TEST). Productie krijgt dit artefact nooit: die blijft op
# dist met de gecommitte lijst tot er een productie-CMS is.
build-test:
needs: check
if: (github.event_name == 'workflow_dispatch' && github.event.inputs.deploy_test == 'true') || (github.event_name == 'push' && github.ref == 'refs/heads/master') || github.event_name == 'schedule'
runs-on: linux
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
- uses: pnpm/action-setup@v4
with:
package_json_file: web/package.json
- name: Get pnpm store directory
id: pnpm-store
run: echo "path=$(pnpm store path)" >> "$GITHUB_OUTPUT"
- name: Restore pnpm store
uses: actions/cache@v4
with:
path: ${{ steps.pnpm-store.outputs.path }}
key: pnpm-${{ hashFiles('web/pnpm-lock.yaml') }}
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Build (testomgeving, pakketten uit het CMS)
run: pnpm build
env:
VITE_RELEASE: ${{ github.sha }}
OFFERINGS_URL: ${{ vars.ASF_OFFERINGS_URL_TEST }}
# De testsite staat op zichzelf: canonical, og:url, og:image,
# JSON-LD en sitemap wijzen naar het eigen adres, zodat een gedeelde
# link (WhatsApp, Discord) ook zijn eigen plaatje toont. Alleen in
# deze testbuild; het productie-artefact (job check) krijgt de
# variabele niet en houdt https://andreaslop.nl.
VITE_SITE_URL: https://test.andreaslop.nl
# Het contactformulier staat alleen in deze testbuild open; standaard
# (en in het productie-artefact) is het dicht. Productie aanzetten
# vraagt Bryans expliciete go (docs/go-live-checklist.md).
VITE_CONTACT_FORM_ENABLED: 'true'
- name: Upload build artifact (test)
uses: actions/upload-artifact@v3
with:
name: dist-test
path: web/dist/client/
retention-days: 7
# Test wacht niet op Lighthouse: test is om te testen, de rapporten zie je
# achteraf. Lighthouse draait ernaast of erna (zie de volgorde bovenaan).
# Deploys alleen vanaf de Pi: die bereikt zichzelf zeker, en container-
# actions werken niet op Podman.
deploy-test:
needs: check
if: (github.event_name == 'workflow_dispatch' && github.event.inputs.deploy_test == 'true') || (github.event_name == 'push' && github.ref == 'refs/heads/master')
needs: [check, build-test]
if: (github.event_name == 'workflow_dispatch' && github.event.inputs.deploy_test == 'true') || (github.event_name == 'push' && github.ref == 'refs/heads/master') || github.event_name == 'schedule'
runs-on: raspberry-pi
steps:
- uses: actions/checkout@v4
@@ -121,7 +186,7 @@ jobs:
- name: Download build artifact
uses: actions/download-artifact@v3
with:
name: dist
name: dist-test
path: web/dist
# Alleen de clientmap hoort online: geen servermap, geen source maps
@@ -182,6 +247,7 @@ jobs:
# Lighthouse tegen de gebouwde site (mobiel en desktop)
lighthouse:
needs: check
if: github.event_name != 'schedule'
runs-on: linux
steps:
- uses: actions/checkout@v4
+1
View File
@@ -5,3 +5,4 @@ This file is the entry point for AI coding agents working in this repository. Pr
## Index
- [.ai/layout-conventions.md](.ai/layout-conventions.md) — how to build and update the Mermaid diagrams in [LAYOUT.md](LAYOUT.md).
- [README.md](README.md) and [docs/](docs/) — set-up and commands, [CMS integration](docs/cms-integration.md), [deploy and CI](docs/deploy-and-ci.md) and the [go-live checklist](docs/go-live-checklist.md), [translations](docs/translations.md) and the [assets and licences](docs/assets-and-licenses.md). New texts of the site go in `web/src/i18n/nl.json`, not in the components. Update them in the same change when you alter the packages or banners, the use of the CMS API, the workflow (inputs, jobs, triggers), the server config or the go-live conditions. Work that is not built through AI-DLC is documented there, not only in a commit message.
+29 -2
View File
@@ -1,9 +1,36 @@
# Andrea Slop Fotografie
Photography website made with .Net and React for Andrea Slop Fotografie.
Photography website made with .NET and React for Andrea Slop Fotografie. The site (in [web/](web/)) is a React single-page app (Vite, TanStack Start prerendering, Chakra UI v3) that is prerendered to static HTML at build time. On the test host it is served by the SLP CMS host (.NET), on production the same CMS host behind an IIS pass-through (planned): the host serves the pages, `/admin` and `/api/v1/*`.
## Set-up
### Pre-requisites
- Node.js 24 and pnpm (run every command in [web/](web/)).
- Chrome for the end-to-end checks (`pnpm e2e` uses the installed Chrome; CI uses Playwright's Chromium).
### Commands (in `web/`)
| Command | What it does |
| -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `pnpm install` | Installs the dependencies (also generates the Chakra types). |
| `pnpm dev` | Dev server. Set `API_PROXY_TARGET` (for example the ASF test host) to forward `/api` to a CMS host, so the contact form and the live packages work. |
| `pnpm build` | Fetches the packages and banners from the CMS (see [docs/cms-integration.md](docs/cms-integration.md)), type-checks, builds and prerenders into `dist/`. |
| `pnpm preview` | Serves `dist/` like the host does (headers, redirects). `--contact-stub` answers the contact and offerings API with a stub, as CI does. |
| `pnpm test` | Unit, component, property and axe tests with coverage (100% required for `src/lib/**`). |
| `pnpm e2e` | Real-browser checks against a built `dist/`. |
| `pnpm check` | Everything CI runs: lint, format, tests, build, e2e, audit and Lighthouse. |
| `pnpm server-config` | Regenerates `web/deploy/iis/web.config` and `web/deploy/nginx/*.conf`. Do not edit those by hand. |
## Lay-out
Lay-out of the website and its pages can be found in a sepoarate document [LAYOUT.md](LAYOUT.md)
Lay-out of the website and its pages can be found in a separate document [LAYOUT.md](LAYOUT.md).
## Documentation
- [docs/cms-integration.md](docs/cms-integration.md): packages and banners from the CMS, the API, the build step, live refresh and the reverse proxy.
- [docs/deploy-and-ci.md](docs/deploy-and-ci.md): the pipeline, the workflow inputs, deploying to test, the nightly build and the contact form switch.
- [docs/assets-and-licenses.md](docs/assets-and-licenses.md): where the images, icons and fonts come from and what is still to confirm about their licence.
- [docs/translations.md](docs/translations.md): where the texts of the site live (language files), how keys work and how a language is added.
- [docs/go-live-checklist.md](docs/go-live-checklist.md): what must be true before the CMS features and the contact form go to production.
- [aidlc-docs/](aidlc-docs/): the AI-DLC records per feature (requirements, design, decisions, audit). [aidlc-docs/active-features.md](aidlc-docs/active-features.md) lists them.
+18 -13
View File
@@ -1,15 +1,20 @@
# Active Features
| Type | Name | Status | Branch | Affected Components | Session Start |
|------|------|--------|--------|---------------------|---------------|
| Bug | [hero-carousel-announce-and-pause](bugs/hero-carousel-announce-and-pause/bug-fix.md) | ✅ Complete | fix/hero-carousel-announce-and-pause | web/src/components/Hero (Hero, HeroArrows, useHeroSlider) | 2026-10-19 |
| Feature | frontend-shell | ✅ Complete | feature/frontend-shell | web/src (AppShell, NavigationBar, Footer, Hero socials, new BackToTop/SkipLink/404/error pages, routes, theme.ts, main.tsx), web/vite.config.js, web/package.json | 2026-10-14 |
| Feature | homepage-sections | ✅ Complete | feature/homepage-sections | web/src/routes/index.tsx, new homepage section components, web/src/content (types + static content), possibly web/config/securityHeaders.ts (contact form) | 2026-10-19 |
| Feature | over-mij-page | ✅ Complete | feature/over-mij-page | web/src/routes/over-mij.tsx, web/src/content, possibly shared components (PageIntro, FramedImage, SectionHeading) and web/src/seo.ts | 2026-10-22 |
| Feature | soorten-fotoshoots-page | ✅ Complete | feature/soorten-fotoshoots-page | web/src/routes/soorten-fotoshoots.tsx, new web/src/content/shootTypes.ts, new web/src/assets/shoots/, new shared CallToAction, MediaText (reverse prop), Pricing (id="prijzen" only), siteContent (service area), own entries in sitePages.ts / lighthouserc.cjs, JSON-LD via the shared webPage() helper in seo.ts | 2026-10-24 |
| Feature | contact-page | ✅ Complete | feature/contact-page | web/src/routes/contact.tsx, web/src/content, possibly ContactForm/ContactSection, PageIntro, MediaText/FramedImage, web/src/seo.ts, sitePages/sitemap | 2026-10-24 |
| Feature | portfolio-page | ✅ Complete | feature/portfolio-page (based on master after over-mij merge; worktree ../AndreaSlopFotografie-portfolio) | web/src/routes/portfolio.tsx, web/src/content, new PortfolioGrid + Lightbox, InstagramGrid (moved to shared), own entries in sitePages.ts / lighthouserc.cjs, ImageGallery JSON-LD via the shared webPage() helper | 2026-10-24 |
| Feature | shoot-type-pages | ✅ Complete (content follow-up: [content-pending.md](features/shoot-type-pages/content-pending.md)) | feature/shoot-type-pages (worktree ../AndreaSlopFotografie-shoot-type-pages) | new route(s) per shoot type under web/src/routes, web/src/content (shootTypes.ts extension, timeline content), shared Timeline component, links from soorten-fotoshoots, seo.ts (webPage helper), sitePages.ts / sitemap, lighthouserc.cjs | 2026-10-29 |
| Feature | prerendering | ✅ Complete (merged, PR #14) | feature/prerendering (worktree ../AndreaSlopFotografie-prerendering) | web/vite.config.ts, web/src/main.tsx, web/index.html, web/config/serverConfig.ts + web/deploy, CI workflow, web/lighthouserc.cjs, possibly Reveal/useReveal and hooks using media queries | 2026-10-31 |
| Feature | testimonials-redesign | ✅ Complete (merged, PR #16) | feature/testimonials-redesign (worktree ../AndreaSlopFotografie-testimonials-redesign) | web/src/components/home/Testimonials (Testimonials, TestimonialSlide, TestimonialCarousel), web/src/recipes/carouselControl.ts, web/src/content (Testimonial type, testimonials.ts), possibly SectionHeading, LAYOUT.md, unit/e2e tests that reference the dots | 2026-11-05 |
| Feature | cms-api-foundation | ✅ Complete (merged PR #17, 2026-11-10; follow-ups: ASF production, contact feature) | feature/cms-api-foundation (worktree ../AndreaSlopFotografie-cms-api-foundation) | Cross-repo: feature briefs for the SlpModularCms repo (new Api.AndreaSlopFotografie client, per-site theming, per-site module set); in this repo only docs, later web integration (CMS serves the site) | 2026-11-05 |
| Type | Name | Status | Branch | Affected Components | Session Start |
| ------- | ------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- |
| Bug | [hero-carousel-announce-and-pause](bugs/hero-carousel-announce-and-pause/bug-fix.md) | ✅ Complete | fix/hero-carousel-announce-and-pause | web/src/components/Hero (Hero, HeroArrows, useHeroSlider) | 2026-10-19 |
| Feature | frontend-shell | ✅ Complete | feature/frontend-shell | web/src (AppShell, NavigationBar, Footer, Hero socials, new BackToTop/SkipLink/404/error pages, routes, theme.ts, main.tsx), web/vite.config.js, web/package.json | 2026-10-14 |
| Feature | homepage-sections | ✅ Complete | feature/homepage-sections | web/src/routes/index.tsx, new homepage section components, web/src/content (types + static content), possibly web/config/securityHeaders.ts (contact form) | 2026-10-19 |
| Feature | over-mij-page | ✅ Complete | feature/over-mij-page | web/src/routes/over-mij.tsx, web/src/content, possibly shared components (PageIntro, FramedImage, SectionHeading) and web/src/seo.ts | 2026-10-22 |
| Feature | soorten-fotoshoots-page | ✅ Complete | feature/soorten-fotoshoots-page | web/src/routes/soorten-fotoshoots.tsx, new web/src/content/shootTypes.ts, new web/src/assets/shoots/, new shared CallToAction, MediaText (reverse prop), Pricing (id="prijzen" only), siteContent (service area), own entries in sitePages.ts / lighthouserc.cjs, JSON-LD via the shared webPage() helper in seo.ts | 2026-10-24 |
| Feature | contact-page | ✅ Complete | feature/contact-page | web/src/routes/contact.tsx, web/src/content, possibly ContactForm/ContactSection, PageIntro, MediaText/FramedImage, web/src/seo.ts, sitePages/sitemap | 2026-10-24 |
| Feature | portfolio-page | ✅ Complete | feature/portfolio-page (based on master after over-mij merge; worktree ../AndreaSlopFotografie-portfolio) | web/src/routes/portfolio.tsx, web/src/content, new PortfolioGrid + Lightbox, InstagramGrid (moved to shared), own entries in sitePages.ts / lighthouserc.cjs, ImageGallery JSON-LD via the shared webPage() helper | 2026-10-24 |
| Feature | shoot-type-pages | ✅ Complete (content follow-up: [content-pending.md](features/shoot-type-pages/content-pending.md)) | feature/shoot-type-pages (worktree ../AndreaSlopFotografie-shoot-type-pages) | new route(s) per shoot type under web/src/routes, web/src/content (shootTypes.ts extension, timeline content), shared Timeline component, links from soorten-fotoshoots, seo.ts (webPage helper), sitePages.ts / sitemap, lighthouserc.cjs | 2026-10-29 |
| Feature | prerendering | ✅ Complete (merged, PR #14) | feature/prerendering (worktree ../AndreaSlopFotografie-prerendering) | web/vite.config.ts, web/src/main.tsx, web/index.html, web/config/serverConfig.ts + web/deploy, CI workflow, web/lighthouserc.cjs, possibly Reveal/useReveal and hooks using media queries | 2026-10-31 |
| Feature | testimonials-redesign | ✅ Complete (merged, PR #16) | feature/testimonials-redesign (worktree ../AndreaSlopFotografie-testimonials-redesign) | web/src/components/home/Testimonials (Testimonials, TestimonialSlide, TestimonialCarousel), web/src/recipes/carouselControl.ts, web/src/content (Testimonial type, testimonials.ts), possibly SectionHeading, LAYOUT.md, unit/e2e tests that reference the dots | 2026-11-05 |
| Feature | cms-api-foundation | ✅ Complete (merged PR #17, 2026-11-10; follow-ups: ASF production, contact feature) | feature/cms-api-foundation (worktree ../AndreaSlopFotografie-cms-api-foundation) | Cross-repo: feature briefs for the SlpModularCms repo (new Api.AndreaSlopFotografie client, per-site theming, per-site module set); in this repo only docs, later web integration (CMS serves the site) | 2026-11-05 |
| Feature | contact-form-cms | ✅ Complete (closed 2026-11-16; Operations in the joint production checklist; merges with asf-packages-cms) | feature/contact-form-cms (worktree ../AndreaSlopFotografie-contact-form) | web/src/components/ContactForm, ContactFormGate, web/src/contact (submitContactForm), new web/src/cms-client (copied headless package), web/config/securityHeaders.ts, content/siteContent contactForm switch | 2026-11-10 |
| Feature | asf-packages-cms | ✅ Complete (closed 2026-11-16; PR to master after the CMS PR; no production release) | feature/asf-packages-cms (worktree ../AndreaSlopFotografie-packages, based on feature/contact-form-cms) | web/config (offerings, fetchOfferings), web/src/content (packages, snapshot, types), Pricing + PriceBanner + PriceTopBar (two banners, centred card rows), PackagesProvider (live refresh), CI build-test job and nightly test build, docs/ (CMS integration, deploy and CI, go-live checklist) | 2026-11-12 |
| Feature | asf-cms-host-injection | ✅ Complete on the ASF side (2026-11-16, delivered with asf-packages-cms; host side by SMC) | feature/asf-packages-cms | web (PackagesProvider, build markers, neutral HTML), preview server stand-in injector, e2e/contract tests; host side in the SlpModularCms repo | 2026-11-15 |
| Feature | asf-translation-files | ✅ Complete on the ASF side (2026-11-16, delivered with asf-packages-cms) | feature/asf-packages-cms | web/src/i18n (nl.json, helpers), content modules, components, ESLint rules, baseline tool, docs/translations.md | 2026-11-15 |
| Feature | hero-module | 🔵 Inception (requirements questions to Bryan) | (none yet) | Hero as a manageable CMS module (SMC builds the module, ASF consumes it); LCP in the first HTML via host injection or prerender; static hero texts move into it | 2026-11-16 |
@@ -0,0 +1,22 @@
# AI-DLC State Tracking
## Project Information
- **Feature Name**: CMS host injects CMS data into the prerendered ASF pages
- **Feature Slug**: asf-cms-host-injection
- **Project Type**: Brownfield (cross-repo: this repo delivers markers, contract and golden files; SlpModularCms owns the injector)
- **Start Date**: 2026-11-15
- **Current Stage**: COMPLETE on the ASF side (closed 2026-11-16); delivered on branch feature/asf-packages-cms together with [asf-packages-cms](../asf-packages-cms/aidlc-state.md). Host side by SMC (CMS PR).
- **Plan**: [plan.md](plan.md) (approach agreed by Bryan, 2026-11-15)
## Language Configuration
- **Documentation Language**: English
- **Conversation Language**: User Language (Dutch)
## Stage Progress
- [x] INCEPTION - Requirements and plan (plan.md; decisions (a) brief look change accepted, (b) host writes the list HTML)
- [x] CONSTRUCTION - Code Generation: markers and regions, data block, hydration from the block, JSON-LD price, inline price, own address replacement, stand-in host in the preview server, golden files in `web/contract/host-injection/`, e2e tests, deployment-check normalisation
- [x] CONSTRUCTION - Build and Test: see the asf-packages-cms summary; end-to-end on ASF-test: SMC still to confirm (not part of closing the ASF side)
- [x] OPERATIONS - part of the joint production checklist (production needs IIS pass-through to the CMS host, separate feature)
@@ -0,0 +1,91 @@
# Plan (approach agreed, waiting for the start): the CMS host injects CMS data into the prerendered ASF pages
Status (2026-11-16): ASF side built and closed (see [aidlc-state.md](aidlc-state.md)); host side by SMC. Original status: plan, approach agreed 2026-11-15.
Decisions of Bryan (via SLS-Main, 2026-11-15):
- (a) A short change of look of the cards on first paint (neutral HTML first, then the styled cards after hydration) is ACCEPTED.
- (b) The host MAY write the list HTML (C# template; this repo delivers the spec and the golden files): YES.
It starts as a separate feature after the current merges (contact-form-cms, then asf-packages-cms), not through them. To be built together with SLP Modular CMS - SMC - Main, who owns the host side.
## Why
Hosting decision (2026-11-15): the CMS host is the one entry of the website and serves the prerendered pages, `/admin` and `/api/v1/*`; IIS passes everything to it. A CMS change (packages, banners, later gallery and hero) must then be visible to search engines at once, with no rebuild. The host injects the current data into the prerendered HTML through markers (as on SLP, 60 s cache).
## What is CMS data on the pages today
Packages: the price cards (home), the shoot list and shoot blocks, the "welke shoot" choices of the contact form, the `?pakket=` check, the offer price in the JSON-LD of the shoot pages. Banners: the slim top bar and the band under the cards. See [docs/cms-integration.md](../../../docs/cms-integration.md).
## Proposal
### 1. Three kinds of markers (built into the page by the ASF build, filled by the host)
- **Data block**, one per page: `<script type="application/json" id="cms-data">…</script>` holding the raw answers of `GET /api/v1/offerings` and both banners. The host replaces its content with the current answers (JSON-escaped: `<`, `>`, `&`, U+2028/2029). It is a non-executable block, so the CSP stays as it is and the build step that moves inline scripts treats it as data (as it does for `ld+json`).
- **Region**, for lists that differ in length (the cards, the banners): a wrapper `<div data-cms-region="offerings">` whose content is the neutral HTML. The host replaces everything between `<!--cms:offerings-->` and `<!--/cms:offerings-->` (written into the wrapper by the build; React cannot emit comments, so the build writes them through `dangerouslySetInnerHTML`).
- **Inline value**, for a single price or name inside a sentence: `<span data-cms-price="newborn">€ 185</span>`. The host replaces the text.
- **JSON-LD price** of a shoot page: the `ld+json` block gets `data-cms-offer="newborn"`; the host sets `offers.price` from the live package (or removes `offers` when the package is gone or has no readable price).
- The same marker format as SLP, if SLP already has one (to be confirmed by SMC).
### 2. Neutral HTML in the markers
The build puts crawlable, simple semantic HTML between the markers (package name, price, features, a plain link to `/?pakket=<slug>#contact`; the banner as an `aside`), written from the baked data by one pure function (`web/src/lib/neutralHtml.ts`, all text escaped). The host produces the same markup from live data (template in C#; the ASF repo delivers the spec and golden files, SMC implements, a contract test in each repo checks both sides against the same fixtures). Light static CSS in the page makes it look acceptable (the section is below the fold).
Why not exact copies of the styled cards: Chakra/Emotion class names and styles are generated at build time, a C# template cannot reproduce them.
### 3. Hydration: read the JSON, do not fetch
- `PackagesProvider` takes its initial state from the data block (reusing `mapOfferings`, `mapBanner`, `mapTopBanner`), not from the baked import and not from a fetch after hydration. Without a block (preview, tests, a host that does not inject) it falls back to the baked data plus the live fetch it has today, so nothing is lost.
- Regions are not hydrated by React (`dangerouslySetInnerHTML` with `suppressHydrationWarning`, so React keeps the server DOM). After hydration (`useHydrated`) the styled React components render into the region and replace the neutral HTML. So the first paint is the neutral HTML, and a brief change of look follows; the cards are below the fold, and the region keeps a minimum height to avoid a layout shift.
- Inline values hydrate directly from the same data (`suppressHydrationWarning` for the formatting difference).
- The contact form choices and `?pakket=` read the same state, so they agree with what the host injected.
### 4. Hydration and contract tests (per marker, before anything ships)
- Build test: every expected marker exists exactly once per page, in the final `dist/` (after the script-moving step), and the neutral HTML equals what the pure function gives.
- E2E in real Chrome with a stand-in injector in the preview server (same algorithm as the host, fixtures with more, fewer and different packages, with and without banners, an unreadable price, a hostile text such as `<script>`): no hydration or console error, the final DOM shows the injected data, the layout shift stays under the CLS limit.
- Fail-safe tests: marker missing, data block empty or invalid, host injection off: the page shows the baked data.
- Contract tests with golden fixtures shared with the CMS repo (marker format, escaping, the neutral HTML, the JSON-LD price edit).
- Security: all CMS text is HTML-escaped by the host; the data block is escaped as above; no executable inline script appears.
### 5. Build and deploy consequences
- The build no longer needs the CMS: the baked data is only the fallback, so `build-test` with `OFFERINGS_URL` and the nightly content build can go. One artifact can serve test and production.
- Optional: the test address (`VITE_SITE_URL`) could become a host replacement like SLP's `Website:AuthoredBaseUrl`, which would make the artifact identical for test and production. Needs the injector on ASF's prerendered-pages host; to ask SMC.
- Production deploy changes with the hosting: `dist/` goes to the CMS host's prerendered-pages folder (as on test). The generated IIS config reduces to redirects and pass-through. See the Hosting section of the CMS integration doc.
- The safety net of AI-DLC: a pipeline option (debounced rebuild after a CMS change) stays possible for build-processed gallery images later.
### 6. Hero and gallery later (separate plans, same mechanism)
- **Hero (LCP):** the first slide must be in the first HTML, with the image preloaded. The host injects the slide markup and a `<link rel="preload" as="image">` into a head marker; the client slider starts from the same first slide so nothing swaps. Own plan, because the carousel is interactive.
- **Gallery:** `figure` list with image URLs, sizes and alt texts in a region (crawlable), React adds lazy loading and the lightbox after hydration. Images are served same-origin by the CMS host (CSP `img-src 'self'`).
## Host contract (agreed with SMC, 2026-11-15; built after Bryan's approval)
The host (CMS repo) finds all markers in one pass. A page with no marker and without the written production address is served unchanged as a static file. **Fail open everywhere:** a missing marker does nothing, invalid or missing data leaves the baked page as it is, an unknown slug keeps the baked fallback.
1. **List regions** `<!--CMS:OFFERINGS-HTML-->…<!--/CMS:OFFERINGS-HTML-->`, and for the banners `<!--CMS:BANNER-TOP-HTML-->…<!--/CMS:BANNER-TOP-HTML-->` and `<!--CMS:BANNER-BOTTOM-HTML-->…<!--/CMS:BANNER-BOTTOM-HTML-->`: the host replaces the content between the markers by simple crawlable HTML from the live data (C# template, everything HTML-encoded); the markers stay. No live data or a provider error keeps the baked fallback. Spec and golden files below.
2. **Data** `<!--CMS:DATA-->` directly followed by the baked `<script type="application/json" id="cms-data">…</script>`: the host replaces the pair by the live block `{"siteUrl":"…","offerings":[…],"banners":{"top":…|null,"bottom":…|null}}` (offerings and banners exactly as the public GETs; `<`, `>`, `&`, U+2028 and U+2029 written as `\uXXXX` escapes). Without a block after the marker the live block replaces the marker. The block the build bakes carries `"source":"build"` (the host replaces the whole block, so the live one has no `source`); the site treats a block with that source as "no host data" and asks the API itself, as before the injection existed. `siteUrl` is the effective public base URL (see 5), which the client needs because the JS bundle cannot be rewritten (immutable assets).
3. **JSON-LD price** `<!--CMS:OFFER-JSON-LD slug="newborn"-->` directly before `<script type="application/ld+json">…</script>`: the host parses the block and sets `offers.price` (whole euros, our parsing: "€ 175", "€ 1.250", "175,-") on the node that has `offers`; when the package is gone, switched off, scheduled or has no readable price, `offers` is removed from that node. A database or provider failure is different: the baked block stays (fail open). A block that is not valid JSON stays. The marker comment is removed; property order is kept. Only the shoot pages of newborn, zwangerschap and gezin get this marker; loveshoot, portret ("Prijs op aanvraag"), the overview and the home page get none.
4. **Inline value** `<span data-cms-price="newborn">€ 185</span>`: the host replaces the text by "€" + U+00A0 + whole euros; an unknown slug or an unreadable price leaves the span alone. Only simple, non-nested spans with exactly this attribute. Used in the price block of a shoot page.
5. **Own address** (`Website:AuthoredBaseUrl`): the same injector replaces the written production address in every HTML page, `sitemap.xml` and `robots.txt` by `Website:PublicBaseUrl` when that is set on the host (test: `https://test.andreaslop.nl`; production: equal or empty, nothing to replace). One artifact then serves test and production, and `VITE_SITE_URL` no longer differs per environment. The ASF build is written with `https://andreaslop.nl` (the non-www canonical origin; IIS redirects www to it). The site has no web manifest. The client takes its address from `siteUrl` in the data block (fallback: the production address), not from the bundle, so canonical and `og:` tags stay right after hydration and on navigation.
6. **Caching:** injected pages get `Cache-Control: no-cache`, a strong ETag (hash of the final body), 304 on `If-None-Match` and no Last-Modified, behind the host's 60 s cache with direct invalidation on every CMS change. `/assets/` stays immutable. Pages without markers keep the native static-file headers.
### Neutral HTML spec (draft; golden files follow once Bryan has approved the approach)
- Order: `displayOrder`, then the order given. Skip a package with a slug that is not `[a-z0-9-]+`, a duplicate slug, no title, a price that is not readable as whole euros above zero, or no features (same rules as `mapOfferings`). The baked fallback stays when the host has no live data at all.
- Per package: `<li data-slug="newborn"><h3>Newborn</h3><p>€&nbsp;185</p><ul><li>…</li></ul><a href="/?pakket=newborn#contact">Boek Newborn</a></li>` inside one `<ul>` per region; the price with U+00A0 after the euro sign; the inner list items are the features in order; all text HTML-encoded. A featured package gets `data-featured="true"` on its `<li>`. Description, price note and button label are not rendered.
- Banner regions: `<aside><strong>{title}</strong> <span>{text}</span> <a href="{url}">{label}</a></aside>`; `strong`, `span` and `a` only when the field is present; the link only when label and URL are both present and the URL is `https://` or a path with one leading `/`; nothing at all when there is no banner (204).
- The ASF repo delivers the fixtures (input JSON and expected HTML) and a README with the commit; SMC tests against the same files.
## Order of work (after approval)
1. Marker spec and golden fixtures (ASF repo), agreed with SMC.
2. Pure neutral-HTML function, build writes the markers, build tests.
3. `PackagesProvider` reads the data block, regions, inline values, JSON-LD price; stand-in injector in the preview server; e2e and fail-safe tests.
4. SMC implements the injector with the same fixtures; test on ASF test.
5. Hosting switch for production (separate), then remove the nightly content build.
## Open questions
- For SMC: the marker format SLP uses today; how the injector reads and edits JSON and `ld+json`; behaviour when data or a marker is missing (must fail open: serve the baked page); caching and ETag; whether `AuthoredBaseUrl` can also run on the prerendered-pages host.
- For Bryan: (answered, see the decisions at the top) accept a brief look change of the cards on first paint, and let the host write the list HTML? Both yes. The alternative that was not chosen: one set of cards styled by plain CSS and owned by the host, with no React in those regions.
@@ -0,0 +1,42 @@
# AI-DLC State Tracking
## Project Information
- **Feature Name**: ASF packages and banners from the CMS (build step, live refresh, CMS-host injection, translation files, fonts)
- **Feature Slug**: asf-packages-cms
- **Project Type**: Brownfield
- **Start Date**: 2026-11-12
- **Current Stage**: COMPLETE (closed 2026-11-16, Bryan's go via SLP Software - SLS - Main); PR feature/asf-packages-cms to master, waiting for the CMS PR to merge first. No production release.
- **Branch**: feature/asf-packages-cms (carries the contact-form-cms commits; the TEST ONLY commit d449e76 is undone by the `VITE_CONTACT_FORM_ENABLED` switch)
- **Worktree**: K:\Development\SlpSoftware\Projects\AndreaSlopFotografie-packages
## Language Configuration
- **Documentation Language**: English
- **Conversation Language**: User Language (Dutch)
- **Source**: aidlc-docs/language-preference.md
## Extension Configuration
- Security Baseline: Yes (inherited from contact-form-cms)
- Property-Based Testing: Partial (inherited)
## Operations Configuration
- **Include Operations Phase**: Yes, as part of the joint production checklist ([docs/go-live-checklist.md](../../../docs/go-live-checklist.md)); no separate steps. The rebuild-trigger question lapses: the CMS host injects current data into the pages, so a CMS change is visible at once (NFR-10).
## Scope as delivered
- Packages and both banners (top bar, band under the cards) from the CMS offerings API, snapshot fallback, centred card rows, featured package style.
- CMS-host injection of the data into the prerendered pages (own feature record: [asf-cms-host-injection](../asf-cms-host-injection/aidlc-state.md)).
- Translation files: all static Dutch text in `web/src/i18n/nl.json` ([asf-translation-files](../asf-translation-files/aidlc-state.md)).
- Fonts (Cormorant Garamond, Mulish), green outline buttons, theme twigs removed with the assets and licence document, own test address (`VITE_SITE_URL`), contact form switch (`VITE_CONTACT_FORM_ENABLED`), documentation set (README, docs/*).
## Stage Progress
- [x] INCEPTION - Workspace Detection, Requirements (approved by SLP Software - SLS - Main for Bryan, 2026-11-12)
- [x] INCEPTION - Workflow Planning (single unit)
- [x] CONSTRUCTION - Functional Design (requirements.md)
- [x] CONSTRUCTION - Code Generation
- [x] CONSTRUCTION - Build and Test: closed 2026-11-16, see [build-and-test-summary.md](construction/build-and-test/build-and-test-summary.md); the former blocker (CMS data on ASF-test) no longer applies: the data reaches the pages through the CMS host
- [x] OPERATIONS - included in the joint production checklist (no separate steps)
@@ -0,0 +1,22 @@
# Build and test summary: asf-packages-cms
Closed 2026-11-16 on branch feature/asf-packages-cms. Unit: web only (host side lives in the SlpModularCms repo).
| Check | Result |
| --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `tsc`, `pnpm lint`, `pnpm format:check` | clean |
| `pnpm test` (Vitest, 100% thresholds on `src/lib/**`, `src/i18n/**`, `seo.ts`, `sitemap.ts`) | 145 files, 1643 tests; one run had a single timing-dependent failure that did not repeat on the next run (to watch, not a known defect) |
| `pnpm baseline:check` (page text byte-identical after the move to nl.json) | equal to the baseline, 12 pages |
| E2E (real Chrome, built site): hydration, contact form, host injection with the stand-in host | passing in CI |
| CI run 107 on the test deploy (check, build-test, deploy-test, lighthouse) | all green, deploy-production skipped |
| Deployment check on ASF-test (pages normalised for host injection, admin files, POST status) | passing |
## Findings and decisions
- Host injection: contract and golden files in `web/contract/host-injection/`; the host side is built by SMC; end-to-end confirmation on ASF-test is still to be reported by SMC.
- The test build sets `VITE_SITE_URL` and `VITE_CONTACT_FORM_ENABLED=true`; the production artifact sets neither (form closed, own address of production).
- Production keeps the committed snapshot until the CMS host is the one entry of the site (separate hosting feature).
## Open (not part of this feature)
- IIS pass-through and production CMS for ASF; Website__PublicBaseUrl on ASF-test; removal of the nightly content build and `OFFERINGS_URL` once host injection is confirmed end to end.
@@ -0,0 +1,30 @@
# Requirements and design: packages and banner from the CMS
Decided by Bryan via SLP Software - SLS - Main, 2026-11-12. Source of truth: the CMS API `GET /api/v1/offerings` (fields: id, slug, title, description, price as free text, priceNote, features[], ctaLabel, featured, displayOrder, categoryId, category, layout `card|banner`; at most one banner per site).
## Requirements
- FR-PK-01 The build asks the CMS for the offerings and bakes them into the pages (prices in the HTML and in the structured data). The browser never calls the offerings API.
- FR-PK-02 Fallback: with no address, an unreachable CMS or an answer without a valid package the committed snapshot (`src/content/offerings.snapshot.json`, the three packages) is used. The build never fails because of the CMS and never shows an empty or wrong price. The log names the source.
- FR-PK-03 One source: the price cards, the "welke shoot" choices of the contact form and the `?pakket=` check use the same list (`content/packages.ts`).
- FR-PK-04 Mapping: `slug` is the package id (kept `zwangerschap`, `newborn`, `gezin`: they appear in `?pakket=` and the form), `title` the name, the price text is read as whole euros ("€ 175", "€ 1.250", "175,-"); a card with an unreadable price, no features or a bad slug is skipped; order by `displayOrder`.
- FR-PK-05 Banner: the first usable offering with `layout=banner` becomes an optional dark band under the cards (own block, price as free text). It is not a package: not in the form choices, not in the package count, no booking link with a package.
- FR-PK-07 Last row of cards (desktop): rows of three, an incomplete last row is centred, for any number of cards, with no styling per number. Phone and tablet stay one column. Done with a wrapping flex and card width `calc((100% - 2 * gap) / 3)`.
- FR-PK-08 Slim top bar (2026-11-14, Bryan via SLS-Main): a second banner ABOVE the cards, next to the one under them; both may show at once. One line (title and text on one line, optional small text link), a slim bar in the ASF style that matches the white bottom banner. Contract: `GET /api/v1/offerings/banner?position=top|bottom` (no parameter is bottom), 204 is none, fields title/text/linkLabel/linkUrl, the title may be empty for top (title or text required). Built in like the bottom banner: baked in the HTML, replaced live after hydration, 204 hides it, errors keep what was baked, empty fields hidden.
- FR-PK-06 The rebuild trigger (CMS change leads to a new build) is separate from the build; decision for Bryan (webhook to workflow_dispatch or a nightly build). Until then a change shows after the next build.
- NFR-PK-01 Tests use the snapshot only (no dependence on a build or network).
## Design
- `web/config/offerings.ts` pure mapping and validation (unit and property tests).
- `web/config/fetchOfferings.ts` build step (`pnpm build` runs it first): `OFFERINGS_URL` (the site's own address serving the API), 10 s timeout, 2 attempts, writes the gitignored `src/content/offerings.generated.json`.
- `web/src/content/packages.ts` picks generated data (build) or the snapshot (tests, missing file).
- CI: the Build step gets `OFFERINGS_URL` from the repo variable `ASF_OFFERINGS_URL`. The artifact built there is also what goes to production, so the variable must point to the CMS holding the real data.
- `PriceBanner` component inside `Pricing`.
## Open
- Offerings module on the ASF-test host and the three packages in the ASF-test CMS (asked of the CMS session; 2026-11-12 the endpoint answered 404 on test.andreaslop.nl).
- Repo variable `ASF_OFFERINGS_URL` (who sets it: Bryan or SLS).
- Rebuild trigger.
- ASF production CMS address does not exist yet.
@@ -0,0 +1,22 @@
# AI-DLC State Tracking
## Project Information
- **Feature Name**: Translation files (all static Dutch text in one language file)
- **Feature Slug**: asf-translation-files
- **Project Type**: Brownfield (part of the asf-packages-cms delivery)
- **Start Date**: 2026-11-15
- **Current Stage**: COMPLETE (closed 2026-11-16); delivered on branch feature/asf-packages-cms
- **Documentation**: [docs/translations.md](../../../docs/translations.md)
## Language Configuration
- **Documentation Language**: English
- **Conversation Language**: User Language (Dutch)
## Stage Progress
- [x] Approach agreed (no library, typed `t`/`tList`/`tPlural`, one `nl.json`; second language later)
- [x] Code Generation, steps 0-8: helper and checks, common, site, home, about and contact, shoots, portfolio, instagram, testimonials, SEO titles, form messages of the cms-client package (block cmsClient)
- [x] Build and Test: baseline tool shows the page text byte-identical; ESLint rules block new hard-coded text; i18n tests and 100% coverage
- Out of scope, separate: hero (becomes a CMS module, see the hero-module feature) and the privacy statement; second language (`en.json`, routes per language)
@@ -0,0 +1,55 @@
# AI-DLC State Tracking
## Project Information
- **Feature Name**: Contact form on the CMS API (ASF contact form talks to the SlpModularCms contact module, using the headless cms-client package)
- **Feature Slug**: contact-form-cms
- **Project Type**: Brownfield
- **Start Date**: 2026-11-10T21:42:54Z
- **Current Stage**: COMPLETE (closed 2026-11-16, Bryan's go via SLP Software - SLS - Main); Operations = included in the joint production checklist (docs/go-live-checklist.md), no separate steps; the form stays closed in production until Bryan's explicit go. Merges with feature/asf-packages-cms (PR), after the CMS PR.
- **Branch**: feature/contact-form-cms (from master 7d594ff)
- **Worktree**: K:\Development\SlpSoftware\Projects\AndreaSlopFotografie-contact-form
## Workspace State
- **Existing Code**: Yes (web/src has ContactForm, ContactFormGate, submitContactForm stub, contactFormReducer)
- **Reverse Engineering Needed**: No (team agreement: no full RE refresh per feature)
- **Workspace Root**: K:\Development\SlpSoftware\Projects\AndreaSlopFotografie-contact-form
## Code Location Rules
- **Application Code**: Workspace root, web code in web/ (NEVER in aidlc-docs/)
- **Feature Documentation**: aidlc-docs/features/contact-form-cms/ only
- **Shared Artifacts**: aidlc-docs/_shared/
- **Server side**: lives in the SlpModularCms repo (branch feature/contact-forms-module, session "SLS Software - CMS"); NOT built from this session, only asked for
## Language Configuration
- **Documentation Language**: English
- **Conversation Language**: User Language (Dutch)
- **Source**: inherited from aidlc-docs/language-preference.md (answer A)
## Cross-session coordination
- Source package (read only): SlpSoftware repo, src/cms-client/ (branch feature/redesign-modern-timetravel), coordinated by session "SLP Software - SLS - Main"
- Server contract: contact-api-contract.md (v0.3.x) in the SlpSoftware repo
- Milestones (plan ready, built) are reported to "SLP Software - SLS - Main"
- Nothing is pushed, merged or deployed without Bryan; the form stays off in production until Bryan's explicit go
## Extension Configuration
- Security Baseline: Yes
- Property-Based Testing: Partial (PBT-02, 03, 07, 08, 09)
## Operations Configuration
- **Include Operations Phase**: Yes
- **Decided At**: Requirements Analysis
## Stage Progress
- [x] INCEPTION - Workspace Detection (2026-11-10)
- [x] INCEPTION - Requirements Analysis (approved by SLP Software - SLS - Main on behalf of Bryan, 2026-11-10)
- [x] INCEPTION - User Stories: SKIP
- [x] INCEPTION - Workflow Planning (approved by SLP Software - SLS - Main on behalf of Bryan)
- [x] INCEPTION - Application Design: SKIP
- [x] INCEPTION - Units Generation: SKIP (one unit: contact-form)
- [x] CONSTRUCTION - Functional Design: EXECUTE (approved by SLS-Main for Bryan)
- [x] CONSTRUCTION - NFR Requirements: SKIP
- [x] CONSTRUCTION - NFR Design: SKIP
- [x] CONSTRUCTION - Infrastructure Design: EXECUTE (approved; CSP set by Bryan: exact frame hosts)
- [x] CONSTRUCTION - Code Generation: EXECUTE (plan approved; steps 1-13 done)
- [x] CONSTRUCTION - Build and Test: EXECUTE (summary written; awaiting approval)
- [x] OPERATIONS - included in the joint production checklist (docs/go-live-checklist.md); the rebuild-trigger question lapses (NFR-10); go-live conditions stay open there
@@ -0,0 +1,71 @@
# Audit Log: contact-form-cms
## Initial request (via peer session)
**Timestamp**: 2026-11-10T21:30:00Z
**User Input**: "Opdracht van Bryan: bouw het eigen contactformulier voor Andrea Slop Fotografie, en doe dat met AI-DLC (aidlc-workflow skill, eigen feature in jullie aidlc-docs; vragen interactief aan Bryan, plan-goedkeuring vóór code). Uitgangspunt/bronnen (alleen lezen, niets daarin wijzigen): Headless pakket: SlpSoftware\src\cms-client\ ... Regels: niets pushen, mergen of deployen zonder Bryan; het formulier blijft in productie uit tot Bryans expliciete go. Meld mij bij mijlpalen (plan klaar, gebouwd)." (relayed by session "SLP Software - SLS - Main"; full text in the session transcript)
**AI Response**: Asked Bryan directly whether to start; he confirmed ("Ja, start AI-DLC (Recommended)").
**Context**: Workspace Detection. Classification: Feature (full workflow), brownfield.
---
## Workspace Detection
**Timestamp**: 2026-11-10T21:42:54Z
**AI Response**: Created worktree AndreaSlopFotografie-contact-form on branch feature/contact-form-cms from master 7d594ff. Language inherited (A). Found existing ASF contact form (ContactForm, ContactFormGate, submitContactForm stub, contactFormReducer, siteContent.contactForm switch) that this feature connects to the CMS API.
**Context**: Reverse Engineering skipped (team agreement). Next: Requirements Analysis.
---
## Delegation and extension decisions
**Timestamp**: 2026-11-10T21:55:00Z
**User Input**: "`SLP Software - SLS - Main` is in de lead van de bouw van het contactformulier en de communicatie. Hij mag toestemming geven namens mij. Bij twijfel vraag van wie de toestemming komt."
**AI Response**: Recorded in memory. Asked first four requirement questions in chat.
**Context**: Bryan answered: Security Baseline = Yes; PBT = Partial; Operations = Yes (include now); Reuse = package replaces state and validation, existing ContactForm UI stays.
---
## Requirements Analysis
**Timestamp**: 2026-11-10T22:20:00Z
**User Input**: "Stuur je vragen door naar SLS sessie. als je dat niet al had gedaan. om te voorkomen dat ik 2x dezelfde vragen beantwoord en om te zorgen dat SLS alles kan reguleren"
**AI Response**: Forwarded open questions A-E to SLP Software - SLS - Main and wrote requirements.md and requirement-verification-questions.md. SLS-Main answered: captcha slot not built yet (copy final package only after its message); lazy token fetch via IntersectionObserver; Friendly Captcha v2 provisional (CSP to be confirmed by CMS-U9 and a real-browser test); ASF server side by SLS Software - CMS with AndreaSlopFotografie; plan and approval steps go to SLS-Main, who approves on Bryan's behalf within the agreed frame (push, merge, deploy, production and content/privacy preferences stay with Bryan).
**Context**: Requirements Analysis complete, approval requested.
---
## Requirements approval and Workflow Planning
**Timestamp**: 2026-11-10T22:40:00Z
**User Input**: (SLP Software - SLS - Main, on behalf of Bryan) "Requirements contact-form-cms: volledig gelezen, technisch akkoord (namens Bryan, binnen de kaders). ... Ga door met workflow planning en design; plan komt bij mij voor akkoord voor code."
**AI Response**: Processed the six refinements into requirements.md. Wrote inception/plans/execution-plan.md.
**Context**: Workflow Planning complete; approval requested from SLS-Main.
---
## Construction and Operations
**Timestamp**: 2026-11-10T23:55:00Z
**User Input**: (SLP Software - SLS - Main, on behalf of Bryan) approved functional design, infrastructure design (frame-src exact hosts global, global0, global1) and the code generation plan; privacy wording approved with retention 1 year / 30 days spam and Andrea as controller; the full privacy statement is a separate feature required before go-live.
**AI Response**: Built steps 1-13 (commits e094594, a1444b7 and later), ran build and test (summary in construction/build-and-test), tested the real widget in Chrome against the local ASF host (202, no CSP violation), wrote deployment plan, monitoring plan and production readiness checklist with the go-live conditions.
**Context**: Build and Test and Operations documents written; approval requested from SLS-Main. Production stays off until Bryan go.
---
@@ -0,0 +1,31 @@
# Build and test summary: contact-form-cms
Date: 2026-11-10. Branch feature/contact-form-cms (a1444b7 plus later commits). Unit: contact-form (web only).
| Check | Result |
|---|---|
| `tsc` (typecheck in `pnpm build`) | clean |
| `pnpm lint` (ESLint incl. cms-client import boundary) | clean |
| `pnpm format:check` | clean |
| `pnpm test` (Vitest, 100% thresholds for pure functions) | 134 files, 1473 tests passed |
| cms-client package tests (copied) | 62 passed (boundary test included) |
| `pnpm build` + prerender | ok, 12 pages |
| E2E `contactForm.e2e.ts` + `hydration.e2e.ts` (real Chrome, built site, mocked `/api`) | 49 passed, 2 skipped with the switch off; the 2 "switch on" tests pass in a build with the switch on |
| `pnpm audit --prod` | no known vulnerabilities |
| Lighthouse mobile | all pages pass, except `/` performance 0.84 (threshold 0.85); same chance result as on master earlier (0.84); not a regression of this feature |
| Lighthouse desktop | all 12 pages pass |
| Real widget in real Chrome against the local ASF host (CMS 192.168.1.2:5291, captcha on, global endpoint) | form opens, widget loads and solves, POST 202, thank-you shown, no CSP violation, no console message |
## Requirement coverage
FR-CF-01..12 and NFR-CF-01..05 are covered by the unit/component tests (ContactForm, ContactPanel, useContactAvailability through the panel, securityHeaders, shootOptions), the e2e and the real-browser run. PBT (partial): label length 1-100 and uniqueness, JSON round trip with special characters, and the package's own property tests.
## Findings and decisions
- CSP: only `frame-src` with the exact hosts global, global0, global1 is needed; the real-browser run showed no violation without `connect-src`, `script-src` or `worker-src` additions (the widget's own fetches run inside its iframe).
- With the switch on, a `404` on the token route (form closed) logs a console message in the browser; the hydration e2e tests therefore run with the switch off and the switch-on behaviour has its own e2e with a mocked API.
- The package needed two small changes for ASF's stricter rules (explicit field instead of a constructor parameter property; a loop instead of a recursive `useCallback`); SLS-Main made them upstream (93fa729), so the copy is unchanged.
- Dev (StrictMode) asks for the token twice; the production build asks once.
## Not done / needs others
- Test of the form against a deployed ASF test host (needs the CMS branch merged and deployed; not requested yet).
- EU endpoint (`eu`, `eu0`, `eu1` in `frame-src`) is not tested; it needs a paid plan.
- Screen reader check by a person.
@@ -0,0 +1,3 @@
# Build instructions
From `web/`: `pnpm install --frozen-lockfile`, then `pnpm build` (typecheck, Vite build with prerender, inline scripts moved to files). Output in `web/dist/client`.
Local run against a CMS host: `API_PROXY_TARGET=http://<host>:<port> pnpm exec vite --host --port <port>` (no proxy without the variable). The form only talks to the server when `siteContent.contactForm.enabled` is `true`.
@@ -0,0 +1,3 @@
# Integration and e2e test instructions
1. Built site against a mocked API: `pnpm build` then `pnpm e2e` (real Chrome; `e2e/contactForm.e2e.ts` runs the "off" or "on" variant depending on the switch in `siteContent.ts`; to run the "on" variant build with the switch on locally and run only that file).
2. Real server: start the local ASF host (SLS Software - CMS: API `192.168.1.2:5291`, captcha on, smtp4dev for mail), run the dev server with `API_PROXY_TARGET=http://192.168.1.2:5291`, and open `/contact`. Expected: the notice disappears, the widget solves, sending gives the thank-you, the message appears in the ASF CMS admin and in smtp4dev. Check the browser console for CSP messages.
@@ -0,0 +1,2 @@
# Performance test instructions
Build with the switch off (as in production now) and run `pnpm lighthouse` (mobile) and `lhci autorun --config=lighthouserc.desktop.cjs` (desktop). The form and the captcha SDK are lazy chunks loaded only when the form is near the screen and open, so pages without a form in view load no new JavaScript. Known: `/` mobile performance varies around the 0.85 threshold (0.84 also on master).
@@ -0,0 +1,2 @@
# Unit and component test instructions
`pnpm test` (Vitest, jsdom, coverage thresholds). Relevant files: `src/components/ContactForm/ContactForm.test.tsx` (fake Friendly Captcha SDK, fake client), `src/components/ContactPanel/ContactPanel.test.tsx` (availability states), `src/lib/shootOptions.test.ts`, `config/securityHeaders.test.ts`, `src/cms-client/**/__tests__` (copied package tests incl. the boundary test). Property tests print their fast-check seed; rerun with `FC_SEED=<seed>`.
@@ -0,0 +1,115 @@
# Functional design: contact-form (unit 1, web)
Status: DRAFT for approval by SLP Software - SLS - Main (on behalf of Bryan). Based on the package in `SlpSoftware/src/cms-client` (current version without captcha) and the existing ASF components. Details marked **[slot]** depend on the captcha slot that SLS-Main still builds.
## 1. Components and responsibilities
```mermaid
flowchart TD
CP[ContactPanel<br/>existing: packages, ?pakket=, lazy chunk] --> GATE[ContactFormGate<br/>existing: dimmed Binnenkort]
GATE -->|enabled=true| AV[ContactAvailability<br/>NEW: token fetch when in view]
AV -->|token ok and provider supported| CF[ContactForm<br/>ADAPTED: skin on useContactForm]
AV -->|anything else| GATE
CF --> HOOK[useContactForm<br/>cms-client]
CF --> CAP[CaptchaWidget<br/>NEW: client only, reserved height]
HOOK --> CLIENT[createContactClient<br/>cms-client]
CLIENT --> API[(/api/v1/contact-messages)]
classDef existing fill:#9ae6b4,stroke:#2f855a,color:#000;
classDef newc fill:#63b3ed,stroke:#2b6cb0,color:#000;
classDef pkg fill:#f6e05e,stroke:#c05621,color:#000;
class CP,GATE existing;
class AV,CAP newc;
class CF newc;
class HOOK,CLIENT pkg;
```
Text alternative: ContactPanel renders the gate; when enabled, ContactAvailability fetches the token and only then mounts the adapted ContactForm, which uses the package hook and, when needed, the captcha widget.
| Part | Change |
|---|---|
| `ContactPanel` | Keeps shoot options, `?pakket=` and the lazy chunk. Maps the chosen package id to its **label** and remembers the last preselect (FR-CF-08). Passes `enabled` through. |
| `ContactFormGate` | Unchanged look. Stays the initial render and the closed state. Its mail button keeps the `useEmailAddress` approach (no address in HTML before hydration). |
| `ContactAvailability` (new) | Only when `enabled`: waits until the form area is in view (IntersectionObserver, wide rootMargin; fallback first focus/pointer when IO is missing), then calls `client.getToken()` once. Exposes `{ state: 'idle' \| 'checking' \| 'open' \| 'closed', token, refreshToken }`. Renders children only in `open`. No request when `enabled=false`. |
| `ContactForm` | Keeps the Chakra skin, ids, test ids, thank-you and privacy note. State, validation, submit, idempotency and token refresh come from `useContactForm`. The old reducer, `validateContact`, `toContactPayload` and `submitContactForm` are deleted. |
| `CaptchaWidget` (new) | Renders the Friendly Captcha widget only when the token response says `captcha` with a supported provider. Client-only, after mount, in a reserved height. **[slot]** |
| `cms-client` | Copied unchanged into `web/src/cms-client/` (final version after SLS-Main's message). |
## 2. Availability state machine (ContactAvailability)
| From | Event | To | Note |
|---|---|---|---|
| idle | `enabled=false` | idle | no request, gate stays |
| idle | in view (or first focus without IO) and `enabled` | checking | one `getToken()` |
| checking | `ok` and (`captcha=null` or provider supported) | open | token kept in memory only |
| checking | `ok` and unsupported provider | closed | gate; no log of the provider value beyond a generic event |
| checking | `closed` (404) / `failed` / 429 / network | closed | gate; no retry loop (a later page view tries again) |
| open | submit reports `expired` | open | `refreshToken()` once (package) |
| closed | - | closed | terminal for this page view |
Prerender and first client render are always `idle` (the gate), so there is no hydration mismatch and no layout shift: the placeholder heights 649/547 px stay.
## 3. Field mapping and validation
| Visible field | Package field | Limit | Notes |
|---|---|---|---|
| Naam | `name` | 100 | `autoComplete="name"` |
| E-mail | `email` | 254 | `type=email`, `autoComplete="email"` |
| In welke shoot... | `subject` | 100 | **value = readable label**; options are `{ value: label, label }` from `shootOptions`; "Overig" is the fixed label for other |
| Stel hier je vraag | `message` | 2000 | |
- Validation and the Dutch messages come from the package (`required`, `tooLong`, `invalid`). Error texts of the old reducer are gone; where the package text differs from the old text, the package wins (SLS-Main and Bryan accepted: no forks).
- Trim is done by the package (`trimFields`). Maximum lengths also stay as `maxLength` on the inputs.
- `?pakket=` resolves to a package id (existing `packageFromSearch`) and then to that package's label before reaching the hook (`subject` is the label).
## 4. Submit flow (package)
1. Submit with errors: errors show per field, focus moves after the render to the first invalid field (inputs are disabled while sending).
2. Valid: `Idempotency-Key` per attempt series, honeypot `hpCheck` from the hook, token from availability, `captchaToken` **[slot]**.
3. `202`: thank-you (`Bedankt voor je bericht! Ik reageer binnen {replyTime}.`) takes focus; event `contact-sent`.
4. `400 expired`: one refresh and retry (package). Field errors map to fields.
5. 413 / 429 / 5xx / network: failure message from the package (429 with Retry-After in minutes); mail fallback text with the address assembled client-side after hydration; event `contact-failed`. The visitor can try again; the form keeps the typed values.
6. Spam (honeypot filled): silent success, no request (package).
Events go through the existing analytics wrapper with only `contact-sent` and `contact-failed`. No field values, token or idempotency key reach logs, Sentry or Umami.
## 5. Preselect (FR-CF-08)
`ContactPanel` keeps `{ subject: label, key }` from the first "Boek..." click, also before the form chunk has mounted, and `ContactForm` passes it to the hook as `initialSubject` (added to the package by SLP Software - SLS - Main together with the captcha slot) plus the `preselect` change counter for later clicks. The earlier key-bump workaround is dropped. Until the final package arrives, the code is written against `initialSubject` and tested with a fake of the hook.
## 6. Captcha **[slot]**
- Data: token response `captcha: { provider, siteKey }` or `null`.
- Supported: `friendlycaptcha` only. Anything else keeps the gate.
- Hook offers `setCaptchaToken(token|null)` and `captchaRequired`. The widget calls `setCaptchaToken` on solve, `setCaptchaToken(null)` and a reset on expiry or error.
- Decided by Bryan: Friendly Captcha v2 with the bundled npm package `@friendlycaptcha/sdk`. The CSP guide says the widget uses iframes, so `frame-src` is needed (see infrastructure design); no external script tag.
- SDK details verified against the current docs (developer.friendlycaptcha.com, v2):
- Package `@friendlycaptcha/sdk`; `FriendlyCaptchaSDK.createWidget({ element, sitekey, apiEndpoint, language, theme, startMode, formFieldName })`; `startMode` is `auto`, `focus` (default) or `none`; `apiEndpoint` accepts the shortcuts `"global"` (default) and `"eu"`; `formFieldName` default `frc-captcha-response`; `theme` `light | dark | auto`.
- Widget handle: `reset()`, `destroy()`, `getResponse()`, `start()`, `getState()`, `getElement()`.
- Events on the widget element: `frc:widget.complete` (`event.detail.response` is the token), `frc:widget.expire` (response `.EXPIRED`), `frc:widget.error` (response `.ERROR`, `detail.error.code`), `frc:widget.statechange`.
- We use the `response` of `complete` as `captchaToken` (not the form field), and set it to null on `expire`/`error`, then `reset()`.
- Choices for ASF: `startMode: "focus"` (starts when the visitor focuses the form), `language: "nl"`, `theme: "light"`, `apiEndpoint` from the host Bryan picks (`"eu"` recommended).
- Still to verify in Build and Test with a real browser: exact behaviour on `reset()` and the CSP entries marked "test".
- A missing token counts as spam on the server (still `202`), so the client blocks the submit with a clear message until the captcha is solved when `captchaRequired`; the client never relies on the server to tell the visitor.
- The widget code is a separate lazy chunk, loaded only in `open` with captcha required; reserved height; no script in prerendered HTML.
- Provider outage is fail-open on the server; the client never decides that.
## 7. Accessibility
Labels stay `Field.Label`; error text is outside the label (accessible name stays clean); `aria-invalid` and `aria-describedby` come from the hook; success and failure use `role="status"`/`role="alert"`; the honeypot stays off-screen, `aria-hidden`, `tabIndex=-1`, `autoComplete="off"`; focus order unchanged; axe tests stay part of the component tests.
## 8. Business rules (BR-CF)
- BR-CF-01 No token request unless `enabled` and the form is in view.
- BR-CF-02 The form is interactive only when the server said `200` and (captcha absent or supported).
- BR-CF-03 Subject sent is always the visible label, 1-100 characters.
- BR-CF-04 No personal data, token or idempotency key leaves the form except in the POST body.
- BR-CF-05 Prerendered HTML contains no token, widget or e-mail address.
- BR-CF-06 Failure never exposes technical text; the mail fallback is always offered.
- BR-CF-07 An expired captcha token is never sent.
## 9. Testability and PBT (partial)
- PBT-02/03 (round trip, invariants): `label -> payload.subject` (length 1-100 for all content labels; labels with & ' " < > survive the JSON round trip); `trimFields` idempotent.
- PBT-07/08/09: generators for form values shared in `src/test/arbitraries.ts`, shrinkable, seeds logged by the existing setup.
- Example-based tests: gate states, no request when disabled, unsupported captcha keeps gate, expired captcha token not sent, 429 text from the package, failure path without the address in HTML, preselect before mount.
- E2E (mocked `/api` route): token 200 -> form; 404 -> gate; submit 202; submit 400 expired -> retry; prerendered HTML check (no token/widget/address).
- Manual run against the temporary environment (192.168.1.2) with evidence.
## 10. Open items
1. Final package (captcha slot) and the exact captcha version/CSP: pending SLS-Main and CMS-U9.
2. Package text changes versus the old texts (small differences) are accepted unless Bryan objects to wording.
3. `initialSubject` arrives with the final package (SLS-Main).
4. Host (EU or global), exact versus wildcard `frame-src` and the plan needed for the EU endpoint: Bryan decides.
@@ -0,0 +1,64 @@
# Infrastructure design: contact-form (unit 1, web)
Status: DRAFT for approval by SLP Software - SLS - Main (on behalf of Bryan).
## 1. Request path
All calls are same-origin: `/api/v1/contact-messages/token` and `/api/v1/contact-messages`. The site is served by the CMS host (test now, ASF production on IIS later), which also serves `/api`; no CORS and no new origin for the API.
```mermaid
flowchart LR
B[Browser] -->|same origin /api/v1| H[ASF CMS host<br/>contact module]
H --> M[(MariaDB)]
H --> S[SMTP]
B -.captcha API.-> F[Friendly Captcha<br/>global.frcapi.com provisional]
classDef c fill:#f6e05e,stroke:#c05621,color:#000;
classDef s fill:#63b3ed,stroke:#2b6cb0,color:#000;
classDef x fill:#fbb6ce,stroke:#97266d,color:#000;
class B c;
class H,M,S s;
class F x;
```
Text alternative: the browser talks only to the ASF CMS host on the same origin, plus the captcha provider's API when a captcha is required.
## 2. Content Security Policy
Two places define the CSP and both must match:
- `web/config/securityHeaders.ts` (the prescription and the Vite dev/preview headers) - changed in this feature.
- The ASF CMS host's security header options (set by the CMS session `AndreaSlopFotografie`) - requested from them, not edited here.
Planned additions (provisional; Friendly Captcha v2 with the bundled `@friendlycaptcha/sdk`). The official CSP guide (developer.friendlycaptcha.com/docs/v2/guides/csp) says the widget uses iframes and needs at least `frame-src https://*.frcapi.com`; it names no other directive. Bryan decides exact origin versus wildcard and the host (EU recommended, `eu.frcapi.com`; the EU endpoint needs a Friendly Captcha Advanced or Enterprise plan, to be checked by Bryan). Everything marked "test" is added only if a real-browser test proves it necessary; no wildcards beyond what Bryan accepts.
| Directive | Now | Add |
|---|---|---|
| frame-src | not set (falls back to default-src) | the exact origin of the chosen host (`https://eu.frcapi.com` or `https://global.frcapi.com`), or `https://*.frcapi.com` if Bryan accepts the wildcard the docs name |
| connect-src | `'self'` + Umami + Sentry | test: the chosen host origin (the SDK fetches from its API endpoint) |
| script-src | `'self'` + Umami | nothing planned (SDK bundled, first-party chunk); test: `'wasm-unsafe-eval'` only if the SDK needs WebAssembly |
| worker-src | not set | test: `blob:` only if the SDK needs it |
Rules: add only what a real-browser test proves necessary (except the documented frame-src); each added entry gets a comment with the reason; the existing test `securityHeaders` gets assertions for the exact directives; no `unsafe-eval`, no wildcard hosts. The captcha script chunk is first-party, so `script-src 'self'` still holds.
## 3. Dev proxy
`vite.config.ts` `server.proxy`: `/api` to `http://192.168.1.2:5290` (the temporary environment) for local development, configurable through an env variable (default off in CI). Production and preview have no proxy. The dev CSP `connect-src` stays `'self' ws:` plus the above; the proxy keeps requests same-origin in the browser.
## 4. Build and delivery
- New code is in the lazy ContactForm chunk and a separate captcha chunk; pages without a form in view load no new JS (Lighthouse budgets in `lighthouserc.cjs` must stay green; a measurement is part of Build and Test).
- `web/src/cms-client/` is plain TypeScript/React inside the existing build. ESLint `no-restricted-imports` and the boundary test copy over with the package.
- `siteContent.contactForm.enabled` stays `false` in the merge; Bryan switches it on after the server is ready and he gives the explicit go.
- The CI pipeline is unchanged (unit, e2e, lint, Lighthouse); the CMS-check mode of deploy-test is unchanged.
## 5. Configuration and secrets
No secrets in the client. The captcha `siteKey` is public and arrives in the token response, so there is no new build-time variable. Server settings (`Contact__RecipientEmail`, `Contact:Enabled`, `MinSeconds`, retention, `ForwardedHeaders:KnownProxies`/`ClientPartitionKey`, `Email:AllowedFromAddresses`) belong to the CMS sessions and are requested through SLP Software - SLS - Main.
## 6. Observability
Events `contact-sent` and `contact-failed` through the existing analytics wrapper; nothing else, no field values, no tokens. Sentry captures unexpected exceptions without breadcrumbs from form fields (existing scrubbing configuration is checked in Build and Test).
## 7. Rollback and go-live
- Rollback: set `siteContent.contactForm.enabled = false` and redeploy; the gate returns and no token request is made. The server can also close the form (`Contact:Enabled` off gives 404, which keeps the gate).
- Go-live needs: server module deployed on the ASF host, recipient and sender configured, captcha configured (or off), Bryan's explicit go.
## 8. Dependencies on other sessions
| Item | Owner |
|---|---|
| Package captcha slot (branch and commit) | SLP Software - SLS - Main |
| Server contact module, captcha verifier, openapi for ASF | SLS Software - CMS |
| ASF host config (CSP options, recipient, proxies, Contact:Enabled) | AndreaSlopFotografie (via SLS-Main) |
| ASF test host with the endpoint | after Bryan merges the CMS branch (not requested yet) |
@@ -0,0 +1,35 @@
# Privacy statement: draft text for the contact form (needs Bryan's approval)
Status: DRAFT, wording approved by Bryan (via SLP Software - SLS - Main, 2026-11-10) with the retention periods and the controller below; the captcha sentence is published together with the captcha only. Nothing of this is in the site yet: the page `/privacyverklaring` is still the placeholder "Deze pagina is nog in de maak". The text is site copy in Dutch, so Bryan (and Andrea, as the controller) decide the wording. Items marked **[CHECK]** are facts that must be confirmed before publishing; they are not guessed here.
## What the form sends and stores (from the API contract v0.3.x)
- Sent: name, e-mail address, the chosen shoot (the readable label, e.g. "Newborn"), the message, a signed time token, and (when the captcha is on) the captcha response.
- Stored by the CMS: the four fields, the time of receipt, a status and the mail status. **No IP address is stored** by the contact module (contract section 4.2). Retention (decided by Bryan): 1 year for contact messages, 30 days for messages marked as probable spam (`retentionUntil` is fixed per message from the server setting).
- Mail: each message is sent to Andrea's mailbox. **[CHECK]** mail provider and where it processes the data.
- The reply: Andrea answers by e-mail to the address given.
## Captcha (only when switched on)
- Provider: Friendly Captcha (Friendly Captcha GmbH, Germany). Region: the server decides. With the **global** endpoint (free key, tests only) the visitor's IP address can be processed outside the EU; the EU endpoint (`eu`, paid plan) keeps it in the EU. According to the provider the widget uses no cookies and does no tracking (Bryan's note via SLS-Main). **[CHECK]** exactly what the widget sends to the provider (quote the provider's privacy documentation) and whether a processing agreement is needed.
- Commercial use of the free tier is not allowed (Bryan's note): the captcha stays off in production until a paid plan exists, so this paragraph is only published together with the captcha.
## Draft text (Dutch)
### Contactformulier
Als je het contactformulier gebruikt, verwerk ik de gegevens die je invult: je naam, je e-mailadres, de soort shoot waarvoor je interesse hebt en je bericht. Ik gebruik die gegevens alleen om te reageren op je vraag. Het bericht wordt opgeslagen in het beheersysteem van deze website en als e-mail naar mij gestuurd. Je IP-adres wordt daarbij niet bewaard. Ik bewaar je bericht maximaal 1 jaar en verwijder het daarna. Berichten die waarschijnlijk spam zijn, bewaar ik 30 dagen.
Je kunt me ook gewoon mailen via de knop onder het formulier; dan gebruik je het formulier niet.
### Beveiliging tegen spam
Om spam tegen te gaan gebruikt het formulier een onzichtbaar veld en een korte wachttijd voordat je kunt versturen. **[Alleen bij ingeschakelde captcha:]** Daarnaast controleert de dienst Friendly Captcha (Friendly Captcha GmbH, Duitsland) of je een persoon bent. Volgens de aanbieder gebruikt die controle geen cookies en volgt hij je niet. Daarbij wordt wel je IP-adres naar de dienst gestuurd. **[Bij het gratis `global`-endpoint kan dat buiten de EU verwerkt worden; bij het EU-endpoint blijft het binnen de EU. Kies de zin die past.]** **[CHECK: welke gegevens deze dienst precies ontvangt, dit uit hun privacyinformatie overnemen]**
### Je rechten
Je kunt me vragen welke gegevens ik van je heb, ze te laten corrigeren of verwijderen. Mail daarvoor naar info@andreaslop.nl, het adres onder het formulier. Andrea Slop is verantwoordelijk voor de verwerking van deze gegevens.
## Where it appears
1. `PrivacyNote` under the form already links to `/privacyverklaring`; no change to that line is needed.
2. The page `routes/privacyverklaring.tsx` still has to be written; this draft is the part about the form. A full privacy statement (analytics: Umami without cookies, Sentry, hosting) is a separate piece of content.
## Questions for Bryan (via SLP Software - SLS - Main)
Answered by Bryan (via SLS-Main, 2026-11-10): retention 1 year (30 days for probable spam); Andrea is the controller and the contact address is info@andreaslop.nl; wording approved; the captcha sentence is published together with the captcha (off at go-live). The full ASF privacy statement is a SEPARATE feature that must be ready before the form goes live (not needed for testing); recorded as a go-live condition in the Operations checklist.
Still open for that privacy feature: the mail provider and where it processes the data, and exactly what the captcha widget sends to the provider (quote the provider's documentation).
@@ -0,0 +1,31 @@
# Code generation plan: contact-form (unit 1, web)
Status: DRAFT for approval by SLP Software - SLS - Main (on behalf of Bryan). No code until approved. All paths under `web/` in the worktree `AndreaSlopFotografie-contact-form`, branch `feature/contact-form-cms`. Nothing is pushed or merged without Bryan.
Order matters: steps 1-2 can start with the current package (without captcha); the final package (captcha slot and `initialSubject`) is copied in step 9 after SLS-Main's message, and steps 10-12 need it.
## Steps
- [x] **1. Copy the current package**: `src/cms-client/` (http/, contact/, README, tests, boundary test) copied unchanged from `SlpSoftware/src/cms-client` (read only). Add the ESLint `no-restricted-imports` rule for `src/cms-client/**`. Check: boundary test and the package's own tests pass in this repo.
- [x] **2. Client factory**: `src/contact/contactClient.ts` creating `createContactClient` with same-origin base `/api/v1`; no logging of bodies.
- [x] **3. Subject options by label**: `src/lib/shootOptions.ts` returns `{ value: label, label }` plus the id-to-label map for `?pakket=`; test that every content label is 1-100 characters and that `& ' " < >` survive the payload (PBT-02/03).
- [x] **4. ContactAvailability**: new `src/components/ContactForm/ContactAvailability.tsx` with the state machine of the functional design (no request when disabled; IntersectionObserver with the `useInView` hook; first-focus fallback; `idle/checking/open/closed`; token in memory; `refreshToken`). Tests: no request when disabled, one request when in view, 404/429/5xx/network keep the gate, unsupported provider keeps the gate, first-focus fallback.
- [x] **5. ContactPanel + Gate wiring**: Gate stays the initial render; Panel renders Availability inside Gate when `enabled`; Panel remembers the last preselect as `{ subject: label, key }`; placeholder heights unchanged. Tests: prerendered HTML has no token/widget/address; hydration test stays green.
- [x] **6. ContactForm on `useContactForm`**: replace reducer, validation, 3 s check and submit prop; keep Chakra skin, ids, test ids, thank-you and PrivacyNote; error text outside the label; honeypot from `honeypotProps`; failure message from the package with address assembled after hydration (`useEmailAddress`); events `contact-sent`/`contact-failed` through the analytics wrapper. Tests: component tests incl. axe, field errors, focus after render, 429 text, failure path without address in HTML.
- [x] **7. Remove dead code**: `src/lib/contactFormReducer.ts`, `validateContact.ts`, `toContactPayload.ts`, `isLikelySpam`, `src/contact/submitContactForm.ts` and `types.ts` (as far as unused), plus their tests; update `src/test/arbitraries.ts` (form generators) and references.
- [x] **8. Dev proxy and CSP**: `vite.config.ts` `server.proxy` for `/api` (env-configurable, default off in CI); `config/securityHeaders.ts` additions per the infrastructure design (frame-src decided by Bryan; others only after the real-browser test) with reason comments; extend the `securityHeaders` tests.
- [x] **9. Final package** (after SLS-Main's message): replace `src/cms-client/` by the final version (captcha slot, `initialSubject`); re-run boundary and package tests.
- [x] **10. CaptchaWidget**: new lazy chunk `src/components/ContactForm/CaptchaWidget.tsx` using `@friendlycaptcha/sdk` (`createWidget`, `startMode: focus`, `language: nl`, `apiEndpoint` per Bryan's host choice); complete -> `setCaptchaToken(response)`; expire/error -> `setCaptchaToken(null)` and `reset()`; `destroy()` on unmount; reserved height; add the pinned dependency (check `minimumReleaseAge` rules of pnpm). Tests with a fake SDK: expired token not sent, error resets, unsupported or missing provider keeps the gate, submit blocked with message until solved.
- [x] **11. Preselect with `initialSubject`**: Panel passes the remembered preselect to the form, the form to the hook; test "Boek..." before the form is mounted.
- [x] **12. Privacy text (draft, for Bryan's approval; not in the site)**: PrivacyNote and the privacy page name the captcha provider and what the form stores (wording needs Bryan's approval; draft goes to SLS-Main for routing).
- [x] **13. PBT and e2e**: fast-check properties (PBT-02/03/07/08/09) for the label/payload mapping and trim; e2e with a mocked `/api` route: token 200 -> form, 404 -> gate, 202 success, 400 expired -> retry, prerendered HTML check; extend `noJs` e2e (gate and mail button without JS).
- [x] **14. Documentation**: update `LAYOUT.md` if the contact block changes; README note for the copied package (source and sync rule); `aidlc-docs` code summary.
- [x] **15. Automatic build and test (Step 13.5)**: `pnpm` typecheck, lint, unit tests, e2e where available, build and prerender; fix and repeat; report any decision only Bryan can make.
## Not in this plan
- Server module, verifier, openapi, ASF host configuration (other sessions).
- Switching `siteContent.contactForm.enabled` to true, push, merge, deploy (Bryan).
- Real-browser CSP verification and manual run against the temporary environment: Build and Test stage.
## Traceability
FR-CF-01 -> 1, 9; FR-CF-02 -> 6, 7; FR-CF-03 -> 3, 6; FR-CF-04/05 -> 4, 5; FR-CF-06/07 -> 6; FR-CF-08 -> 5, 11; FR-CF-09 -> 10; FR-CF-10 -> 12; FR-CF-11 -> 8; FR-CF-12 -> 6; NFR-CF-01 -> 8, 10; NFR-CF-02 -> 4, 10 (lazy chunks); NFR-CF-03 -> 3, 4, 6, 10, 13.
@@ -0,0 +1,48 @@
# Execution plan: contact-form-cms
## Summary
Single unit of work (web only): connect the ASF contact form to the CMS contact module through the copied headless package, with Friendly Captcha, CSP and dev proxy. Server work and the package captcha slot are delivered by other sessions.
## Stages
| Stage | Decision | Reason |
|---|---|---|
| Workspace Detection | Done | Brownfield, Feature |
| Reverse Engineering | Skip | Team agreement |
| Requirements Analysis | Done (approved by SLS-Main for Bryan) | |
| User Stories | Skip | One persona (visitor); acceptance in requirements |
| Workflow Planning | This document | |
| Application Design | Skip | No new components; ContactForm, Gate and Panel are adapted. The package boundary is fixed by the package |
| Units Generation | Skip | One unit: `contact-form` |
| Functional Design | Execute | State machine of gate, availability, captcha and submit; field mapping; preselect; accessibility; error handling |
| NFR Requirements | Skip | Covered in the requirements (security, performance, testing); Security Baseline is enforced at each stage |
| NFR Design | Skip | Merged into functional and infrastructure design |
| Infrastructure Design | Execute | CSP directives (captcha), Vite dev proxy, deploy impact, pipeline, rollback |
| Code Generation | Execute | Plan first; approval before code (SLS-Main for Bryan; push and merge stay with Bryan) |
| Build and Test | Execute | Unit, component, PBT, e2e with mocks, manual run against the temporary environment, Lighthouse |
| Operations | Execute (included) | Deployment notes, monitoring (events only, no personal data), production readiness checklist; production stays off until Bryan's go |
## Sequence and dependencies
```mermaid
flowchart LR
RA[Requirements<br/>done] --> WP[Workflow Planning]
WP --> FD[Functional Design]
FD --> ID[Infrastructure Design]
ID --> CG[Code Generation<br/>plan then code]
CG --> BT[Build and Test]
BT --> OP[Operations]
PK[Package with captcha slot<br/>SLP Software - SLS - Main] -.final copy.-> CG
SV[Server verifier and ASF host<br/>SLS Software - CMS / AndreaSlopFotografie] -.real test.-> BT
classDef done fill:#9ae6b4,stroke:#2f855a,color:#000;
classDef todo fill:#63b3ed,stroke:#2b6cb0,color:#000;
classDef ext fill:#f6e05e,stroke:#c05621,color:#000;
class RA done;
class WP,FD,ID,CG,BT,OP todo;
class PK,SV ext;
```
Text alternative: requirements are done; planning, functional design, infrastructure design, code generation, build and test and operations follow in order; the package slot and the server work from other sessions feed code generation and the real test.
## Gates
- Design and plan approvals go to SLP Software - SLS - Main (acts for Bryan within the agreed frame).
- Push, merge, deploy, production and choices about design, text or privacy stay with Bryan.
- No code before the code generation plan is approved. The final package is copied only after SLS-Main's message.
@@ -0,0 +1,56 @@
# Requirements clarification: contact-form-cms
Questions were asked interactively in chat (project agreement); answers recorded here afterwards. Open follow-up questions are routed through the session "SLP Software - SLS - Main" (Bryan's instruction, 2026-11-10).
## Question 1: Security Baseline extension
- A) Yes, enforce
- B) No
[Answer]: A
## Question 2: Property-based testing extension
- A) Full
- B) Partial (pure functions and round-trips)
- C) No
[Answer]: B
## Question 3: Operations phase
- A) Yes, include now
- B) Decide later
- C) No
[Answer]: A
## Question 4: Relation between the cms-client package and the existing ASF form
- A) Package replaces state and validation; the existing ContactForm UI stays and uses useContactForm
- B) Package only for sending
[Answer]: A
## Question 5: Subject
- A) Select value (id) is the subject
- B) Free text
- X) Other
[Answer]: X - The human-readable label ("Newborn shoot", "Overig") is sent as `subject`; the id stays local for the ?pakket= preselect. (Decision by Bryan, relayed by SLP Software - SLS - Main)
## Question 6: Robot check
- A) None now
- B) Friendly Captcha now
- X) Other
[Answer]: B - Build Friendly Captcha now (Bryan via SLP Software - SLS - Main). Package gets a captcha slot (SLS-Main), server verifier by SLS Software - CMS, widget + CSP + privacy text by this feature.
## Question 7: Form unavailable
- A) Mailto block instead of "Binnenkort"
- B) Keep the dimmed "Binnenkort" view
- X) Other
[Answer]: B - Keep the existing dimmed "Binnenkort" gate (Bryan).
## Question 8: Testing against the server
- A) Mocks in CI + manual check against the temporary environment
- B) Mocks only
[Answer]: A
@@ -0,0 +1,44 @@
# Requirements: contact-form-cms
## Intent analysis
- **User request**: Build the own contact form for Andrea Slop Fotografie on the CMS contact module, using the headless `cms-client` package from the SlpSoftware repo (read only, copied here).
- **Request type**: New feature on existing code (brownfield). Replaces the "no back-end yet" stub from `contact-page`.
- **Scope**: Web repo only (components, content, CSP, dev proxy, tests, docs). Server work is requested from other sessions, not built here.
- **Complexity**: Moderate to complex: public endpoint with personal data, captcha, prerender/hydration constraints, cross-session contract.
- **Depth**: Standard, security-relevant. User Stories skipped (one persona: the visitor).
## Decisions (see requirement-verification-questions.md)
Security Baseline: enforced. PBT: partial (PBT-02, 03, 07, 08, 09). Operations: included. Package replaces the form's own state and validation. Subject is the readable label. Friendly Captcha built now. Gate stays the dimmed "Binnenkort" view. Tests: mocks in CI plus manual against the temporary environment.
## Functional requirements
- **FR-CF-01 Package**: Copy `src/cms-client/` (http/, contact/, README, boundary test) into `web/src/cms-client/`. It stays headless and imports nothing from the app (boundary test plus ESLint rule). The copy is kept in sync with the SlpSoftware original; no local forks of its logic.
- **FR-CF-02 Logic**: `useContactForm` drives the existing Chakra skin (fields, select, PrivacyNote, success state with `replyTime`). The old `contactFormReducer`, own validation and the `submitContactForm` stub are removed or reduced to a thin mapping.
- **FR-CF-03 Field mapping**: naam to name (max 100), email to email (254), shoot to subject (the readable label, 1-100, e.g. "Newborn shoot", "Overig"), bericht to message (2000). The package id stays local for the `?pakket=` preselect. Messages are the package's NL messages.
- **FR-CF-04 Availability (progressive enhancement)**: The prerendered/initial render is the gate ("Binnenkort"). After hydration and when the form scrolls into view (IntersectionObserver) the client calls `GET /api/v1/contact-messages/token`; only on `200` (and a captcha provider this site supports) does the form become active. Any other result (404 form closed, 429, 5xx, network, unsupported captcha) keeps the gate. `siteContent.contactForm.enabled` stays as an extra static kill switch (default false until Bryan's go). When it is `false`, the client makes NO token request at all (no network traffic, no server cost). The token is fetched lazily when the form comes into view (IntersectionObserver); first focus is only the fallback where IntersectionObserver is missing.
- **FR-CF-05 Layout stability**: No layout shift on upgrade; the existing placeholder heights stay valid. No token, widget or e-mail address in the prerendered HTML.
- **FR-CF-06 Submit**: `POST /api/v1/contact-messages` with `Idempotency-Key`, honeypot `hpCheck` (client side only the honeypot; the 3 s browser time check is dropped, the server enforces `minSeconds` through the token), one automatic token refresh on `errors.token = expired`, `202` means success. Server field errors map to the fields; focus moves after render (inputs are disabled while sending). Error messages are not placed inside `<label>`.
- **FR-CF-07 Failure**: 429, 5xx, 503 or network errors give a generic failure message with the mailto fallback; visitors never see technical text. The 429 message comes from the package (Retry-After in minutes), no own text. The mailto fallback after a failed send keeps the address out of the HTML (the `useEmailAddress` approach stays).
- **FR-CF-08 Preselect**: A package chosen via a "Boek..." link before the form has mounted is not lost: `ContactPanel` remembers the last preselect and passes it as initial value.
- **FR-CF-09 Captcha (Friendly Captcha)**: When the token endpoint returns `captcha = {provider, siteKey}`, the widget is shown client-only after hydration in a reserved height, its token goes to `captchaToken`, and it resets on expiry. The package provides the slot (SLP Software - SLS - Main), the server verifies (SLS Software - CMS); this feature builds the widget, loads it only when needed, and adds the CSP entries for the exact provider and version. Fail-open on a provider outage is a server decision already taken.
- **FR-CF-10 Privacy**: The privacy statement names the captcha provider and what the form stores. No personal data in logs, Sentry or Umami; only the events `contact-sent` and `contact-failed`.
- **FR-CF-11 Dev proxy**: Vite dev proxy for `/api` to the temporary environment (`http://192.168.1.2:5290`). Production is same-origin through the host/IIS proxy; no CORS.
- **FR-CF-12 Accessibility**: Labelled fields, focus handling for errors, live region for success/failure, honeypot hidden from assistive tech, keyboard operable, widget with reserved height.
## Non-functional requirements
- **NFR-CF-01 Security** (Security Baseline enforced): CSP `connect-src 'self'` plus captcha origins only (script/frame entries per provider and version, nothing wider); no secrets in the client (the siteKey is public); no personal data, tokens or idempotency keys logged; input limits identical to the server; honeypot and idempotency handled; dependency audit stays clean.
- **NFR-CF-02 Performance**: No new JS on pages without a form in view; the captcha script loads only when the form is active; Lighthouse budgets of `lighthouserc.cjs` stay green.
- **NFR-CF-03 Testing**: Unit and component tests for mapping, gate states, preselect and submit paths with a mocked API; fast-check on mapping/validation round-trips (PBT-02/03/07/08/09); e2e with a mocked `/api` route; manual verification against the temporary environment (CMS 192.168.1.2:5175, API :5290, smtp4dev :5301) with evidence in the construction docs. Tests of the old reducer are replaced. Extra cases: an unknown or missing captcha provider keeps the gate; an expired captcha token is never sent; every subject label is 1-100 characters and a label containing & ' " < > does not break the payload (mail encoding is server-side, the payload is tested here).
- **NFR-CF-04 Compatibility**: Works with hydration of the prerendered site (PR #14); no hydration mismatch; with JS off the gate and the mail button show.
- **NFR-CF-05 Operations**: CSP and dev-proxy changes deploy through the existing pipeline; production stays off (`enabled: false`) until Bryan's explicit go; rollback is switching `enabled` off; checklist in the Operations phase.
## Out of scope / asked of others
- Server module, captcha verifier, openapi (SLS Software - CMS); package captcha slot (SLP Software - SLS - Main).
- Per-site server config for ASF: `Contact__RecipientEmail` (env only), sender in `Email:AllowedFromAddresses`, `ForwardedHeaders:KnownProxies`/`ClientPartitionKey` on IIS, `Contact:Enabled`, `MinSeconds`, retention, CMS switch (session `AndreaSlopFotografie`, routed by SLP Software - SLS - Main).
- ASF production hosting (IIS) and the production go-live.
## Resolved with SLP Software - SLS - Main (approved on behalf of Bryan, 2026-11-10)
1. Lazy token fetch via IntersectionObserver (first focus only as fallback).
2. Friendly Captcha: provisionally v2 (bundled SDK, script-src 'self'; API origin https://global.frcapi.com in connect-src and possibly frame-src; possibly worker-src blob: and 'wasm-unsafe-eval'). Final directives per version come from CMS-U9 and a test in a real browser; no wildcards.
3. Labels come from the existing shoot options in content; the label of "Overig" is fixed per site.
4. Package captcha slot: the token response carries `captcha {provider, siteKey}` or null; the hook offers `setCaptchaToken(token|null)` and `captchaRequired`; an expired token means `setCaptchaToken(null)` and a widget reset. The final package is copied only after SLS-Main reports the branch and commit.
5. Server side for ASF is done by SLS Software - CMS (module, captcha) with AndreaSlopFotografie (host); an ASF test host with the endpoint exists only after the CMS branch is merged and deployed (not requested yet).
@@ -0,0 +1,32 @@
# Deployment plan: contact-form-cms
Scope: the web change only. The server module and host configuration are delivered by other sessions.
## Method
The existing Gitea pipeline (continuous_integration.yaml). A push to master deploys the test site and ASF test; production only by manual dispatch. Nothing is merged or deployed without Bryan (a test deploy of the feature branch is allowed on request of Bryan or SLP Software - SLS - Main).
## What changes on deploy
- Site bundle with the form (lazy chunks), cms-client package, captcha widget chunk, new `frame-src` in the generated server configs (`web/deploy/iis/web.config`, `web/deploy/nginx/*.conf`, regenerated with `pnpm server-config`).
- `siteContent.contactForm.enabled` stays `false` in the merge: the site then asks the server nothing and shows the "Binnenkort" gate.
## Server side prerequisites for turning it on (not built here)
| Item | Owner |
|---|---|
| Contact module in the ASF host, `openapi/andreaslopfotografie.v1.json` | SLS Software - CMS |
| `Contact__RecipientEmail` (env only), sender in `Email:AllowedFromAddresses`, `Contact:Enabled` + CMS switch, `MinSeconds`, retention 1 year / 30 days spam | AndreaSlopFotografie (host) |
| `ForwardedHeaders:KnownProxies` / `ClientPartitionKey` on IIS | AndreaSlopFotografie (host) |
| ASF host CSP `frame-src`: global, global0, global1 (`AllowedSiteFrameOrigins__0..2`) | AndreaSlopFotografie (host) |
| Recipient address: later from the CMS site settings (CMS-U11, in preparation) with the environment variable as fallback | SLS Software - CMS |
| Captcha: verifier configured with the secret; free key only for tests, paid plan before commercial use | Bryan / SLS Software - CMS |
## Rollback
Set `siteContent.contactForm.enabled = false` and redeploy (the gate returns, no token request). The server can also close the form (`Contact:Enabled` off answers 404, which keeps the gate). Captcha problems are handled by the form itself (message plus mail button).
## Test deploy steps (on request)
1. Merge or deploy the feature branch to the ASF test site through the pipeline (switch on only if the test host serves the contact endpoint).
2. Run the real-browser check from the build and test instructions against the test host.
## ASF test host (Pi-Main)
- Environment file: `/home/gitea-workflow/apps/andreaslopfotografie/test/shared/env`; restart through the systemd user unit `andreaslopfotografie-test`. Details in the SlpSoftware repo, `construction/contact-form/operations/host-config-checklist.md` (read only; owned by SLP Software - SLS - Main).
- `ForwardedHeaders:KnownProxies` for ASF test is already `192.168.1.102` (the proxy Pi).
- A test deploy of the feature branch and a pull request are NOT requested yet: Bryan has not finished the local ASF test. SLP Software - SLS - Main reports when he wants a test host deploy.
@@ -0,0 +1,7 @@
# Monitoring plan: contact-form-cms
- **Events (Umami)**: only `contact-sent` and `contact-failed`, names only. No field values, token, idempotency key or captcha response anywhere in analytics, logs or Sentry.
- **Sentry**: the existing browser setup stays; the form logs nothing itself. Check once on the test site that a failed send does not put form values into a breadcrumb or event (Build and Test of the next deploy).
- **Server side (CMS)**: the contact module's message list (status, mail status, attempts) is the operational view; failed mails and spam counts are watched there. Owner: CMS sessions.
- **Watch after go-live**: ratio `contact-failed` to `contact-sent` in Umami; messages with mail status `failed`; captcha problem message shown (not counted separately, visible through failed sends).
- **Alerts**: none new on the web side; mail failures are shown in the CMS admin.
@@ -0,0 +1,32 @@
# Production readiness checklist: contact-form-cms
Status (2026-11-16): web side closed and merged with feature/asf-packages-cms; this checklist is part of the joint production checklist (docs/go-live-checklist.md). NOT ready for production (go-live conditions open). The form is closed in production: it opens only when the build sets `VITE_CONTACT_FORM_ENABLED=true` (only the test build does), and that needs Bryan's explicit go.
## Done (web)
- [x] Form on the headless `cms-client` package, no forked logic; import boundary enforced
- [x] No request to the server while the switch is off; token only when the form is near the screen
- [x] No token, widget or e-mail address in the prerendered HTML (tests)
- [x] Honeypot, idempotency key, one token refresh, server-side time check, captcha slot with fail-safe message and mail button
- [x] CSP: `frame-src` with exact global, global0, global1 hosts; no wildcard; real-browser run without violations
- [x] No personal data in analytics/logs; events limited to `contact-sent`/`contact-failed`
- [x] Tests: unit, component, property, e2e, real-browser widget run; lint, format, audit clean; Lighthouse as before
- [x] Dependency: `@friendlycaptcha/sdk` 1.1.3 (MPL-2.0), audit clean
## Go-live conditions (all must be true; Bryan decides)
- [ ] **Full ASF privacy statement published** (separate feature; the form text in `privacy-statement-draft.md` is input; mail provider and widget data still to check). Not needed for testing, required before go-live.
- [ ] **Captcha decision**: off at go-live until a paid Friendly Captcha plan exists (free key is for testing only); with the EU endpoint the CSP gets eu, eu0, eu1 and the privacy text changes.
- [ ] Server: recipient address from the CMS site settings (CMS-U11, in preparation) with the environment fallback; contact module deployed on the ASF host, recipient and sender configured, retention 1 year / 30 days spam, proxies/partition key set, host CSP `frame-src` set.
- [ ] ASF test host (Pi-Main): env file `/home/gitea-workflow/apps/andreaslopfotografie/test/shared/env` set, systemd user unit `andreaslopfotografie-test` restarted, `KnownProxies` 192.168.1.102 (already set).
- [ ] A real mail from the production host checked (SPF/DKIM, "toon origineel") and the message visible in the ASF CMS.
- [ ] Test of the form on the deployed ASF test host with the real server (after the CMS branch is merged and deployed).
- [ ] ASF production hosting (IIS) in place (separate feature).
- [ ] Bryan's explicit go, then the production build gets `VITE_CONTACT_FORM_ENABLED=true` in its own reviewed change.
## Rollback
unset `VITE_CONTACT_FORM_ENABLED` and redeploy, or `Contact:Enabled` off on the server (404 keeps the gate).
## Risks and notes
- Free captcha tier must not be used commercially.
- The global endpoint processes IP addresses possibly outside the EU; EU needs the paid plan.
- With the switch on, a closed form (404) logs one console message per page view in the browser.
- Hydration e2e tests run with the switch off; if it is on, they need the API mocked.
@@ -832,16 +832,6 @@ p:last-child { margin-bottom: 0; }
.price-card .btn { align-self: center; margin-top: auto; }
/* Decoratieve illustraties uit het thema */
.pricing__deco {
position: absolute;
z-index: 0;
width: clamp(90px, 10vw, 160px);
opacity: .55;
pointer-events: none;
}
.pricing__deco--1 { top: 8%; left: 2%; }
.pricing__deco--2 { bottom: 6%; right: 3%; }
.pricing .container { position: relative; z-index: 1; }
/* ==========================================================================
Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

@@ -47,6 +47,4 @@ portfolio-8.jpg https://andreaslop.nl/wp-content/uploads/2026/04/F41A7284_websiz
# --- Lieve woorden: hergebruikt hero-5.jpg (Trouwshoot) en portfolio-6.jpg (Newbornshoot) ---
# --- Decoratie prijzensectie ---
deco-1.png https://andreaslop.nl/wp-content/uploads/2020/01/landing-img-18.png
deco-2.png https://andreaslop.nl/wp-content/uploads/2020/01/h1-img-16.png
# --- Decoratie prijzensectie: weggelaten (themabeelden, licentie; zie docs/assets-and-licenses.md) ---
-2
View File
@@ -181,8 +181,6 @@
<!-- ======================================================= Prijzen -->
<section class="section pricing">
<img class="pricing__deco pricing__deco--1" src="assets/img/deco-1.png" alt="" aria-hidden="true" loading="lazy">
<img class="pricing__deco pricing__deco--2" src="assets/img/deco-2.png" alt="" aria-hidden="true" loading="lazy">
<div class="container">
<div class="section__head section__head--center reveal">
+17
View File
@@ -0,0 +1,17 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 143 112" width="143" height="112" fill="none" stroke="#7f8b76" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
<path d="M6 100 C40 92 80 60 128 22"/>
<path d="M25.0 93.5 C38.1 90.9 41.8 75.7 33.0 68.7 C21.8 69.2 15.9 83.6 25.0 93.5 Z" fill="#7f8b76" fill-opacity=".10"/>
<path d="M42.8 84.2 C45.4 96.0 59.4 99.4 65.7 91.6 C65.1 81.6 51.7 76.2 42.8 84.2 Z" fill="#7f8b76" fill-opacity=".10"/>
<path d="M64.2 70.6 C75.2 66.5 75.9 53.3 67.0 48.8 C57.3 50.8 54.6 63.8 64.2 70.6 Z" fill="#7f8b76" fill-opacity=".10"/>
<path d="M86.9 54.1 C90.1 64.0 102.0 65.4 106.5 57.9 C105.1 49.3 93.5 46.1 86.9 54.1 Z" fill="#7f8b76" fill-opacity=".10"/>
<path d="M108.3 37.6 C116.4 33.6 116.3 22.8 109.5 19.6 C102.3 21.8 100.8 32.5 108.3 37.6 Z" fill="#7f8b76" fill-opacity=".10"/>
<path d="M128.0 22.0 C135.5 25.0 142.7 18.4 140.7 11.9 C134.9 8.5 126.8 14.0 128.0 22.0 Z" fill="#7f8b76" fill-opacity=".10"/>
<g stroke-width="1" opacity=".7">
<path d="M25.0 93.5 L30.6 76.2"/>
<path d="M42.8 84.2 L58.8 89.4"/>
<path d="M64.2 70.6 L66.2 55.3"/>
<path d="M86.9 54.1 L100.7 56.7"/>
<path d="M108.3 37.6 L109.2 25.0"/>
<path d="M128.0 22.0 L136.9 15.0"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.2 KiB

+23
View File
@@ -0,0 +1,23 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 239 224" width="239" height="224" fill="none" stroke="#7f8b76" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 214 C60 196 120 140 214 26"/>
<path d="M26.8 207.4 C41.2 199.0 39.2 186.1 35.6 174.6 C26.7 182.8 18.6 192.9 26.8 207.4 Z" fill="#7f8b76" fill-opacity=".10"/>
<path d="M42.4 198.5 C46.9 215.9 68.1 220.3 77.1 208.2 C75.7 193.2 55.3 185.9 42.4 198.5 Z" fill="#7f8b76" fill-opacity=".10"/>
<path d="M60.8 185.7 C73.4 174.9 69.3 162.6 63.7 151.8 C56.3 161.4 50.1 172.8 60.8 185.7 Z" fill="#7f8b76" fill-opacity=".10"/>
<path d="M80.5 169.7 C86.9 186.3 107.4 187.3 114.2 174.0 C110.9 159.4 90.9 155.3 80.5 169.7 Z" fill="#7f8b76" fill-opacity=".10"/>
<path d="M101.7 150.4 C113.1 138.8 107.5 127.8 100.8 118.4 C94.6 128.2 89.7 139.5 101.7 150.4 Z" fill="#7f8b76" fill-opacity=".10"/>
<path d="M124.7 127.5 C131.7 142.1 149.7 141.3 154.7 128.6 C150.6 115.5 132.7 113.5 124.7 127.5 Z" fill="#7f8b76" fill-opacity=".10"/>
<path d="M149.5 100.9 C159.0 90.1 153.4 80.9 146.7 73.1 C141.8 82.0 138.1 92.2 149.5 100.9 Z" fill="#7f8b76" fill-opacity=".10"/>
<path d="M176.5 70.5 C182.7 80.8 197.0 79.5 200.5 70.0 C196.7 60.8 182.3 60.0 176.5 70.5 Z" fill="#7f8b76" fill-opacity=".10"/>
<path d="M214.0 26.0 C224.7 27.8 232.2 17.2 227.7 9.3 C219.2 6.5 210.2 15.9 214.0 26.0 Z" fill="#7f8b76" fill-opacity=".10"/>
<g stroke-width="1" opacity=".7">
<path d="M26.8 207.4 L32.9 184.5"/>
<path d="M42.4 198.5 L66.7 205.3"/>
<path d="M60.8 185.7 L62.8 162.0"/>
<path d="M80.5 169.7 L104.1 172.7"/>
<path d="M101.7 150.4 L101.0 128.0"/>
<path d="M124.7 127.5 L145.7 128.3"/>
<path d="M149.5 100.9 L147.6 81.4"/>
<path d="M176.5 70.5 L193.3 70.2"/>
<path d="M214.0 26.0 L223.6 14.3"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.8 KiB

+90
View File
@@ -0,0 +1,90 @@
# Assets: source and licence
Where the images, icons and fonts of the site come from. Status "owner" means made or owned by Andrea or Bryan as far as the repo shows; "to confirm" means the repo does not prove it and Bryan has to check. This is an overview of what the repo shows, not legal advice.
Last checked: 2026-11-15.
## Decorative twigs on the home page: removed (theme images, licence)
Status 2026-11-15 (decision of Bryan): left out. `deco-1.png` and `deco-2.png` are removed from the site (Pricing section and the banner under the cards) and from the repo, including the copies in `design/andreaslop-static/assets/img` (with their `<img>` tags, the `.pricing__deco` CSS and the manifest lines there). The reason is the licence below. Own replacements are kept in reserve and not built in: two SVG line drawings in the brand green, `design/own-assets/twig-1.svg` and `twig-2.svg` (drawn for this project, free of rights, not used by the site) and the options public-domain illustrations or a commissioned illustration. The site works without them: no empty space and no shifting (checked on desktop and phone, with and without banners). The earlier commits still contain the PNG files in the git history; they are not in the working tree or in any new build.
The record of what they were:
| File | Used by | Source recorded in the repo |
| -------------------------------------------- | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| `web/src/assets/home/deco-1.png` (143 x 112) | Pricing section (top left) and the banner under the cards | `design/andreaslop-static/assets/img/manifest.txt`: `https://andreaslop.nl/wp-content/uploads/2020/01/landing-img-18.png` |
| `web/src/assets/home/deco-2.png` (239 x 224) | Pricing section (bottom right) | same manifest: `https://andreaslop.nl/wp-content/uploads/2020/01/h1-img-16.png` |
What the repo shows:
- The files are byte-identical to the ones in `design/andreaslop-static/assets/img/`, which a download script copied from the live WordPress site (design committed 2026-09-27; used in the site since 2026-10-20, the Pricing section).
- `design/andreaslop-static/README.md` says the live site is "WordPress + Solene-thema". The design stylesheet calls these images "Decoratieve illustraties uit het thema" (decorative illustrations from the theme).
- The upload names `landing-img-18` and `h1-img-16`, uploaded in January 2020, look like demo content of a theme (a "landing" page and a "h1" home page variant), not like files the owner made. The owner's own photos in the same manifest have camera names (`F41A...`, `DSC_...`).
- The PNG files carry no author, copyright or licence metadata.
- Not verified: whether these exact files appear in the theme's public demo. The demo site could not be reached from here and a search for the file names found nothing; Bryan can compare them with the theme package he downloaded as buyer.
### The theme and its licence (public information, read 2026-11-15; not legal advice)
- The theme: [Solene - Wedding Photography WordPress Theme](https://themeforest.net/item/solene-wedding-photography-theme/25611487) on ThemeForest (Envato), author Elated-Themes. The item page shows a Regular License for "use, by you or one client, in a single end product which end users are not charged for", and says the item is "licensed 100% GPL". Its update log (version 2.4) mentions "images licensed for digital use on websites made with Solene theme". It includes the plugins WPBakery Page Builder and Slider Revolution, and icon packs (Font Awesome, Font Elegant, Linea, Ion Icons).
- The [Envato Regular License](https://themeforest.net/licenses/terms/regular): an Item is the digital work bought (here the theme); an End Product is the customised implementation of it (here the website with its content). One licence covers one End Product, for yourself or one client. Modifying the Item and combining it with other works is allowed as long as the result is a permitted End Product. Not allowed: redistributing or making available the Item "as-is or with superficial modifications", extracting a single component (such as an icon) for standalone use, and letting end users extract the Item from the End Product. Clause 13: third-party components that the author took from elsewhere keep their own licence (for example images under Creative Commons). Clause 14: for WordPress themes the open source (GPL) licence may apply to part of the item (a "split licence") or, when the item is fully GPL, to the entire item instead of the Envato licence.
- What this means for the twigs (reading of the public text, to be confirmed by Bryan): (1) The live site is an End Product made with the theme; the images belong to the theme and are licensed for use on websites made with it. (2) The new site is a rebuild that does not run on the theme. Copying a theme graphic into it is extracting a component of the Item for use outside the End Product it was licensed for; the "100% GPL" label applies to the theme's code, and it does not obviously give the graphics a free licence for any other use. (3) The licence does not address a rebuild of the End Product at all, so it can not be assumed that a rebuild by the same owner is covered. Because of this the twigs are treated as not cleared.
- What Bryan still has to check: which licence was bought for Solene (regular or extended), on whose name (Andrea, a company, the previous web builder) and for which End Product (andreaslop.nl); whether the theme package he can download as buyer has a licence or readme that says how the demo images and graphics are licensed (split licence, "images licensed for digital use on websites made with Solene"); whether Andrea herself ordered or bought the twigs separately; and whether the previous web builder owes him a licence statement.
- Safe choice: do not use the twigs on the new site until that is settled. Replace them with something whose source and licence is recorded: a drawing made for this project, a public-domain/CC0 illustration with its source, or an illustration made or bought with a commercial licence. Fonts, icons and patterns of the theme are not used (see below), so the twigs are the only theme-derived asset the repo shows.
Nothing has been removed or replaced.
### Licence files of the theme package (supplied by Bryan, 2026-11-15)
Bryan holds a Regular License for the theme and supplied the licence files of the theme package. They are not stored in this repo; this is what they say.
- `README_License.txt` and `README_License_1.txt` (two versions of the same notice): the theme "is comprised of two parts": (1) the PHP code and integrated HTML are licensed under the GPL; (2) "all other parts of the theme including, but not limited to the CSS code, images, and design are licensed according to the license purchased" (the Envato licence, here Regular: one end product). `GPL.txt` is the GPL v2 text.
- So the "licensed 100% GPL" label on the item page covers the PHP code and HTML only. The images and the design are under the purchased Regular License, for the one End Product they were bought for (the existing WordPress site). They are not free to reuse in a rebuild that does not run on the theme.
- Two Envato certificates, for Slider Revolution and WPBakery Page Builder, are Extended licences held by the theme maker (licensee QODE LTD, purchase date 2020-01-21). They are not Bryan's and not relevant: the new site uses neither plugin. They do show that the theme package was put together in January 2020, the month in which the twig files were uploaded to the live site (`wp-content/uploads/2020/01/`), which fits the twigs being part of the theme's demo content.
- The design README also says that the live contact page still carried two links from the Solene demo (a `mailto:` to the theme maker and a dummy phone number), which shows that the live site contains demo content that was never replaced.
Conclusion for Bryan to confirm: the twigs are images from the theme and fall under the Regular License of the existing site, not under the GPL. They must not stay in the rebuild unless the licence clearly allows it (the Envato terms do not address rebuilding an End Product, and forbid taking single components out of the Item). Treat them as not cleared and replace them (see the proposal).
### What else was taken from the theme: checked
- `design/andreaslop-static` (CSS, JS, HTML, README): written for this project, not a copy of the theme. Its stylesheet and script have their own structure and comments (BEM class names, own tokens); there are no theme class names, file names or code (searched for the theme and plugin vendor names, `qodef`, `vc_`, `rev_slider`, `wpb`, `themeforest`, `envato`). The only mentions are comments ("Solene is hoekig") and the README.
- Colours, fonts and spacing: the design README says that the exact theme settings are in the WordPress database and could not be read, and that the values in the stylesheet are the designer's own interpretation ("De gekozen richting"): warm paper, heidegroen accent, Marcellus and Jost (both free Google Fonts under the SIL Open Font License). No colour value, font or spacing was read from theme files.
- Layout: rebuilt from what the live site shows publicly (sections, order, texts), with new markup and styles. The layout of the owner's own website and its texts are the owner's; the theme's specific page designs are not copied.
- Fonts, icon fonts and plugins of the theme (Font Awesome, Font Elegant, Linea, Ion Icons, WPBakery, Slider Revolution): not used.
- Safe approach going forward: keep theme files out of git (no theme zips, no extracted theme images or CSS); do not download assets from the live site without recording the source and licence in this document first; only the twigs are theme-derived.
- Remaining check: the downloaded images in `design/andreaslop-static/assets/img` also include the owner's photos; the ones the manifest lists with `wp-content/uploads/2020/01/` (the twigs) are the only theme-named files. `loveshoot.jpg` (hash file name) is still to be confirmed with Andrea.
## Other images
| Asset | Where | Source and status |
| -------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Hero photos `hero-1..8.jpg`, intro photos, portfolio photos (`src/assets/portfolio`), shoot photos (`src/assets/shoots`), about and contact photos | pages of the site | Camera file names (`F41A...`, `DSC_...`, `IMG_...`) and WhatsApp images of the owner, taken from the live site. Owner, to confirm with Andrea. People shown: consent for use on the site is Andrea's to confirm. |
| `shoots/loveshoot.jpg` (from `.../2025/08/e77ff000dce5a31c0a38c5d824bfdb95.jpeg`) | loveshoot page, shared photo | Hash file name, no camera name: origin unclear (client delivery, other photographer or stock?). To confirm. |
| `src/assets/logo-dark.png`, `src/assets/logo-light.png`, `public/favicon.png`, `public/logo.png` | header, footer, favicon | Andrea's logo (on the live site uploaded in 2025). Owner, to confirm who designed it. |
| `public/og-*.jpg` | link previews | Made from the owner's photos (see above). |
| `public/icons.svg` | not used anywhere in `src` | Left over from the Vite starter (Bluesky, GitHub and other icons). Not part of the design; can be deleted. |
| Process icons (`components/shoots/ProcessIcons`) | shoot pages | Inline 24 px stroke icons, no source recorded. Plain geometric strokes; to confirm that they were drawn for this project. |
| Social icons in the hero and footer | hero, footer | Platform logos of Instagram and Facebook as small icons; platform trademarks, used only to link to the profiles. |
## Other visual elements (checked 2026-11-15)
| Element | Where | Origin |
| ---------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| Section ornament (diamond between two hairlines), top rule of banners, framed photo blocks, timeline | `PriceBanner`, `PriceTopBar`, `FramedImage`, `ProcessTimeline` | Drawn in code (CSS borders and rotated squares) for this site. No image files. |
| Dividers, backgrounds, patterns | whole site | CSS colours and borders only; no background images or patterns. |
| Colour palette | `src/theme.ts` | From the design stylesheet that was made from the live site. Colour values are not protected as such. |
| Layout and texts | pages | Rebuilt by us from the owner's site; no theme CSS or theme code was copied (the stylesheet mentions the theme only in a comment: "Solene is hoekig"). |
| Slider, lightbox, form, carousel | components | Written for this site (no theme plugins such as Slider Revolution or WPBakery). |
| Icon packs of the theme (Font Awesome and others) | not used | The site uses a few inline SVG icons (process steps, arrows, social links) and no icon font. |
## Fonts
Cormorant Garamond (headings, weights 500 and 600) and Mulish (text, nav and buttons, weights 300, 400 and 500), the main fonts of the live site, self-hosted through the npm packages `@fontsource/cormorant-garamond` and `@fontsource/mulish` (version 5.3.0). Both fonts are Google Fonts under the SIL Open Font License 1.1 (free for commercial use and for self-hosting; the licence text ships in the packages), so there is no theme licence involved. Only the latin subset and the weights in use are loaded (about 100 KB of WOFF2 in total), with no request to Google. The previous fonts, Marcellus and Jost, were replaced.
- Layout shift: `src/fonts.css` defines two fallback faces ("Cormorant Garamond Fallback" on Georgia, "Mulish Fallback" on Arial) with `size-adjust`, `ascent-override` and `descent-override` computed from the font files, so the text barely moves when the web fonts arrive (measured layout shift of the pages: 0.001 to 0.016 on desktop and phone, as before).
- Size: Cormorant Garamond has a smaller x-height than Marcellus (0.386 against 0.50), so every use of the heading font carries `font-size-adjust: 0.43` (about 12% larger letters; browsers that do not know the property show the font at its natural size). Prices use lining numerals (`font-variant-numeric: lining-nums`), because the default figures of Cormorant Garamond are old-style. Headings use weight 500 instead of 400 (Cormorant is thin at 400).
- No font preload is used (the images are the largest content of the first screen); the fallback metrics keep the first paint stable.
- The CSP is unchanged (`font-src 'self'`).
## When you add an image
Add a row here with its source (URL or "own photo"), the licence and who checked it. Record the same in the commit message. Do not copy images from the old site or from a theme without checking the licence first.
+60
View File
@@ -0,0 +1,60 @@
# CMS integration
The site talks to the SLP CMS host through its API. On the test host the CMS host serves the site itself, so every call is same-origin (`/api/v1/*`, CSP `connect-src 'self'`, no CORS). Three things come from the CMS: the shoot packages, two banners and the contact form.
## Shoot packages
Source: `GET /api/v1/offerings`. One list feeds the price cards on the home page and on the pages for each shoot type, the "welke shoot" choices of the contact form and the `?pakket=` check, so they can never disagree.
- **Any number of packages.** The cards are a wrapping flex row. On desktop (`lg` and up) every card is a third of the row (`calc((100% - 2 * gap) / 3)`) and every row is centred, so an incomplete last row (4, 5, 7, 8, 10 cards, ...) sits in the middle. There is no styling per number of cards. On phone and tablet the cards are one column; there is no swipe row.
- **Mapping** (`web/src/lib/offerings.ts`, pure functions): `slug` is the package id (kept `zwangerschap`, `newborn`, `gezin`: they appear in `?pakket=` and the form), `title` the name, the free price text is read as whole euros ("€ 175", "€ 1.250", "175,-"). A card with an unreadable price, no features or a bad slug is skipped. Order follows `displayOrder`. Empty `description`, `priceNote` and `ctaLabel` are accepted and left out of the card.
- **Where the data comes from, in order:**
1. At build time `web/config/fetchOfferings.ts` (the first step of `pnpm build`) asks `OFFERINGS_URL` (10 s timeout, 2 attempts) and writes the gitignored `web/src/content/offerings.generated.json`. The packages are baked into the prerendered HTML (search engines see the prices, no layout jump).
2. Without `OFFERINGS_URL`, with a CMS that is down or with an unusable answer, the committed `web/src/content/offerings.snapshot.json` is used. The build never fails and never shows empty prices; the log says which source was used. Tests always use the snapshot.
3. After hydration `PackagesProvider` (`web/src/components/PackagesProvider/`) asks the CMS once and replaces the baked list only if the answer differs. A network error, time-out (8 s), bad status or invalid answer keeps what was baked. A change in the CMS therefore shows at once; the nightly build only matters for search engines.
- **Featured package** (the star in the CMS admin, field `featured`): the card gets a heidegroen rule along its top, a heidegroen border and a small "Uitgelicht" tab on the top edge (`PriceCard`). The tab is positioned on the border, so the cards of a row keep the same layout. Any number of cards may be featured.
- **Description, price note and button label** (`description`, `priceNote`, `ctaLabel`) are optional in the CMS and the site does not use them: they are not shown and a card never depends on them (empty, `null` or absent all give the same card; covered by tests).
- **Scheduling in the CMS:** the API only returns packages that are live at the moment of the request (switched on and inside their from/to dates), so the site shows them and nothing else. The baked list reflects the moment of the build; the live refresh after hydration corrects it for every visitor, and the nightly build corrects it for search engines. A package that goes live or expires between two builds is therefore right in the browser but can be stale in the HTML until the next build.
- **Keep the snapshot current** when the real packages change (prices, features), because production builds use it (see "Hosting" below).
## Banners (OfferingBanner)
Source: `GET /api/v1/offerings/banner?position=top|bottom`. No parameter means `bottom`; `204` means no active banner; an invalid value is `400`. Answer fields: `title` (at most 100 characters), `text` (at most 300 for bottom, 120 for top), `linkLabel`, `linkUrl` (both or neither; `https://` or a path on the site with one `/`) and `position`. Both banners may be active and visible at the same time.
| | Under the cards (`bottom`) | Above the cards (`top`) |
| --------- | --------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| Component | `PriceBanner` | `PriceTopBar` |
| Look | Light band, thin heidegroen top rule, section-heading title, ornament, deep-green link button | Slim white bar, same hairline and top rule, one line: small capitals title, diamond, text, small underlined link |
| Required | title | title or text (title may be empty) |
| Mapping | `mapBanner` | `mapTopBanner` |
Both follow the same rules as the packages: baked into the HTML at build time, replaced live after hydration, empty fields are hidden, an error or invalid answer keeps what was baked. A `204` hides that banner (the one deliberate exception to "keep what was baked"); the two banners are independent of each other. Neither banner is a package: not in the form choices, not in the package count.
**Layout shift:** a banner that was not active at the last build is not in the HTML. When it appears live, the content below it moves down by its height once (for the top bar, the cards move). Rebuilding with the banner active (the nightly test build does this) removes the shift. The same holds in reverse when a baked banner is switched off.
## Contact form
`GET /api/v1/contact-messages/token` and `POST /api/v1/contact-messages` through the headless `web/src/cms-client`. The form is behind the switch `contactForm.enabled` in `web/src/content/siteContent.ts` (off means the "Binnenkort" gate and no request to the server). Details and the go-live conditions are in `aidlc-docs/features/contact-form-cms/` and [go-live-checklist.md](go-live-checklist.md). Friendly Captcha is off at go-live.
## Hosting: the CMS host serves everything
Decision (Bryan, 2026-11-15): the hosting package has one entry per website. The CMS host (Kestrel) is that entry and serves the website itself (the prerendered pages), `/admin` and `/api/v1/*`. In production IIS (or the proxy) therefore passes **all** requests to the CMS host, not only `/api/v1/*`, and serves no static files or HTML cache of its own. This holds for the test host and for ASF production alike.
- **Test (ASF):** nginx on the proxy Pi forwards everything for `test.andreaslop.nl` to the CMS host (`web/deploy/nginx/test.andreaslop.nl.proxy.conf`), which serves the site files and the API. Nothing to add.
- **Production: not in place yet.** The generated `web/deploy/iis/web.config` and the FTP upload of static files (`web/deploy/upload-production.sh`) still describe the old idea of IIS serving the files. They have to change with the production hosting: IIS keeps only the redirects (www, HTTPS) and the pass-through to the CMS host, and the prerendered `dist/` goes to the CMS host's prerendered-pages folder as on test. Security headers then come from the CMS host (as on test). This is part of the production hosting work, not of the packages feature. Until then production builds use the committed snapshot and the live calls fail safely (the baked list stays; the browser console shows a 404 for the API). Change generated server files only in `web/config/serverConfig.ts` and run `pnpm server-config`.
- **Host injection (built in the site; the host side is the CMS repo's work):** the build leaves markers in the prerendered pages and the CMS host fills them from live data, so a CMS change is visible to search engines at once without a rebuild. Contract and plan: `aidlc-docs/features/asf-cms-host-injection/plan.md`; golden files for the list HTML: `web/contract/host-injection/`.
- Markers: `<!--CMS:DATA-->` + `<script type="application/json" id="cms-data">` (root document, every page), `<!--CMS:OFFERINGS-HTML-->`, `<!--CMS:BANNER-TOP-HTML-->` and `<!--CMS:BANNER-BOTTOM-HTML-->` regions (home page), `<!--CMS:OFFER-JSON-LD slug="...">` before the ld+json block of the newborn, zwangerschap and gezin pages, and `<span data-cms-price="slug">` in their price block.
- In the page: `CmsRegion` renders the plain HTML between the markers (`lib/cmsHtml.ts`, styled by `.cms-*` rules in `theme.ts`) and React leaves it alone until hydration, so a host that wrote different data causes no hydration mismatch; after hydration the styled components take over. `PackagesProvider` reads the data block in the first render after hydration (`hostCmsData`); a block with `"source":"build"` is the baked one and counts as "no host data", so the page asks the API as before. The site address comes from `siteUrl` in the block (`setSiteUrl` in `client.tsx`), because the script files cannot be rewritten per host.
- Tests: golden files (`src/lib/cmsHtml.test.ts`), a stand-in for the host (`config/hostInjector.ts`, also in the preview server as `--cms-data=<json>`) and browser tests with it (`e2e/hostInjection.e2e.ts`: HTML without JavaScript, hydration without errors, banners hidden on 204, JSON-LD price edited or removed, address changed and kept after navigation, unusable data, hostile text).
## Environment and variables
| Name | Where | Meaning |
| --------------------------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `OFFERINGS_URL` | build env | Site address that serves the API (for example `https://test.andreaslop.nl`). Unset gives the snapshot. |
| `ASF_OFFERINGS_URL_TEST` | Gitea repo variable | Value of `OFFERINGS_URL` for the test build. Set by SLS, not by feature sessions. |
| `API_PROXY_TARGET` | dev env | Forwards `/api` in `pnpm dev` to a CMS host. |
| `VITE_SITE_URL` | build env | Address the site presents itself under (canonical, og:*, JSON-LD, sitemap). Only the test build sets it (`https://test.andreaslop.nl`); unset gives `https://andreaslop.nl`. |
| `VITE_CONTACT_FORM_ENABLED` | build env | Opens the contact form when exactly `true`. Only the test build sets it; unset keeps the form closed (production). Opening it in production needs Bryan's explicit go, after the captcha decision ([go-live-checklist.md](go-live-checklist.md)). |
The production artifact is built without `OFFERINGS_URL` on purpose: production must never carry the prices of the test CMS.
+50
View File
@@ -0,0 +1,50 @@
# Deploy and CI
Pipeline: [.gitea/workflows/continuous_integration.yaml](../.gitea/workflows/continuous_integration.yaml). Branch strategy and rollback are in `aidlc-docs/features/frontend-shell/operations/deployment/` and `aidlc-docs/features/prerendering/`.
## Triggers
| Trigger | Result |
| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Pull request | Checks only, no deploy. |
| Push to `master` | Checks, then deploy to test. |
| Every night, 03:15 UTC (`schedule`) | Test build with the packages and banners from the test CMS, deploy to test, no Lighthouse. Gitea runs schedules only from the default branch, so this works after the packages feature is merged to `master`. Never production. |
| Manual (`workflow_dispatch`), any branch | Checks, and a deploy to test if `deploy_test` is on. |
| Manual from a `release/*` branch | Deploy to production if `deploy_production` is on. |
## Workflow inputs
- `deploy_test` (boolean, default false): "Deploy to Test". Builds the test artifact and deploys it to ASF test.
- `deploy_production` (boolean, default false): "Deploy to Production". Only works from a `release/*` branch and only with Bryan's explicit go.
Dispatch from the CLI (the token comes from your git credentials, never print it): `POST /api/v1/repos/SLP_Software/AndreaSlopFotografie/actions/workflows/continuous_integration.yaml/dispatches` with `{"ref": "<branch>", "inputs": {"deploy_test": "true"}}`.
## Jobs
1. `check`: lint, format, unit/property/axe tests (coverage threshold 100% on `src/lib/**`), build **without** `OFFERINGS_URL` (so with the committed snapshot), audit. Uploads artifact `dist` (this is what production gets).
2. `build-test`: builds again with `OFFERINGS_URL=${{ vars.ASF_OFFERINGS_URL_TEST }}` (packages and banners from the test CMS) and `VITE_SITE_URL=https://test.andreaslop.nl` (see "Own address of the test site") and uploads `dist-test`.
3. `deploy-test`: needs `check` and `build-test`, downloads `dist-test`, uploads to the ASF test host and runs the deployment check (served by the CMS host, admin files, POST status).
4. `lighthouse`: against the built site with the preview stub (`--audit-route --contact-stub`); skipped on `schedule`.
5. `deploy-production`: manual, from `release/*` only, uses artifact `dist`.
There is one Raspberry Pi runner plus a desktop runner, so jobs can wait in the queue for a long time (for example 30 minutes before `build-test`); a deploy that only just started is not hung. Check `started_at` (UTC) before cancelling anything.
## Deploying a feature branch to test
Committing, pushing and deploying a feature branch to test is allowed for the sessions that work on it. Merging, deploying to production and changing repo variables are not (Bryan decides). After a test deploy, check the page in a real browser against the real test CMS; `web/e2e/` holds the checks that run in CI.
## Contact form switch (`VITE_CONTACT_FORM_ENABLED`)
The contact form is closed by default. Only the test build (`build-test`) sets `VITE_CONTACT_FORM_ENABLED=true`, so the ASF test host shows the real form; the production artifact (job `check`) is built without it and stays closed. Only the exact value `true` opens the form (`src/lib/contactFormFlag.ts`); anything else keeps it closed, so a typo cannot open it in production. This replaced the former TEST ONLY commit `d449e76` (which hard-coded `enabled: true`); it was reverted before the merge, so nothing has to be undone any more. Opening the form in production needs Bryan's explicit go after the captcha decision (see [go-live-checklist.md](go-live-checklist.md)). Locally: `VITE_CONTACT_FORM_ENABLED=true pnpm build`.
## The check after a deploy and the host injection
`deploy/verify-deployment.sh` compares what the server sends with the files in `dist`. Once the CMS host injects (packages, banners, prices, JSON-LD price, site address), the pages differ from `dist` by design, so both sides are first normalised with `config/normalizeInjected.ts` (the contents of the CMS regions, the data block, `offers` in structured data, inline prices and the site address are taken out). Everything else must still be equal byte for byte, so an old build or a wrong server config is still caught; the 404 page is not injected and is compared as it is. The preview server can stand in for the host (`node config/previewServer.ts --cms-data=<json>`), which is how the script is tried locally.
## Own address of the test site
The test site stands on its own: in the test build `VITE_SITE_URL` is `https://test.andreaslop.nl`, so canonical, `og:url`, `og:image`, the JSON-LD ids and urls and `sitemap.xml` all point to the test host. A link shared from the test site (WhatsApp, Discord) therefore shows its own picture, not one from production. The production artifact (job `check`) is built without the variable and keeps `https://andreaslop.nl`. `src/lib/siteUrl.ts` only accepts an origin (https, or http on localhost); anything else falls back to production, so a typo cannot move production to another domain. This is a build setting, not TEST ONLY code: nothing has to be reverted before a merge. `robots.txt` on the test host is the nginx one (`Disallow: /`, plus `X-Robots-Tag: noindex`), not `public/robots.txt`, so the test site stays out of search engines. To try it locally: `VITE_SITE_URL=http://localhost:4173 pnpm build`.
## Generated files
`web/deploy/iis/web.config` and `web/deploy/nginx/*.conf` are generated by `pnpm server-config` from `web/config/serverConfig.ts`. Change the generator, rerun it and commit the result; a test checks that they match.
+42
View File
@@ -0,0 +1,42 @@
# Go-live checklist
What must be true before the CMS-driven parts of the site go to production. Bryan gives the explicit go for each; nothing here is done by merging alone. The per-feature record is in `aidlc-docs/features/contact-form-cms/operations/production-readiness-checklist.md` and `aidlc-docs/features/asf-packages-cms/`.
## Before merging to master
- [x] The TEST ONLY commit `d449e76` is undone: the form is closed unless the build sets `VITE_CONTACT_FORM_ENABLED=true` (only the test build does; [deploy-and-ci.md](deploy-and-ci.md)).
- [ ] Merge: the CMS PR first, then `feature/asf-packages-cms` (which carries the contact-form commits).
- [ ] The nightly test build only starts after the packages feature is on `master` (schedules run from the default branch).
## Packages and banners
- [ ] Production hosting in place with the CMS host as the one entry of the website: IIS passes ALL requests to the CMS host (not only `/api/v1/*`) and serves no static files itself; the prerendered `dist/` is deployed to the CMS host ([cms-integration.md](cms-integration.md), "Hosting"). The generated IIS config and the production upload script are updated for this. Without it production keeps the committed snapshot and the console shows a 404 per page view for the API.
- [ ] `web/src/content/offerings.snapshot.json` holds the real, current packages (production builds use it).
- [ ] The production CMS holds the real packages. The test CMS prices must never end up in the production artifact (it is built without `OFFERINGS_URL`).
## Contact form
- [ ] All conditions in the contact-form production readiness checklist (server module, recipient, sender, retention 1 year / 30 days spam, proxies, CSP `frame-src`, a real mail from the production host).
- [ ] Captcha decision: off at go-live until a paid Friendly Captcha plan exists; the EU endpoint changes the CSP and the privacy text.
- [ ] Then, with Bryan's explicit go (after the captcha decision), the production build gets `VITE_CONTACT_FORM_ENABLED=true`, in its own reviewed change. Until then the production artifact has the form closed.
- [ ] Operations for the form are part of this joint production checklist (no separate steps; the rebuild-trigger question lapses because the CMS host shows changes at once, NFR-10).
## Privacy statement (page `/privacyverklaring`)
The statement is a separate feature on branch `feature/privacy-statement` (a draft; nothing of it is live). It may only go live when:
- [ ] Bryan has approved the text.
- [ ] The hosting and mail provider (MijnHostingPartner) is confirmed as processor, a processing agreement (verwerkersovereenkomst) exists, and data and mail processing in the Netherlands is confirmed.
- [ ] The response time ("binnen een maand") is confirmed.
- [ ] The captcha paragraph matches the captcha decision above (the paragraph is hidden while captcha is off).
- [ ] No `[OPEN:` marker is left in a visible section (`unresolvedPlaceholders()` in `privacyContent.ts` returns an empty list).
- [ ] The retention periods in the statement match the server settings (1 year, 30 days for spam).
The contact form must not go live before the statement does.
## Other open items
- ASF production hosting: CMS host behind IIS pass-through (separate feature, see above).
- Host injection of CMS data into the prerendered pages (plan: `aidlc-docs/features/asf-cms-host-injection/plan.md`, after the current merges).
- First ASF administrator and removal of the setup token (CMS).
- Messages created by the Playwright test run in the ASF test CMS are archived by Bryan.
+63
View File
@@ -0,0 +1,63 @@
# Texts and translations
The texts of the site live in language files, not in the components. Dutch is the only language now; the structure allows a second one without a redesign.
## Where things are
- `web/src/i18n/nl.json`: all Dutch texts of the site in one file, in blocks per area in the order of the site: `common`, `site`, `home`, `about`, `contact`, `shoots`, `portfolio`, `instagram`, `testimonials`, `seo`, `cmsClient`. The file is the source of the types. A second language is `web/src/i18n/en.json` with the same keys.
- `web/src/i18n/index.ts`: `t(key, params?)` for a text, `tList(key)` for a list of texts, `tPlural(key, count, params?)` for a text with a singular and a plural form, `locales`, `locale` and `Messages`.
- `web/src/i18n/compare.ts`: the checks the tests use (same keys and parameters, nothing empty).
- The typed content modules in `web/src/content` keep their structure, images and paths; the words come from the language files.
Not in the language files: the hero (becomes a CMS module), the privacy statement (separate feature), and everything that comes from the CMS (packages, banners, later the gallery).
## Keys
Dotted paths: the block (`common`, `home`, ...), then the page or section, then the element: `home.pricing.title`, `shoots.newborn.faq.0.question`, `common.aria.backToTop`, `common.form.errors.required`, `seo.pages.contact.title`. A list is an array in the JSON and keeps the order of the page; a position is a number in the path. Parameters are written `{name}`; a text with a plural has the forms `one` and `other` (`photos.one`, `photos.other`) and `{count}` is filled in by `tPlural`. No HTML in the texts: a text with a link or emphasis is a structured list of parts, as the content modules already have.
## Two ways to read a text
- A single text in a component: `t('home.pricing.title')`, or `tList(...)` for a list of plain texts, `tPlural(...)` for singular and plural.
- Structured content (a list of items with several texts, such as the questions and answers of a page): the content module reads the typed tree directly, `messages.shoots.newborn.faq.map((item) => ({ question: item.question, answer: item.answer }))`. A missing property breaks `tsc`, the same as a missing key. The content modules in `web/src/content` keep their types, images and paths and take the words from `messages`.
- `t()` is not given keys that are built at run time (`` `faq.${i}.question` ``): use the tree for lists.
## How a missing text is found
- `t('...')` only accepts keys that exist in the Dutch files; a typo or a missing key stops `tsc` and the build.
- A second language is typed as `Messages`, so a missing key is a compile error there too.
- A test checks that every language has the same keys and `{parameters}` as Dutch, and that no text is empty or says TODO.
- ESLint (`react/jsx-no-literals`) warns about a text typed straight into JSX, so a new hardcoded text is noticed in review and in CI.
## What is in which block
| File | Texts |
| ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `common.json` | shared labels: `aria`, `site.name`, `newTab`, `actions` (general button words), `form` (labels, placeholders, captcha message), `status` (404 and error page), `lightbox`, `gate`, `privacyNote`, `pricing` labels |
| `site.json` | `nav`, `footer`, `breadcrumb`, `info` (service area, reply time, mail subjects), `socials` |
| `home.json` | the home page sections and the booking labels (`booking.book`, `booking.readMore`) |
| `about.json`, `contact.json` | the about page and the contact page |
| `shoots.json` | the overview, every shoot type and every shoot page (`pages.<id>`), shared shoot texts |
| `portfolio.json`, `instagram.json`, `testimonials.json` | those pages and sections, with their photo alt texts and reviews |
| `seo.json` | page titles, descriptions and link-preview alt texts per page (`seo.pages.<page>`) |
The block `cmsClient` holds the texts of the shared `src/cms-client` package, per part of the package: `cmsClient.contact` has the form's field errors, fallback, waiting time (`rateLimited.one/other` with `{minutes}`), too-large, captcha-required, failure (`{address}`) and the sending label. `src/i18n/cmsClientMessages.ts` builds the `ContactMessages` object from it and `ContactForm` passes it to `useContactForm({ messages })`. The package keeps its own Dutch defaults (`messages.nl.ts`) as a fallback and a test checks that both say the same. Parts that come later (offerings) get their own part of the block.
Not here: the hero, the privacy statement and everything from the CMS.
## Importing the language files
Components import from `@/i18n`. Files that Node loads while building (everything reached from `src/seo.ts`, `src/sitePages.ts`, the content modules, `src/lib`, `src/navigation.ts`) cannot use the `@/` alias or a directory import, so they use `../i18n/index.ts` (relative, with the extension). The JSON file is imported with `with { type: 'json' }` for the same reason.
## Rules that are enforced
`react/jsx-no-literals` and a rule for text attributes (`aria-label`, `alt`, `title`, `placeholder`, `label`) are errors in components and routes (the hero, tests and the privacy page are left out; an empty `alt=""` for a decorative image is fine). A new text goes into `nl.json` first.
## Adding a language (later)
1. Copy `web/src/i18n/nl.json` to `web/src/i18n/<code>.json` and translate the values (keys and `{parameters}` stay).
2. Add it to `locales` in `web/src/i18n/index.ts`; the tests then compare it with Dutch.
3. The site needs routes per language (`/en/...`) and a prerender per language, and `<html lang>` from the language. That is a separate piece of work; the texts do not stand in its way.
## Moving the texts over: the check that nothing changed
While the texts were moved into the language files, the prerendered pages had to stay word for word the same. `pnpm baseline:save` (after `pnpm build`) saves the text, links, labels, meta tags and structured data of every page in `web/.baseline` (not in git), and `pnpm baseline:check` compares a new build with it; styling, scripts and file hashes are ignored. A step is only done when the check says the pages are equal.
+6
View File
@@ -30,3 +30,9 @@ lighthouse-reports
# Gegenereerde cache van Start
.tanstack
# Written by config/fetchOfferings.ts before every build
src/content/offerings.generated.json
# Saved text of the prerendered pages (pnpm baseline:save), a local safety net
.baseline
+6
View File
@@ -11,3 +11,9 @@ pnpm-lock.yaml
.junie
.tanstack
skills-lock.json
# Copied package (source: SlpSoftware src/cms-client); keeps its own formatting
src/cms-client
# Golden files of the host injection contract: exact text, never reformatted
contract/host-injection/*.expected.html
+118
View File
@@ -0,0 +1,118 @@
// Build step, runs before the build: asks the CMS for the shoot packages and
// writes src/content/offerings.generated.json, which the site imports. With
// no address, a failing CMS or an unusable answer the committed snapshot
// (src/content/offerings.snapshot.json) is used, so the build never fails
// and never shows empty prices. The log says which one was used.
//
// OFFERINGS_URL: the site's own address that serves the API, for example
// https://test.andreaslop.nl (the API is same-origin, /api/v1/offerings).
import { readFileSync, writeFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import {
mapBanner,
mapOfferings,
mapTopBanner,
type SiteOfferings,
} from '../src/lib/offerings.ts';
const SNAPSHOT = fileURLToPath(
new URL('../src/content/offerings.snapshot.json', import.meta.url),
);
const GENERATED = fileURLToPath(
new URL('../src/content/offerings.generated.json', import.meta.url),
);
const TIMEOUT_MS = 10_000;
const ATTEMPTS = 2;
// The JSON answer, or undefined for 204 (no content). Other statuses and
// network errors throw.
async function fetchAnswer(base: string, path: string): Promise<unknown> {
const url = new URL(path, base);
for (let attempt = 1; ; attempt++) {
try {
const response = await fetch(url, {
signal: AbortSignal.timeout(TIMEOUT_MS),
headers: { Accept: 'application/json' },
});
if (response.status === 204) return undefined;
if (!response.ok) throw new Error(`status ${response.status}`);
return await response.json();
} catch (error) {
if (attempt >= ATTEMPTS) throw error;
}
}
}
async function main() {
const snapshot = JSON.parse(
readFileSync(SNAPSHOT, 'utf8'),
) as SiteOfferings;
const base = process.env.OFFERINGS_URL?.trim();
let result = { ...snapshot, source: 'snapshot' };
if (!base) {
console.log('[offerings] no OFFERINGS_URL: using the snapshot');
} else {
try {
const mapped = mapOfferings(
await fetchAnswer(base, '/api/v1/offerings'),
);
if (mapped) {
result = {
...snapshot,
packages: mapped.packages,
source: 'cms',
};
console.log(
`[offerings] ${mapped.packages.length} packages from ${base}`,
);
// The banner: 200 is the active one, 204 means none. A
// failing banner call keeps the snapshot's banner (none).
try {
const banner = mapBanner(
await fetchAnswer(base, '/api/v1/offerings/banner'),
);
result.banner = banner;
console.log(
banner
? `[offerings] banner "${banner.title}"`
: '[offerings] no active banner',
);
} catch (error) {
console.warn(
`[offerings] banner not available (${String(error)}): none`,
);
}
// The slim top bar, same rules
try {
const top = mapTopBanner(
await fetchAnswer(
base,
'/api/v1/offerings/banner?position=top',
),
);
result.topBanner = top;
console.log(
top
? `[offerings] top bar "${top.title ?? top.text}"`
: '[offerings] no active top bar',
);
} catch (error) {
console.warn(
`[offerings] top bar not available (${String(error)}): none`,
);
}
} else {
console.warn(
`[offerings] answer of ${base} has no valid package: using the snapshot`,
);
}
} catch (error) {
console.warn(
`[offerings] ${base} not reachable (${String(error)}): using the snapshot`,
);
}
}
writeFileSync(GENERATED, JSON.stringify(result, null, 4) + '\n');
}
await main();
+149
View File
@@ -0,0 +1,149 @@
import { describe, expect, it } from 'vitest';
import { injectCms, type LiveData } from './hostInjector.ts';
const AUTHORED = 'https://andreaslop.nl';
const page = (inner: string) => `<html><body>${inner}</body></html>`;
const pakket = (slug: string, price: string, extra = {}) => ({
slug,
title: slug.toUpperCase(),
price,
features: ['a'],
displayOrder: 0,
...extra,
});
const live = (
offerings: unknown,
banners: LiveData['banners'] = { top: null, bottom: null },
): LiveData => ({ offerings, banners });
const run = (html: string, data: LiveData, publicBaseUrl?: string) =>
injectCms(html, { data, authoredBaseUrl: AUTHORED, publicBaseUrl });
describe('injectCms regions', () => {
const region = (name: string) =>
`<!--CMS:${name}-->baked<!--/CMS:${name}-->`;
it('writes the lists between the markers and keeps the markers', () => {
const out = run(
page(
region('OFFERINGS-HTML') +
region('BANNER-TOP-HTML') +
region('BANNER-BOTTOM-HTML'),
),
live([pakket('newborn', '€ 185')], {
top: { text: 'Boven' },
bottom: { title: 'Onder' },
}),
);
expect(out).toContain(
'<!--CMS:OFFERINGS-HTML--><ul class="cms-offerings">',
);
expect(out).toContain('€&nbsp;185');
expect(out).toContain('<!--CMS:BANNER-TOP-HTML--><aside');
expect(out).toContain('<span>Boven</span>');
expect(out).toContain('<strong>Onder</strong>');
expect(out).toContain('<!--/CMS:BANNER-BOTTOM-HTML-->');
expect(out).not.toContain('baked');
});
it('empties a region without data', () => {
const out = run(page(region('OFFERINGS-HTML')), live([]));
expect(out).toContain(
'<!--CMS:OFFERINGS-HTML--><!--/CMS:OFFERINGS-HTML-->',
);
});
});
describe('injectCms data block', () => {
const baked =
'<!--CMS:DATA--><script type="application/json" id="cms-data">{"source":"build"}</script>';
it('replaces the marker and the baked block by the live one, with the address', () => {
const out = run(
page(baked),
live([pakket('x', '€ 5')]),
'https://t.nl',
);
expect(out).not.toContain('"source"');
const json = /id="cms-data">(.*?)<\/script>/.exec(out)?.[1] ?? '';
expect(JSON.parse(json)).toMatchObject({
siteUrl: 'https://t.nl',
offerings: [{ slug: 'x' }],
banners: { top: null, bottom: null },
});
});
it('writes the block in place of a lone marker, and escapes it', () => {
const out = run(
page('<!--CMS:DATA-->'),
live([pakket('x', '€ 5', { title: '</script><b>' })]),
);
expect(out).toContain('<script type="application/json" id="cms-data">');
expect(out.match(/<\/script>/g)).toHaveLength(1);
expect(out).toContain('\\u003c/script\\u003e');
});
});
describe('injectCms JSON-LD and prices', () => {
const ld = (offers: unknown) =>
`<!--CMS:OFFER-JSON-LD slug="newborn"--><script type="application/ld+json">${JSON.stringify(
{ '@graph': [{ '@type': 'Service', offers }] },
)}</script>`;
it('sets the price of the package', () => {
const out = run(
page(ld({ '@type': 'Offer', price: 1, priceCurrency: 'EUR' })),
live([pakket('newborn', '€ 1.250')]),
);
expect(out).toContain('"price":1250');
expect(out).toContain('"priceCurrency":"EUR"');
expect(out).not.toContain('CMS:OFFER-JSON-LD');
});
it('removes offers when the package is gone or has no readable price', () => {
for (const offerings of [
[pakket('gezin', '€ 1')],
[pakket('newborn', 'op aanvraag')],
]) {
const out = run(page(ld({ price: 1 })), live(offerings));
expect(out).not.toContain('offers');
}
});
it('leaves a block that is not JSON as it is', () => {
const broken =
'<!--CMS:OFFER-JSON-LD slug="newborn"--><script type="application/ld+json">{kapot</script>';
expect(run(page(broken), live([]))).toContain(broken);
});
it('sets the text of an inline price and leaves unknown slugs alone', () => {
const out = run(
page(
'<span data-cms-price="newborn" x>€ 1</span><span data-cms-price="onbekend">€ 9</span>',
),
live([pakket('newborn', '€ 185')]),
);
expect(out).toContain(
'<span data-cms-price="newborn" x>€ 185</span>'.replace(
'€ ',
'€' + String.fromCharCode(160),
),
);
expect(out).toContain('<span data-cms-price="onbekend">€ 9</span>');
});
});
describe('injectCms address', () => {
it('replaces the written address everywhere when another one is set', () => {
const html = page(`<link href="${AUTHORED}/a"><i>${AUTHORED}/b</i>`);
const out = run(html, live([]), 'https://t.nl');
expect(out).not.toContain(AUTHORED);
expect(out.match(/https:\/\/t\.nl/g)).toHaveLength(2);
});
it('leaves it when none is set or it is the same', () => {
const html = page(`<i>${AUTHORED}/b</i>`);
expect(run(html, live([]))).toBe(html);
expect(run(html, live([]), AUTHORED)).toBe(html);
});
});
+116
View File
@@ -0,0 +1,116 @@
// A stand-in for what the CMS host does to a prerendered page: it fills the CMS
// markers from live data (the contract is in aidlc-docs/features/
// asf-cms-host-injection/plan.md and contract/host-injection). The real
// injector is C# in the CMS repo; this one lets the preview server and the
// browser tests show how the site behaves when a host rewrites the HTML, so
// hydration, fail-safe behaviour and layout can be checked without a host.
// It uses the site's own mapping and HTML code, so it proves the page copes
// with what the host writes; the golden files prove the host's template
// matches that code.
import { bannerHtml, offeringsHtml } from '../src/lib/cmsHtml.ts';
import { scriptJson } from '../src/lib/cmsData.ts';
import { formatPrice } from '../src/lib/formatPrice.ts';
import { mapBanner, mapOfferings, mapTopBanner } from '../src/lib/offerings.ts';
export interface LiveData {
// The answers as the public API gives them
offerings: unknown;
banners: { top: unknown; bottom: unknown };
}
export interface InjectOptions {
data: LiveData;
// The address the build was written with and the one to show instead
authoredBaseUrl?: string;
publicBaseUrl?: string;
}
// ld+json that cannot close its script element (same rule as the site's)
const jsonLd = (value: unknown) =>
JSON.stringify(value)
.replace(/</g, '\\u003c')
.replace(/>/g, '\\u003e')
.replace(/&/g, '\\u0026');
const REGION =
/<!--CMS:(OFFERINGS-HTML|BANNER-TOP-HTML|BANNER-BOTTOM-HTML)-->[\s\S]*?<!--\/CMS:\1-->/g;
const DATA_BLOCK =
/<!--CMS:DATA-->(?:<script type="application\/json" id="cms-data">[\s\S]*?<\/script>)?/g;
const OFFER_JSON_LD =
/<!--CMS:OFFER-JSON-LD slug="([a-z0-9-]+)"--><script type="application\/ld\+json">([\s\S]*?)<\/script>/g;
const PRICE_SPAN =
/(<span data-cms-price="([a-z0-9-]+)"[^>]*>)[^<]*(<\/span>)/g;
type Price = Map<string, number>;
// Sets or removes offers on every node of a JSON-LD value that has them
function editOffers(value: unknown, price: number | undefined): void {
if (Array.isArray(value)) {
for (const item of value) editOffers(item, price);
return;
}
if (typeof value !== 'object' || value === null) return;
const node = value as Record<string, unknown>;
if ('offers' in node) {
if (price === undefined) delete node.offers;
else {
node.offers = { ...(node.offers as object), price };
}
}
for (const child of Object.values(node)) editOffers(child, price);
}
export function injectCms(html: string, options: InjectOptions): string {
const { data } = options;
const mapped = mapOfferings(data.offerings);
const packages = mapped ? mapped.packages : [];
const prices: Price = new Map(packages.map((pkg) => [pkg.id, pkg.price]));
const regions: Record<string, string> = {
'OFFERINGS-HTML': offeringsHtml(packages),
'BANNER-TOP-HTML': bannerHtml(mapTopBanner(data.banners.top)),
'BANNER-BOTTOM-HTML': bannerHtml(mapBanner(data.banners.bottom)),
};
const siteUrl = options.publicBaseUrl ?? options.authoredBaseUrl;
let out = html
.replace(
REGION,
(_match, name: string) =>
`<!--CMS:${name}-->${regions[name]}<!--/CMS:${name}-->`,
)
.replace(
DATA_BLOCK,
() =>
'<!--CMS:DATA-->' +
`<script type="application/json" id="cms-data">${scriptJson({
...(siteUrl ? { siteUrl } : {}),
offerings: data.offerings,
banners: data.banners,
})}</script>`,
)
.replace(OFFER_JSON_LD, (match, slug: string, json: string) => {
let parsed: unknown;
try {
parsed = JSON.parse(json);
} catch {
return match;
}
editOffers(parsed, prices.get(slug));
return `<script type="application/ld+json">${jsonLd(parsed)}</script>`;
})
.replace(
PRICE_SPAN,
(match, open: string, slug: string, close: string) => {
const price = prices.get(slug);
return price === undefined
? match
: `${open}${formatPrice(price)}${close}`;
},
);
const { authoredBaseUrl, publicBaseUrl } = options;
if (authoredBaseUrl && publicBaseUrl && authoredBaseUrl !== publicBaseUrl) {
out = out.split(authoredBaseUrl).join(publicBaseUrl);
}
return out;
}
+73
View File
@@ -0,0 +1,73 @@
import { describe, expect, it } from 'vitest';
import { firstDifferences, normalizeHtml } from './htmlBaseline.ts';
describe('normalizeHtml', () => {
it('keeps text, links, labels, meta and structured data', () => {
const html =
'<html><head><title>Titel</title><meta name="description" content="Tekst"/>' +
'<link rel="canonical" href="https://a.nl/"/></head><body>' +
'<a href="/over-mij" aria-label="Naar over mij">Over mij</a>' +
'<script type="application/ld+json">{"a":1}</script></body></html>';
const out = normalizeHtml(html);
for (const part of [
'<title>Titel</title>',
'content="Tekst"',
'rel="canonical"',
'aria-label="Naar over mij"',
'Over mij',
'{"a":1}',
]) {
expect(out).toContain(part);
}
});
it('leaves out look and build details', () => {
const html =
'<style data-emotion="css">.a{}</style><script src="/assets/x-AbCd1234.js"></script>' +
'<link rel="stylesheet" href="/assets/y-AbCd1234.css"/><!-- opmerking -->' +
'<div class="css-1abc" style="color:red" data-reveal="hidden" id="x">tekst</div>' +
'<img src="/assets/foto-AbCd1234.jpg"/><noscript><style>.b{}</style></noscript>';
const out = normalizeHtml(html);
expect(out).not.toMatch(
/css-1abc|color:red|data-reveal|opmerking|\.a\{|stylesheet|AbCd1234.js/,
);
expect(out).toContain('<div id="x">');
expect(out).toContain('/assets/foto.jpg');
expect(out).toContain(
'<noscript>' + String.fromCharCode(10) + '</noscript>',
);
});
it('keeps the CMS markers and the data block', () => {
const html =
'<!--CMS:DATA--><script type="application/json" id="cms-data">{"x":1}</script>' +
'<!--CMS:OFFERINGS-HTML-->a<!--/CMS:OFFERINGS-HTML-->';
const out = normalizeHtml(html);
expect(out).toContain('<!--CMS:DATA-->');
expect(out).toContain('{"x":1}');
expect(out).toContain('<!--/CMS:OFFERINGS-HTML-->');
});
it('notices a changed word', () => {
expect(normalizeHtml('<p>een</p>')).not.toBe(
normalizeHtml('<p>twee</p>'),
);
});
it('puts one tag per line and ends with a newline', () => {
expect(normalizeHtml('<ul> <li>a</li> <li>b</li> </ul>')).toBe(
'<ul>\n<li>a</li>\n<li>b</li>\n</ul>\n',
);
});
});
describe('firstDifferences', () => {
it('shows the lines that differ, at most a few', () => {
const out = firstDifferences('a\nb\nc', 'a\nB\nc\nd');
expect(out.join('\n')).toContain('regel 2');
expect(out.join('\n')).toContain('basislijn: b');
expect(out.join('\n')).toContain('nu: B');
expect(out.join('\n')).toContain('(geen)');
expect(firstDifferences('a', 'a')).toEqual([]);
});
});
+130
View File
@@ -0,0 +1,130 @@
// Safety net for moving texts into the language files: saves what the
// prerendered pages say (their text, links, labels, meta tags and structured
// data) and later checks that a new build says exactly the same. Styling,
// scripts, asset hashes and generated class names are left out, so only a
// change of wording or content shows up.
//
// Usage (after `pnpm build`):
// node config/htmlBaseline.ts save writes .baseline/<page>.html (ignored by git)
// node config/htmlBaseline.ts check compares dist/client with .baseline
import {
existsSync,
mkdirSync,
readdirSync,
readFileSync,
writeFileSync,
} from 'node:fs';
import { join, relative } from 'node:path';
const DIST = 'dist/client';
const BASELINE = '.baseline';
// What stays: text, links, labels, meta, structured data and the data block
const KEEP_SCRIPT = /type="application\/(?:ld\+json|json)"/;
export function normalizeHtml(html: string): string {
return (
html
.replace(/<!--(?!\/?CMS:)[\s\S]*?-->/g, '')
.replace(/<style[\s\S]*?<\/style>/g, '')
.replace(
/<script\b([^>]*)>([\s\S]*?)<\/script>/g,
(all, attrs: string) => (KEEP_SCRIPT.test(attrs) ? all : ''),
)
.replace(/<noscript>[\s\S]*?<\/noscript>/g, '<noscript></noscript>')
// Only the canonical link is content; the others point to hashed files
.replace(/<link\b[^>]*>/g, (tag) =>
/rel="canonical"/.test(tag) ? tag : '',
)
// Look, not content
.replace(/\s(?:class|style|data-emotion|data-reveal)="[^"]*"/g, '')
.replace(/\s(?:hidden|inert)=""/g, ' $&')
// The hash in /assets/name-Hash.ext
.replace(
/(\/assets\/[\w.-]*?)-[A-Za-z0-9_-]{8}(\.[a-z0-9]+)/g,
'$1$2',
)
.replace(/>\s+</g, '><')
// One tag per line, so a difference is readable
.replace(/></g, '>\n<')
.trim() + '\n'
);
}
function pages(dir: string): string[] {
return readdirSync(dir, { recursive: true, withFileTypes: true })
.filter((entry) => entry.isFile() && entry.name.endsWith('.html'))
.map((entry) => relative(dir, join(entry.parentPath, entry.name)))
.sort();
}
// The first lines that differ, for the message
export function firstDifferences(a: string, b: string, max = 6): string[] {
const left = a.split('\n');
const right = b.split('\n');
const out: string[] = [];
for (
let i = 0;
i < Math.max(left.length, right.length) && out.length < max;
i++
) {
if (left[i] !== right[i]) {
out.push(
` regel ${i + 1}:`,
` basislijn: ${left[i] ?? '(geen)'}`,
` nu: ${right[i] ?? '(geen)'}`,
);
}
}
return out;
}
function save() {
mkdirSync(BASELINE, { recursive: true });
for (const page of pages(DIST)) {
const target = join(BASELINE, page.replace(/[\\/]/g, '__'));
writeFileSync(
target,
normalizeHtml(readFileSync(join(DIST, page), 'utf8')),
);
}
console.log(
`Basislijn opgeslagen: ${pages(DIST).length} pagina's in ${BASELINE}`,
);
}
function check(): boolean {
if (!existsSync(BASELINE)) {
console.error('Geen basislijn; draai eerst `save`.');
return false;
}
let ok = true;
const names = pages(DIST);
for (const page of names) {
const file = join(BASELINE, page.replace(/[\\/]/g, '__'));
if (!existsSync(file)) {
console.error(`${page}: niet in de basislijn`);
ok = false;
continue;
}
const now = normalizeHtml(readFileSync(join(DIST, page), 'utf8'));
const was = readFileSync(file, 'utf8');
if (now !== was) {
ok = false;
console.error(`${page}: tekst verschilt van de basislijn`);
console.error(firstDifferences(was, now).join('\n'));
}
}
if (ok) console.log(`Gelijk aan de basislijn: ${names.length} pagina's`);
return ok;
}
if (process.argv[1]?.endsWith('htmlBaseline.ts')) {
const command = process.argv[2];
if (command === 'save') save();
else if (command === 'check') process.exitCode = check() ? 0 : 1;
else {
console.error('Gebruik: node config/htmlBaseline.ts save|check');
process.exitCode = 2;
}
}
+2
View File
@@ -113,6 +113,8 @@ describe('Lighthouse-configuratie', () => {
it('start de preview met de auditroute en meet een keer', () => {
expect(startCommand).toContain('--audit-route');
// CI heeft geen CMS-host: de preview bootst de contact-API na
expect(startCommand).toContain('--contact-stub');
expect(collect.numberOfRuns).toBe(1);
});
+106
View File
@@ -0,0 +1,106 @@
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';
import { injectCms, type LiveData } from './hostInjector.ts';
import { normalizeInjected } from './normalizeInjected.ts';
const AUTHORED = 'https://andreaslop.nl';
const baked = (name: string) => {
try {
return readFileSync(
join(process.cwd(), 'dist', 'client', name),
'utf8',
);
} catch {
return null;
}
};
const live: LiveData = {
offerings: [
{
slug: 'newborn',
title: 'Newborn',
price: '€ 999',
features: ['x'],
displayOrder: 0,
},
],
banners: { top: { text: 'Boven' }, bottom: null },
};
describe('normalizeInjected', () => {
it('makes a page equal to the same page after the host filled the markers', () => {
const pages = ['index.html', 'soorten-fotoshoots/newborn.html'];
for (const page of pages) {
const html = baked(page);
// The tests of the unit run need no build; skip a page that is not built
if (html === null) continue;
const injected = injectCms(html, {
data: live,
authoredBaseUrl: AUTHORED,
publicBaseUrl: 'https://test.example.nl',
});
expect(injected).not.toBe(html);
expect(
normalizeInjected(injected, [
AUTHORED,
'https://test.example.nl',
]),
).toBe(
normalizeInjected(html, [AUTHORED, 'https://test.example.nl']),
);
}
});
const page = (inner: string) => `<body>${inner}</body>`;
it('empties the regions but keeps the markers', () => {
expect(
normalizeInjected(
page('<!--CMS:OFFERINGS-HTML-->a<!--/CMS:OFFERINGS-HTML-->'),
),
).toBe(page('<!--CMS:OFFERINGS-HTML--><!--/CMS:OFFERINGS-HTML-->'));
});
it('removes the data block with or without its marker', () => {
const block =
'<script type="application/json" id="cms-data">{}</script>';
expect(normalizeInjected(page('<!--CMS:DATA-->' + block))).toBe(
page(''),
);
expect(normalizeInjected(page(block))).toBe(page(''));
expect(normalizeInjected(page('<!--CMS:DATA-->'))).toBe(page(''));
});
it('drops offers from structured data and the marker before it', () => {
const withOffers =
'<!--CMS:OFFER-JSON-LD slug="x"--><script type="application/ld+json">{"a":1,"offers":{"price":1}}</script>';
const without =
'<script type="application/ld+json">{ "a": 1 }</script>';
expect(normalizeInjected(page(withOffers))).toBe(
normalizeInjected(page(without)),
);
});
it('leaves structured data that is not JSON, so it still differs', () => {
const broken = '<script type="application/ld+json">{kapot</script>';
expect(normalizeInjected(page(broken))).toBe(page(broken));
});
it('empties inline prices and replaces the site addresses', () => {
expect(
normalizeInjected(
page('<span data-cms-price="x" a>€ 5</span> https://a.nl/x'),
['https://a.nl'],
),
).toBe(page('<span data-cms-price="x" a></span> @SITE@/x'));
});
it('still sees a real difference', () => {
expect(normalizeInjected(page('<p>een</p>'))).not.toBe(
normalizeInjected(page('<p>twee</p>')),
);
});
});
+77
View File
@@ -0,0 +1,77 @@
// Makes a prerendered page and the same page after the CMS host filled its
// markers comparable. The deployment check (deploy/verify-deployment.sh)
// compares what the server sends with the file in dist; since the host
// writes the current packages, banners, prices and address into the page,
// those parts are taken out of both sides first. Everything else must still be
// byte for byte equal, so an old build or a wrong server config is still
// caught. The rules mirror the host contract in
// aidlc-docs/features/asf-cms-host-injection/plan.md.
//
// Usage: node config/normalizeInjected.ts <input.html> <output.html> [site-url ...]
import { readFileSync, writeFileSync } from 'node:fs';
const REGION =
/(<!--CMS:(?:OFFERINGS-HTML|BANNER-TOP-HTML|BANNER-BOTTOM-HTML)-->)[\s\S]*?(<!--\/CMS:(?:OFFERINGS-HTML|BANNER-TOP-HTML|BANNER-BOTTOM-HTML)-->)/g;
const DATA_BLOCK =
/(?:<!--CMS:DATA-->)?<script type="application\/json" id="cms-data">[\s\S]*?<\/script>|<!--CMS:DATA-->/g;
const OFFER_MARKER = /<!--CMS:OFFER-JSON-LD slug="[a-z0-9-]+"-->/g;
const LD_JSON =
/(<script type="application\/ld\+json">)([\s\S]*?)(<\/script>)/g;
const PRICE_SPAN = /(<span data-cms-price="[a-z0-9-]+"[^>]*>)[^<]*(<\/span>)/g;
// JSON-LD: parse, drop every "offers" (the host rewrites or removes them),
// write it back the same way for both sides
function dropOffers(value: unknown): unknown {
if (Array.isArray(value)) return value.map(dropOffers);
if (typeof value !== 'object' || value === null) return value;
return Object.fromEntries(
Object.entries(value)
.filter(([key]) => key !== 'offers')
.map(([key, child]) => [key, dropOffers(child)]),
);
}
export function normalizeInjected(
html: string,
siteUrls: readonly string[] = [],
): string {
let out = html
.replace(REGION, '$1$2')
.replace(DATA_BLOCK, '')
.replace(OFFER_MARKER, '')
.replace(PRICE_SPAN, '$1$2')
.replace(
LD_JSON,
(match, open: string, json: string, close: string) => {
try {
return `${open}${JSON.stringify(dropOffers(JSON.parse(json)))}${close}`;
} catch {
// Not JSON: leave it, so a broken block still shows up as a
// difference
return match;
}
},
);
for (const url of siteUrls) out = out.split(url).join('@SITE@');
return out;
}
function main(args: string[]) {
const [input, output, ...siteUrls] = args;
if (!input || !output) {
console.error(
'Gebruik: node config/normalizeInjected.ts <in.html> <uit.html> [site-url ...]',
);
process.exitCode = 2;
return;
}
writeFileSync(
output,
normalizeInjected(readFileSync(input, 'utf8'), siteUrls),
);
}
// Only when run as a script, not when a test imports it
if (process.argv[1]?.endsWith('normalizeInjected.ts')) {
main(process.argv.slice(2));
}
+26 -1
View File
@@ -570,7 +570,7 @@ function siteDir(): string {
async function serve(
clientDir: string,
options?: { auditRoute?: boolean },
options?: { auditRoute?: boolean; contactStub?: boolean },
): Promise<number> {
const server = await startPreviewServer(clientDir, 0, options);
servers.push(server);
@@ -652,6 +652,31 @@ describe('startPreviewServer', () => {
expect((await ask(port, '/andere')).status).toBe(404);
});
it('bootst de contact-API alleen na met de optie (--contact-stub)', async () => {
const without = await serve(siteDir());
expect(
(await ask(without, '/api/v1/contact-messages/token')).status,
).toBe(404);
const port = await serve(siteDir(), { contactStub: true });
const token = await ask(port, '/api/v1/contact-messages/token');
expect(token.status).toBe(200);
expect(token.headers['content-type']).toBe('application/json');
expect(JSON.parse(token.body)).toMatchObject({
captcha: null,
minSeconds: expect.any(Number),
});
expect(
(await ask(port, '/api/v1/contact-messages', 'POST')).status,
).toBe(202);
// Live pakketten: geen gegevens, zonder 404
expect((await ask(port, '/api/v1/offerings')).status).toBe(204);
expect((await ask(port, '/api/v1/offerings/banner')).status).toBe(204);
// Al het andere blijft zoals het was
expect((await ask(port, '/api/v1/andere')).status).toBe(404);
expect((await ask(port, '/api/v1/contact-messages')).status).toBe(404);
});
it('stuurt een 301 met een relatieve Location, de query en de securityheaders, zonder inhoud', async () => {
const port = await serve(siteDir());
const expected = securityHeaders('production');
+111 -2
View File
@@ -8,7 +8,7 @@
// slash aan het eind krijgen één 301 (BR-HST-03, 04). /404.html is een echte
// 404; Lighthouse auditeert de 404-pagina via de opt-in route /__audit/404
// (--audit-route, BR-HST-22).
import { createReadStream, statSync } from 'node:fs';
import { createReadStream, readFileSync, statSync } from 'node:fs';
import {
createServer,
type IncomingMessage,
@@ -18,6 +18,7 @@ import {
import { extname, join, resolve, sep, win32 } from 'node:path';
import { fileURLToPath } from 'node:url';
import { createGzip } from 'node:zlib';
import { injectCms, type InjectOptions } from './hostInjector.ts';
import { canonicalRedirect, stripTrailingSlashes } from './canonicalUrls.ts';
import {
compressibleExtensions,
@@ -190,6 +191,50 @@ const searchOf = (target: string) => {
export interface PreviewOptions {
auditRoute?: boolean;
// Opt-in stand-in voor de contact-API (--contact-stub): CI heeft geen
// CMS-host, dus met contactForm.enabled=true kreeg de site een 404 op
// de tokenroute (console-fout, run 666). Met deze optie antwoordt de
// server zoals een open formulier zonder captcha: token 200, versturen
// 202. Productie gebruikt dit nooit; tests kunnen het per pagina met
// page.route vervangen (bijvoorbeeld 404 of een captcha).
contactStub?: boolean;
// Opt-in stand-in for the CMS host's injection (--cms-data=<json file>):
// called for every HTML page; the answer is what the host would write into
// the markers (see hostInjector.ts), null serves the page as built.
inject?: () => InjectOptions | null;
}
const CONTACT_API = '/api/v1/contact-messages';
// Antwoord van de stub, of undefined als het verzoek er niet voor is
export function contactStubResponse(
method: string | undefined,
path: string,
): { status: number; body: string } | undefined {
const json = (status: number, value: unknown) => ({
status,
body: JSON.stringify(value),
});
if (method === 'GET' && path === `${CONTACT_API}/token`) {
return json(200, {
token: 'preview-token',
minSeconds: 1,
captcha: null,
});
}
// Live packages and banner: "no data" (204), so the page stays with the
// baked list and shows no banner, without a 404 in the console (the site
// asks once per page load)
if (
method === 'GET' &&
(path === '/api/v1/offerings' || path === '/api/v1/offerings/banner')
) {
return { status: 204, body: '' };
}
if (method === 'POST' && path === CONTACT_API) {
return json(202, { status: 'received' });
}
return undefined;
}
export function startPreviewServer(
@@ -207,6 +252,27 @@ export function startPreviewServer(
};
const handle = (request: IncomingMessage, response: ServerResponse) => {
if (options.contactStub) {
const stub = contactStubResponse(
request.method,
pathOf(request.url ?? '/'),
);
if (stub) {
send(
response,
stub.status,
{
...(stub.body
? { 'Content-Type': 'application/json' }
: {}),
'Cache-Control': 'no-store',
},
stub.body || null,
);
request.resume();
return;
}
}
if (request.method !== 'GET' && request.method !== 'HEAD') {
send(
response,
@@ -246,6 +312,25 @@ export function startPreviewServer(
);
return;
}
// Like the real host, the 404 page is not injected
const injection =
file.endsWith('.html') && status === 200
? options.inject?.()
: null;
if (injection) {
const body = injectCms(readFileSync(target, 'utf8'), injection);
send(
response,
status,
{
'Content-Type': contentTypeOf(file),
'Cache-Control': 'no-cache',
'Content-Length': Buffer.byteLength(body),
},
request.method === 'HEAD' ? null : body,
);
return;
}
const headers: Record<string, string | number> = {
'Content-Type': contentTypeOf(file),
};
@@ -284,6 +369,8 @@ function parseArguments(args: string[]) {
strictPort: false,
dir: 'dist/client',
auditRoute: false,
contactStub: false,
cmsData: '',
};
for (let i = 0; i < args.length; i++) {
const [name, inline] = args[i].split('=', 2);
@@ -292,6 +379,8 @@ function parseArguments(args: string[]) {
else if (name === '--dir') options.dir = value();
else if (name === '--strictPort') options.strictPort = true;
else if (name === '--audit-route') options.auditRoute = true;
else if (name === '--contact-stub') options.contactStub = true;
else if (name === '--cms-data') options.cmsData = value();
}
return options;
}
@@ -299,7 +388,8 @@ function parseArguments(args: string[]) {
const MAX_PORT_TRIES = 10;
async function main(args: string[]) {
const { port, strictPort, dir, auditRoute } = parseArguments(args);
const { port, strictPort, dir, auditRoute, contactStub, cmsData } =
parseArguments(args);
if (!Number.isInteger(port) || port < 0 || port > 65535) {
console.error(`Ongeldige poort: ${port}`);
process.exitCode = 1;
@@ -312,6 +402,25 @@ async function main(args: string[]) {
try {
const server = await startPreviewServer(dir, port + attempt, {
auditRoute,
contactStub,
// Read again for every page, so the file can change while the
// server runs: { offerings, banners, publicBaseUrl? }
...(cmsData
? {
inject: () => {
const file = JSON.parse(
readFileSync(cmsData, 'utf8'),
) as InjectOptions['data'] & {
publicBaseUrl?: string;
};
return {
data: file,
authoredBaseUrl: 'https://andreaslop.nl',
publicBaseUrl: file.publicBaseUrl,
};
},
}
: {}),
});
const address = server.address();
const actual =
+24 -3
View File
@@ -3,6 +3,11 @@ import { contentSecurityPolicy, securityHeaders } from './securityHeaders';
const umami = 'https://analytics.slpsoftware.nl';
const sentry = 'https://o4511795618185216.ingest.de.sentry.io';
const captchaFrames = [
'https://global.frcapi.com',
'https://global0.frcapi.com',
'https://global1.frcapi.com',
];
const directive = (csp: string, name: string) =>
csp.split('; ').find((d) => d.startsWith(name + ' ')) ?? '';
@@ -21,19 +26,35 @@ describe('securityHeaders', () => {
it('productie-CSP opent alleen Umami en Sentry, op de juiste plekken (M7)', () => {
const csp = contentSecurityPolicy('production');
const externalHosts = new Set(csp.match(/https:\/\/[^\s;]+/g));
expect([...externalHosts].sort()).toEqual([sentry, umami].sort());
expect([...externalHosts].sort()).toEqual(
[sentry, umami, ...captchaFrames].sort(),
);
expect(directive(csp, 'connect-src')).toBe(
`connect-src 'self' ${umami} ${sentry}`,
);
// Alleen script-src en connect-src noemen een externe host
// Alleen script-src, connect-src en frame-src noemen een externe host
for (const d of csp.split('; ')) {
if (!/^(script|connect)-src /.test(d)) {
if (!/^(script|connect|frame)-src /.test(d)) {
expect(d).not.toContain('https://');
}
}
expect(csp).not.toContain('*');
});
it('productie-CSP laat het captcha-venster alleen van de drie vaste hosts toe', () => {
const csp = contentSecurityPolicy('production');
expect(directive(csp, 'frame-src')).toBe(
`frame-src ${captchaFrames.join(' ')}`,
);
// Geen wildcard en niets extra's totdat een echte browser het eist
expect(csp).not.toContain('*');
expect(directive(csp, 'script-src')).toBe(`script-src 'self' ${umami}`);
expect(directive(csp, 'worker-src')).toBe('');
expect(directive(csp, 'connect-src')).toBe(
`connect-src 'self' ${umami} ${sentry}`,
);
});
it('dev-CSP voegt alleen toe wat Vite nodig heeft', () => {
const csp = contentSecurityPolicy('development');
expect(directive(csp, 'script-src')).toBe(
+14
View File
@@ -8,6 +8,19 @@ type Mode = 'production' | 'development';
// Chakra/Emotion zetten tijdens runtime <style>-tags in de pagina, daarom
// staat style-src 'unsafe-inline' toe. Scripts komen van de eigen site en het
// Umami-script; verbindingen alleen naar Umami en Sentry (monitoring-plan M7).
// Friendly Captcha (contactformulier): de widget laadt zijn iframes van het
// hoofdhost en twee reservehosts, die de SDK bij een storing probeert. Exact
// deze drie, geen wildcard (besluit Bryan, 2026-11-10). Bij de overstap naar
// het EU-endpoint komen eu, eu0 en eu1 in de plaats; dat regelt de server
// (token-antwoord) en deze lijst moet dan mee. De SDK zelf zit in de eigen
// bundel, dus script-src verandert niet. connect-src en worker-src komen er
// pas bij als een test met een echte browser laat zien dat ze nodig zijn.
export const captchaFrameOrigins = [
'https://global.frcapi.com',
'https://global0.frcapi.com',
'https://global1.frcapi.com',
];
const productionCsp: Record<string, string[]> = {
'default-src': ["'self'"],
'script-src': ["'self'", umamiOrigin],
@@ -15,6 +28,7 @@ const productionCsp: Record<string, string[]> = {
'img-src': ["'self'", 'data:'],
'font-src': ["'self'"],
'connect-src': ["'self'", umamiOrigin, sentryIngestOrigin],
'frame-src': captchaFrameOrigins,
'object-src': ["'none'"],
'base-uri': ["'self'"],
'form-action': ["'self'"],
+28
View File
@@ -0,0 +1,28 @@
# Host injection contract (ASF site and CMS host)
The ASF build leaves markers in the prerendered pages; the CMS host fills them from live data. This folder holds the golden files for the two list regions. For every `NAME.input.json` there is a `NAME.expected.html`: the host's template must give exactly that text (the file ends with one newline that is not part of the HTML) for that input. The ASF repo tests its own implementation (`src/lib/cmsHtml.ts`) against the same files; to change the contract, change the code and run `UPDATE_GOLDEN=1 pnpm test src/lib/cmsHtml.test.ts`, then send the new files to the CMS session. The files come from ASF commit: see `git log -1 -- web/contract/host-injection` in the ASF repo.
## Inputs
- `offerings-*.input.json`: the answer of `GET /api/v1/offerings` (an array).
- `banner-*.input.json`: `{ "position": "top" | "bottom", "answer": <answer of GET /api/v1/offerings/banner?position=...> | null }`; `null` is a 204.
## Rules for the packages region (`<!--CMS:OFFERINGS-HTML-->`)
1. Keep a package only when all hold: `slug` is a string matching `^[a-z0-9-]+$`; `title` is a non-empty string after trimming; `features` is a non-empty array of non-empty strings (each trimmed); `price` is readable as whole euros above zero (below); the slug was not used by an earlier kept package (the first one wins). Trim all texts. Any other package is skipped.
2. Order by `displayOrder` (a number; missing counts as 0), ties keep the given order.
3. Price text to whole euros: trim, then the regex `^\D*?(\d{1,3}(?:\.\d{3})+|\d+)(?:,(?:-|0{1,2}))?\D*$`; group 1 without dots is the amount; it must be a whole number above zero. So "€ 175", "€ 1.250", "175,-", "€ 175,00" are readable; "op aanvraag", "€ 12,50", "€ 0", "175 of 185" are not.
4. Output: `<ul class="cms-offerings">` + one `<li>` per package + `</ul>`; nothing at all (empty string) when no package is kept.
5. Per package: `<li class="cms-offering" data-slug="SLUG"[ data-featured="true"]>` + `<h3>NAME</h3>` + `<p class="cms-price">€&nbsp;AMOUNT</p>` + `<ul class="cms-features">` + `<li>FEATURE</li>`... + `</ul>` + `<a href="/?pakket=SLUG#contact">Boek NAME</a>` + `</li>`. `data-featured="true"` only when `featured` is the boolean `true`. AMOUNT uses a dot as thousands separator (1.250). The literal text `&nbsp;` is written, not a character. `description`, `priceNote` and `ctaLabel` are not used.
6. Escape every text (name, features, slug, amount) as: `&` `&amp;`, `<` `&lt;`, `>` `&gt;`, `"` `&quot;`, `'` `&#39;`.
## Rules for the banner regions (`<!--CMS:BANNER-TOP-HTML-->`, `<!--CMS:BANNER-BOTTOM-HTML-->`)
1. `null` answer: empty string. Bottom: the title is required, otherwise empty string. Top: title or text is required, otherwise empty string.
2. Output `<aside class="cms-banner">` + the parts that are present, joined by one space, + `</aside>`. Parts: `<strong>TITLE</strong>`, `<span>TEXT</span>`, `<a href="URL">LABEL</a>` (trim all texts; empty means absent).
3. The link is written only when label and URL are both present and the URL is safe: it starts with `https://` and parses as a URL, or it starts with one `/` (not `//`, no backslash). Otherwise the link part is left out.
4. Escape as above (also in the `href`).
## Where the region sits
`<!--CMS:OFFERINGS-HTML-->…<!--/CMS:OFFERINGS-HTML-->` (and the two banner pairs) are written by the build; the host replaces what is between the markers and leaves the markers. See `aidlc-docs/features/asf-cms-host-injection/plan.md` for the other markers (data block, JSON-LD price, inline price).
@@ -0,0 +1 @@
<aside class="cms-banner"><strong>Kerstactie</strong> <span>Alleen in december</span> <a href="/contact">Boek de actie</a></aside>
@@ -0,0 +1,10 @@
{
"position": "bottom",
"answer": {
"title": "Kerstactie",
"text": "Alleen in december",
"linkLabel": "Boek de actie",
"linkUrl": "/contact",
"position": "bottom"
}
}
@@ -0,0 +1 @@
<aside class="cms-banner"><strong>Past er niets bij?</strong></aside>
@@ -0,0 +1,10 @@
{
"position": "bottom",
"answer": {
"title": "Past er niets bij?",
"text": null,
"linkLabel": null,
"linkUrl": null,
"position": "bottom"
}
}
@@ -0,0 +1 @@
<aside class="cms-banner"><strong>&lt;img src=x onerror=alert(1)&gt;</strong> <span>&quot;quote&quot; &amp; &#39;single&#39;</span> <a href="https://voorbeeld.nl/?a=1&amp;b=2">Meer</a></aside>
@@ -0,0 +1,10 @@
{
"position": "bottom",
"answer": {
"title": "<img src=x onerror=alert(1)>",
"text": "\"quote\" & 'single'",
"linkLabel": "Meer",
"linkUrl": "https://voorbeeld.nl/?a=1&b=2",
"position": "bottom"
}
}
@@ -0,0 +1 @@
@@ -0,0 +1,4 @@
{
"position": "bottom",
"answer": null
}
@@ -0,0 +1 @@
<aside class="cms-banner"><span>Nog twee plekken in december</span></aside>
@@ -0,0 +1,10 @@
{
"position": "top",
"answer": {
"title": "",
"text": "Nog twee plekken in december",
"linkLabel": null,
"linkUrl": null,
"position": "top"
}
}
@@ -0,0 +1 @@
<aside class="cms-banner"><strong>Nieuw</strong> <span>x</span></aside>
@@ -0,0 +1,10 @@
{
"position": "top",
"answer": {
"title": "Nieuw",
"text": "x",
"linkLabel": "Hier",
"linkUrl": "http://voorbeeld.nl",
"position": "top"
}
}
@@ -0,0 +1 @@
<ul class="cms-offerings"><li class="cms-offering" data-slug="newborn" data-featured="true"><h3>Newborn</h3><p class="cms-price">€&nbsp;185</p><ul class="cms-features"><li>1-2 uur fotografie</li></ul><a href="/?pakket=newborn#contact">Boek Newborn</a></li><li class="cms-offering" data-slug="gezin"><h3>Gezin</h3><p class="cms-price">€&nbsp;1.250</p><ul class="cms-features"><li>Hele dag</li></ul><a href="/?pakket=gezin#contact">Boek Gezin</a></li></ul>
@@ -0,0 +1,18 @@
[
{
"slug": "newborn",
"title": "Newborn",
"price": "€ 185",
"features": ["1-2 uur fotografie"],
"displayOrder": 0,
"featured": true
},
{
"slug": "gezin",
"title": "Gezin",
"price": "€ 1.250,-",
"features": ["Hele dag"],
"displayOrder": 1,
"featured": false
}
]
@@ -0,0 +1 @@
<ul class="cms-offerings"><li class="cms-offering" data-slug="xss"><h3>&lt;script&gt;alert(&quot;x&quot;)&lt;/script&gt; &amp; &quot;co&quot;</h3><p class="cms-price">€&nbsp;100</p><ul class="cms-features"><li>&lt;b&gt;vet&lt;/b&gt;</li><li>o&#39;brien &amp; zoon</li></ul><a href="/?pakket=xss#contact">Boek &lt;script&gt;alert(&quot;x&quot;)&lt;/script&gt; &amp; &quot;co&quot;</a></li></ul>
@@ -0,0 +1,9 @@
[
{
"slug": "xss",
"title": "<script>alert(\"x\")</script> & \"co\"",
"price": "€ 100",
"features": ["<b>vet</b>", "o'brien & zoon"],
"displayOrder": 0
}
]
@@ -0,0 +1 @@
@@ -0,0 +1 @@
[]
@@ -0,0 +1 @@
<ul class="cms-offerings"><li class="cms-offering" data-slug="goed"><h3>Goed</h3><p class="cms-price">€&nbsp;100</p><ul class="cms-features"><li>a</li></ul><a href="/?pakket=goed#contact">Boek Goed</a></li></ul>
@@ -0,0 +1,58 @@
[
{
"slug": "goed",
"title": "Goed",
"price": "€ 100",
"features": ["a"],
"displayOrder": 0
},
{
"slug": "Slecht Slug",
"title": "Fout",
"price": "€ 100",
"features": ["a"],
"displayOrder": 1
},
{
"slug": "goed",
"title": "Dubbel",
"price": "€ 100",
"features": ["a"],
"displayOrder": 2
},
{
"slug": "aanvraag",
"title": "Op aanvraag",
"price": "op aanvraag",
"features": ["a"],
"displayOrder": 3
},
{
"slug": "leeg",
"title": "Zonder kenmerken",
"price": "€ 100",
"features": [],
"displayOrder": 4
},
{
"slug": "zonder-titel",
"title": "",
"price": "€ 100",
"features": ["a"],
"displayOrder": 5
},
{
"slug": "nul",
"title": "Nul",
"price": "€ 0",
"features": ["a"],
"displayOrder": 6
},
{
"slug": "komma",
"title": "Komma",
"price": "€ 12,50",
"features": ["a"],
"displayOrder": 7
}
]
@@ -0,0 +1 @@
<ul class="cms-offerings"><li class="cms-offering" data-slug="zwangerschap"><h3>Zwangerschap</h3><p class="cms-price">€&nbsp;175</p><ul class="cms-features"><li>1 uur fotografie</li><li>Persoonlijke online fotogalerij</li></ul><a href="/?pakket=zwangerschap#contact">Boek Zwangerschap</a></li><li class="cms-offering" data-slug="newborn"><h3>Newborn</h3><p class="cms-price">€&nbsp;185</p><ul class="cms-features"><li>1-2 uur fotografie</li></ul><a href="/?pakket=newborn#contact">Boek Newborn</a></li><li class="cms-offering" data-slug="gezin"><h3>Gezin</h3><p class="cms-price">€&nbsp;175</p><ul class="cms-features"><li>1 uur fotografie</li><li>Minstens 30 zorgvuldig nabewerkte foto&#39;s</li></ul><a href="/?pakket=gezin#contact">Boek Gezin</a></li></ul>
@@ -0,0 +1,29 @@
[
{
"slug": "gezin",
"title": "Gezin",
"price": "€ 175",
"features": [
"1 uur fotografie",
"Minstens 30 zorgvuldig nabewerkte foto's"
],
"displayOrder": 2,
"description": "Een shoot met het hele gezin!",
"priceNote": "eenmalig, incl. btw"
},
{
"slug": "zwangerschap",
"title": "Zwangerschap",
"price": "€ 175",
"features": ["1 uur fotografie", "Persoonlijke online fotogalerij"],
"displayOrder": 0
},
{
"slug": "newborn",
"title": "Newborn",
"price": "€ 185",
"features": ["1-2 uur fotografie"],
"displayOrder": 1,
"ctaLabel": "Boek nu"
}
]
+1 -1
View File
@@ -61,7 +61,7 @@
<httpProtocol>
<customHeaders>
<remove name="X-Powered-By" />
<add name="Content-Security-Policy" value="default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" />
<add name="Content-Security-Policy" value="default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; frame-src https://global.frcapi.com https://global0.frcapi.com https://global1.frcapi.com; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" />
<add name="Strict-Transport-Security" value="max-age=31536000; includeSubDomains" />
<add name="X-Content-Type-Options" value="nosniff" />
<add name="X-Frame-Options" value="DENY" />
+7 -7
View File
@@ -53,7 +53,7 @@ server {
# /index.html gaan, dat hierboven naar / doorverwijst (lus)
autoindex off;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; frame-src https://global.frcapi.com https://global0.frcapi.com https://global1.frcapi.com; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
@@ -92,7 +92,7 @@ server {
# Testsite nooit indexeren
location = /robots.txt {
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; frame-src https://global.frcapi.com https://global0.frcapi.com https://global1.frcapi.com; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
@@ -105,7 +105,7 @@ server {
# Zonder dit zou $uri.html de pagina met 200 tonen
location = /404 {
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; frame-src https://global.frcapi.com https://global0.frcapi.com https://global1.frcapi.com; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
@@ -118,7 +118,7 @@ server {
# Alleen bereikbaar via error_page; een direct verzoek geeft 404
location = /404.html {
internal;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; frame-src https://global.frcapi.com https://global0.frcapi.com https://global1.frcapi.com; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
@@ -129,7 +129,7 @@ server {
# Bestanden met een hash in de naam: lang cachen
location /assets/ {
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; frame-src https://global.frcapi.com https://global0.frcapi.com https://global1.frcapi.com; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
@@ -141,7 +141,7 @@ server {
# Geen index-directive: de beginpagina staat hier uitdrukkelijk
location = / {
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; frame-src https://global.frcapi.com https://global0.frcapi.com https://global1.frcapi.com; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
@@ -156,7 +156,7 @@ server {
# Nooit een slash achter de variabele zetten: dat geeft nginx' eigen
# mapdoorverwijzing.
location / {
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; frame-src https://global.frcapi.com https://global0.frcapi.com https://global1.frcapi.com; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
+15 -1
View File
@@ -115,13 +115,27 @@ check_exact_headers() {
fi
}
# Is het antwoord gelijk aan het bestand uit dist? De CMS-host mag de markers in
# de pagina's vullen (pakketten, banners, prijzen, JSON-LD-prijs, adres); die
# delen worden aan beide kanten weggehaald (config/normalizeInjected.ts), de
# rest moet nog steeds byte voor byte gelijk zijn.
same_page() {
local body="$1" expected="$2" here
cmp -s "$body" "$expected" && return 0
case "$expected" in *.html) ;; *) return 1 ;; esac
here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
node "$here/../config/normalizeInjected.ts" "$body" "$work/norm-body.html" "https://andreaslop.nl" "${base%/}" || return 1
node "$here/../config/normalizeInjected.ts" "$expected" "$work/norm-dist.html" "https://andreaslop.nl" "${base%/}" || return 1
cmp -s "$work/norm-body.html" "$work/norm-dist.html"
}
# Een 200 met de bytes van het verwachte bestand uit dist
expect_file() {
local path="$1" file="$2"
fetch "$path"
if [ "$status" != "200" ]; then
fail "$path: status $status, verwacht 200"
elif ! cmp -s "$work/body" "$dist/$file"; then
elif ! same_page "$work/body" "$dist/$file"; then
fail "$path: antwoord is niet gelijk aan $file uit dist (oude serverconfig of oude build?)"
fi
check_security_headers "$path"
+140
View File
@@ -0,0 +1,140 @@
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import siteContent from '../src/content/siteContent.ts';
import {
eventually,
openPage,
waitForHydration,
type OpenedPage,
} from './support/browser.ts';
import { startServer } from './support/server.ts';
// Het contactformulier tegen de gebouwde site, met een nagebootste API
// (page.route). Welke tests draaien hangt af van de schakelaar in de content:
// uit (nu) betekent dat de site de server niets vraagt; aan betekent dat het
// formulier opent als de server het toestaat.
const enabled = siteContent.contactForm.enabled;
let server: Awaited<ReturnType<typeof startServer>>;
beforeAll(async () => {
server = await startServer();
});
afterAll(() => server.close());
const TOKEN = {
token: 'signed-token',
minSeconds: 3,
captcha: null,
};
// Houdt bij welke API-verzoeken de pagina doet en beantwoordt ze
function mockApi(options: {
token?: { status: number; body?: unknown };
submit?: { status: number; body?: unknown };
}) {
const requests: string[] = [];
const bodies: unknown[] = [];
return {
requests,
bodies,
prepare: async (page: OpenedPage['page']) => {
await page.route('**/api/v1/**', async (route) => {
const request = route.request();
const path = new URL(request.url()).pathname;
// The live packages call of every page: no live data, and
// not part of what these tests count
if (path.startsWith('/api/v1/offerings')) {
return route.fulfill({ status: 204 });
}
requests.push(`${request.method()} ${path}`);
if (path.endsWith('/token')) {
const { status, body } = options.token ?? {
status: 200,
body: TOKEN,
};
return route.fulfill({
status,
contentType: 'application/json',
body: JSON.stringify(body ?? {}),
});
}
bodies.push(request.postDataJSON());
const { status, body } = options.submit ?? {
status: 202,
body: { status: 'received' },
};
return route.fulfill({
status,
contentType: 'application/json',
body: JSON.stringify(body ?? {}),
});
});
},
};
}
describe.skipIf(enabled)('contactformulier uitgeschakeld', () => {
it('vraagt de server niets en toont de poort op /contact', async () => {
const api = mockApi({});
const { page, ...opened } = await openPage(server.origin + '/contact', {
prepare: api.prepare,
});
await waitForHydration(page);
await eventually(() =>
page.getByTestId('contact-gate-notice').count(),
).toBe(1);
// Scrollen naar het formulier mag ook geen verzoek opleveren
await page.getByTestId('contact-gate-notice').scrollIntoViewIfNeeded();
await page.waitForTimeout(500);
expect(api.requests).toEqual([]);
expect(opened.messages).toEqual([]);
expect(opened.violations).toEqual([]);
});
});
describe.skipIf(!enabled)('contactformulier ingeschakeld', () => {
const fill = async (page: OpenedPage['page']) => {
await page.getByTestId('contact-form-naam').fill('Demi');
await page.getByTestId('contact-form-email').fill('demi@example.nl');
await page.getByTestId('contact-form-shoot').selectOption('Newborn');
await page
.getByTestId('contact-form-bericht')
.fill('Wanneer heb je plek?');
};
it('opent als de server het toestaat en verstuurt het bericht', async () => {
const api = mockApi({});
const { page, ...opened } = await openPage(server.origin + '/contact', {
prepare: api.prepare,
});
await waitForHydration(page);
await eventually(() =>
page.getByTestId('contact-gate-notice').count(),
).toBe(0);
await fill(page);
await page.getByTestId('contact-form-submit').click();
await eventually(() =>
page.getByTestId('contact-form-sent').count(),
).toBe(1);
expect(api.requests).toEqual([
'GET /api/v1/contact-messages/token',
'POST /api/v1/contact-messages',
]);
expect(api.bodies[0]).toMatchObject({
name: 'Demi',
subject: 'Newborn',
token: 'signed-token',
});
expect(opened.messages).toEqual([]);
expect(opened.violations).toEqual([]);
});
it('blijft bij de poort als het formulier dicht is (404)', async () => {
const api = mockApi({ token: { status: 404 } });
const { page } = await openPage(server.origin + '/contact', {
prepare: api.prepare,
});
await waitForHydration(page);
await eventually(async () => api.requests.length).toBe(1);
expect(await page.getByTestId('contact-gate-notice').count()).toBe(1);
});
});
+339
View File
@@ -0,0 +1,339 @@
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import type { LiveData } from '../config/hostInjector.ts';
import {
eventually,
openPage,
waitForHydration,
type OpenedPage,
} from './support/browser.ts';
import { startServer } from './support/server.ts';
// De CMS-host vult markers in de geprerenderde HTML (plan: aidlc-docs/features/
// asf-cms-host-injection). Hier doet de previewserver alsof hij die host is
// (config/hostInjector.ts), met data die van de gebakken data afwijkt. Wat
// getest wordt: de HTML die de host schrijft is leesbaar zonder JavaScript,
// de pagina hydrateert zonder fout, toont daarna de actuele data zonder zelf
// de API te vragen, en valt terug op wat gebakken is als de data niet bruikbaar
// is.
const AUTHORED = 'https://andreaslop.nl';
let live: { data: LiveData; publicBaseUrl?: string } | null = null;
let server: Awaited<ReturnType<typeof startServer>>;
beforeAll(async () => {
server = await startServer({
inject: () =>
live && {
data: live.data,
authoredBaseUrl: AUTHORED,
publicBaseUrl: live.publicBaseUrl,
},
});
});
afterAll(() => server.close());
const pakket = (
slug: string,
title: string,
price: string,
order: number,
extra: Record<string, unknown> = {},
) => ({
slug,
title,
price,
features: [`Kenmerk van ${title}`],
displayOrder: order,
...extra,
});
const FIVE = [
pakket('zwangerschap', 'Zwangerschap', '€ 200', 0),
pakket('newborn', 'Newborn', '€ 210', 1, { featured: true }),
pakket('gezin', 'Gezin', '€ 220', 2),
pakket('loveshoot', 'Loveshoot', '€ 230', 3),
pakket('portret', 'Portret', '€ 240', 4),
];
const NO_BANNERS = { top: null, bottom: null };
const html = async (path: string) => (await fetch(server.origin + path)).text();
const cards = (page: OpenedPage['page']) =>
page.locator('[data-testid^="price-card-"]:not([data-testid$="-book"])');
// Elke test begint zonder injectie en zet live zelf
const inject = (data: LiveData, publicBaseUrl?: string) => {
live = { data, publicBaseUrl };
};
describe('markers in de gebouwde pagina', () => {
it('heeft ze op de plekken van het contract, en niet op andere', async () => {
live = null;
const home = await html('/');
for (const marker of [
'OFFERINGS-HTML',
'BANNER-TOP-HTML',
'BANNER-BOTTOM-HTML',
]) {
expect(home.split(`<!--CMS:${marker}-->`)).toHaveLength(2);
expect(home.split(`<!--/CMS:${marker}-->`)).toHaveLength(2);
}
for (const path of [
'/',
'/over-mij',
'/contact',
'/soorten-fotoshoots',
]) {
const page = await html(path);
expect(page.split('<!--CMS:DATA-->')).toHaveLength(2);
expect(page).toMatch(
/<!--CMS:DATA--><script type="application\/json" id="cms-data">\{/,
);
}
// Prijs-JSON-LD en inline prijs alleen op de pakketpagina's
for (const slug of ['newborn', 'zwangerschap', 'gezin']) {
const page = await html(`/soorten-fotoshoots/${slug}`);
expect(page).toContain(
`<!--CMS:OFFER-JSON-LD slug="${slug}"--><script type="application/ld+json">`,
);
expect(page).toContain(`data-cms-price="${slug}"`);
}
for (const slug of ['loveshoot', 'portret']) {
const page = await html(`/soorten-fotoshoots/${slug}`);
expect(page).not.toContain('CMS:OFFER-JSON-LD');
expect(page).not.toContain('data-cms-price');
}
});
});
describe('met data van de host die afwijkt van de build', () => {
it('schrijft leesbare HTML zonder JavaScript', async () => {
inject({
offerings: FIVE,
banners: {
top: {
title: 'Nieuw',
text: 'Nog twee plekken',
position: 'top',
},
bottom: { title: 'Onder', position: 'bottom' },
},
});
const home = await html('/');
// Eén pakket per kaart met de nieuwe prijs, de uitgelichte gemarkeerd
for (const price of ['200', '210', '220', '230', '240']) {
expect(home).toContain(`€&nbsp;${price}`);
}
expect(home).toContain('data-slug="newborn" data-featured="true"');
expect(home).toContain('<strong>Nieuw</strong>');
expect(home).toContain('<strong>Onder</strong>');
// De gebakken prijs (175) staat er niet meer in de lijst
const list = home.slice(
home.indexOf('<!--CMS:OFFERINGS-HTML-->'),
home.indexOf('<!--/CMS:OFFERINGS-HTML-->'),
);
expect(list).not.toContain('175');
});
it('hydrateert zonder fout en toont daarna de actuele data zonder API-verzoek', async () => {
inject({
offerings: FIVE,
banners: {
top: { title: '', text: 'Nog twee plekken', position: 'top' },
bottom: { title: 'Onder', text: 't', position: 'bottom' },
},
});
const requested: string[] = [];
const { page, messages } = await openPage(server.origin + '/', {
prepare: async (p) => {
p.on('request', (request) => {
if (request.url().includes('/api/v1/offerings')) {
requested.push(request.url());
}
});
},
});
await waitForHydration(page);
await eventually(() => cards(page).count()).toBe(5);
expect(await cards(page).first().textContent()).toContain('€\u00a0200');
expect(await page.locator('.cms-offerings').count()).toBe(0);
expect(await page.getByTestId('price-top-bar').textContent()).toContain(
'Nog twee plekken',
);
expect(await page.getByTestId('price-banner').textContent()).toContain(
'Onder',
);
// De uitgelichte kaart is gemarkeerd
expect(await page.locator('[data-featured="true"]').count()).toBe(1);
// Het datablok is er: de site vraagt de API niet zelf
expect(requested).toEqual([]);
expect(messages).toEqual([]);
});
it('verbergt de banners als de host geen actieve heeft (204)', async () => {
inject({ offerings: FIVE, banners: NO_BANNERS });
const { page, messages } = await openPage(server.origin + '/');
await waitForHydration(page);
await eventually(() => cards(page).count()).toBe(5);
expect(await page.getByTestId('price-top-bar').count()).toBe(0);
expect(await page.getByTestId('price-banner').count()).toBe(0);
expect(messages).toEqual([]);
});
it('verbergt de sectie als de host alle pakketten heeft uitgezet', async () => {
inject({ offerings: [], banners: NO_BANNERS });
const { page, messages } = await openPage(server.origin + '/');
await waitForHydration(page);
await eventually(() => page.getByTestId('pricing').count()).toBe(0);
expect(messages).toEqual([]);
});
it('past de formulierkeuze aan op de data van de host', async () => {
inject({ offerings: FIVE, banners: NO_BANNERS });
const { page, messages } = await openPage(
server.origin + '/contact?pakket=portret',
);
await waitForHydration(page);
await eventually(() =>
page.getByTestId('contact-form-shoot').locator('option').count(),
).toBe(7); // Kies een optie, vijf pakketten, Overig
expect(messages).toEqual([]);
});
it('zet de prijs op de pakketpagina in de HTML, in de JSON-LD en na hydratatie', async () => {
inject({
offerings: [pakket('newborn', 'Newborn', '€ 1.250', 0)],
banners: NO_BANNERS,
});
const raw = await html('/soorten-fotoshoots/newborn');
expect(raw).toMatch(/data-cms-price="newborn"[^>]*>€\u00a01\.250</);
expect(raw).toContain('"price":1250');
const { page, messages } = await openPage(
server.origin + '/soorten-fotoshoots/newborn',
);
await waitForHydration(page);
await eventually(() =>
page.locator('[data-cms-price="newborn"]').textContent(),
).toBe('€\u00a01.250');
const prices = await page.evaluate(() =>
[...document.querySelectorAll('script[type="application/ld+json"]')]
.map((script) => JSON.parse(script.textContent ?? ''))
.flatMap(
(data) => JSON.stringify(data).match(/"price":\d+/g) ?? [],
),
);
expect(prices).toEqual(['"price":1250']);
expect(messages).toEqual([]);
});
it('haalt de prijs uit de JSON-LD als het pakket niet meer bestaat', async () => {
inject({
offerings: [pakket('gezin', 'Gezin', '€ 220', 0)],
banners: NO_BANNERS,
});
const raw = await html('/soorten-fotoshoots/newborn');
expect(raw).not.toContain('"offers"');
// Het pakket dat er nog wel is houdt zijn prijs
expect(await html('/soorten-fotoshoots/gezin')).toContain(
'"price":220',
);
});
});
describe('adres van de site', () => {
it('zet canonical, og: en JSON-LD op het adres van de host, ook na navigatie', async () => {
inject(
{ offerings: FIVE, banners: NO_BANNERS },
'https://test.voorbeeld.nl',
);
const raw = await html('/');
expect(raw).not.toContain(AUTHORED);
expect(raw).toContain(
'rel="canonical" href="https://test.voorbeeld.nl/"',
);
const { page, messages } = await openPage(server.origin + '/');
await waitForHydration(page);
// Navigeren binnen de site: de head wordt opnieuw opgebouwd en moet het
// adres uit het datablok gebruiken, niet het gebakken productie-adres
await page.getByRole('link', { name: 'Over mij' }).first().click();
await eventually(() => page.title()).toContain('Over mij');
expect(
await page.locator('link[rel="canonical"]').getAttribute('href'),
).toBe('https://test.voorbeeld.nl/over-mij');
expect(
await page
.locator('meta[property="og:image"]')
.getAttribute('content'),
).toMatch(/^https:\/\/test\.voorbeeld\.nl\//);
expect(messages).toEqual([]);
});
});
describe('als de data niet bruikbaar is', () => {
it('toont wat gebakken is bij een datablok zonder bruikbare lijst', async () => {
// De host schreef een blok waar geen lijst in staat. De site gelooft
// dat niet en houdt de gebakken pakketten (zonder fout).
inject({ offerings: 'kapot', banners: NO_BANNERS });
const { page, messages } = await openPage(server.origin + '/');
await waitForHydration(page);
await eventually(() => cards(page).count()).toBe(3);
expect(messages).toEqual([]);
});
it('vangt vijandige tekst op: geen script, wel de tekst', async () => {
inject({
offerings: [
pakket(
'newborn',
'<img src=x onerror="window.pwned=1">',
'€ 200',
0,
{
features: ['<script>window.pwned=1</script>'],
},
),
],
banners: {
top: null,
bottom: { title: '<b onmouseover=1>x</b>', position: 'bottom' },
},
});
const raw = await html('/');
expect(raw).not.toContain('<img src=x');
expect(raw).not.toContain('<script>window.pwned');
const { page, messages } = await openPage(server.origin + '/');
await waitForHydration(page);
await eventually(() => cards(page).count()).toBe(1);
expect(await page.evaluate(() => 'pwned' in window)).toBe(false);
expect(await cards(page).first().textContent()).toContain(
'<img src=x onerror="window.pwned=1">',
);
expect(messages).toEqual([]);
});
});
describe('zonder host die injecteert', () => {
it('toont de gebakken pakketten en vraagt de API zelf, zoals voor de injectie', async () => {
live = null;
const requested: string[] = [];
const { page, messages } = await openPage(server.origin + '/', {
prepare: async (p) => {
p.on('request', (request) => {
if (request.url().includes('/api/v1/offerings')) {
requested.push(new URL(request.url()).pathname);
}
});
},
});
await waitForHydration(page);
await eventually(() => cards(page).count()).toBe(3);
await eventually(async () => requested.length).toBe(3);
// Het blok dat de build schreef telt niet als data van de host
expect(requested.sort()).toEqual([
'/api/v1/offerings',
'/api/v1/offerings/banner',
'/api/v1/offerings/banner',
]);
expect(messages).toEqual([]);
});
});
+2 -2
View File
@@ -168,7 +168,7 @@ describe('zoekwaarden na de hydratatie', () => {
server.origin + '/?pakket=gezin#contact',
);
await waitForHydration(page);
await eventually(() => shootField(page).inputValue()).toBe('gezin');
await eventually(() => shootField(page).inputValue()).toBe('Gezin');
// De tidy-navigatie haalt de zoekwaarde weg, de hash blijft
await page.waitForFunction(() => location.search === '');
expect(new URL(page.url()).hash).toBe('#contact');
@@ -181,7 +181,7 @@ describe('zoekwaarden na de hydratatie', () => {
server.origin + '/contact?pakket=gezin',
);
await waitForHydration(page);
await eventually(() => shootField(page).inputValue()).toBe('gezin');
await eventually(() => shootField(page).inputValue()).toBe('Gezin');
await page.waitForFunction(() => location.search === '');
expect(new URL(page.url()).pathname).toBe('/contact');
expect(opened.messages).toEqual([]);
+176
View File
@@ -0,0 +1,176 @@
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import {
eventually,
openPage,
waitForHydration,
type OpenedPage,
} from './support/browser.ts';
import { startServer } from './support/server.ts';
// De pakketten staan gebakken in de HTML. Na het laden vraagt de pagina het
// CMS (/api/v1/offerings); een afwijkend antwoord vervangt de lijst, een
// fout laat de gebakken lijst staan.
let server: Awaited<ReturnType<typeof startServer>>;
beforeAll(async () => {
server = await startServer();
});
afterAll(() => server.close());
const answer = (price: string) => [
{
slug: 'newborn',
title: 'Newborn',
price,
features: ['Een kenmerk'],
displayOrder: 0,
layout: 'card',
},
];
const mock =
(status: number, body?: unknown) => async (page: OpenedPage['page']) => {
await page.route('**/api/v1/offerings', (route) =>
route.fulfill({
status,
contentType: 'application/json',
body: body === undefined ? '' : JSON.stringify(body),
}),
);
};
const cards = (page: OpenedPage['page']) =>
page.locator('[data-testid^="price-card-"]:not([data-testid$="-book"])');
describe('pakketten live uit het CMS', () => {
it('toont eerst de gebakken pakketten en daarna het antwoord van het CMS', async () => {
const { page } = await openPage(server.origin + '/', {
prepare: mock(200, answer('€ 200')),
});
await waitForHydration(page);
await eventually(() => cards(page).count()).toBe(1);
expect(await cards(page).first().textContent()).toContain('€\u00a0200');
});
it('past ook de keuze in het formulier aan', async () => {
const { page } = await openPage(
server.origin + '/contact?pakket=newborn',
{ prepare: mock(200, answer('€ 200')) },
);
await waitForHydration(page);
await eventually(() =>
page.getByTestId('contact-form-shoot').locator('option').count(),
).toBe(3); // Kies een optie, Newborn, Overig
});
it.each([
['een fout', mock(500)],
['geen gegevens (204)', mock(204)],
['een ongeldig antwoord', mock(200, { error: 'x' })],
['een lijst zonder geldig pakket', mock(200, answer('op aanvraag'))],
])('houdt de gebakken pakketten bij %s', async (_name, prepare) => {
const { page, messages } = await openPage(server.origin + '/', {
prepare,
});
await waitForHydration(page);
await page.waitForTimeout(800);
expect(await cards(page).count()).toBe(3);
expect(messages.filter((m) => !m.includes('500'))).toEqual([]);
});
// De kaartenrij: op desktop rijen van drie, een onvolledige laatste rij
// staat in het midden, voor elk aantal. Op tablet en mobiel één kolom.
const many = (count: number) =>
Array.from({ length: count }, (_, index) => ({
slug: `pakket-${index + 1}`,
title: `Pakket ${index + 1}`,
price: '€ 100',
features: ['Een kenmerk'],
displayOrder: index,
}));
const boxes = (page: OpenedPage['page']) =>
cards(page).evaluateAll((nodes) =>
nodes.map((node) => {
const { x, y, width } = node.getBoundingClientRect();
return { x, y: Math.round(y + window.scrollY), width };
}),
);
it.each([4, 5, 7, 8, 10])(
'zet de laatste, onvolledige rij van %i kaarten in het midden',
async (count) => {
const { page } = await openPage(server.origin + '/', {
prepare: mock(200, many(count)),
});
await waitForHydration(page);
await eventually(() => cards(page).count()).toBe(count);
const found = await boxes(page);
const rows = new Map<number, typeof found>();
for (const box of found) {
rows.set(box.y, [...(rows.get(box.y) ?? []), box]);
}
const list = [...rows.values()];
expect(list.length).toBe(Math.ceil(count / 3));
const first = list[0];
// Alle kaarten even breed; de volle rij vult de breedte
const width = first[0].width;
const left = first[0].x;
const right = first[2].x + width;
for (const box of found) expect(box.width).toBeCloseTo(width, 0);
for (const row of list.slice(0, -1)) expect(row).toHaveLength(3);
// De laatste rij ligt in het midden van de volle rij
const last = list[list.length - 1];
const rowLeft = last[0].x;
const rowRight = last[last.length - 1].x + width;
expect((rowLeft + rowRight) / 2).toBeCloseTo((left + right) / 2, 0);
},
);
it.each([800, 390])(
'houdt de kaarten onder elkaar bij %ipx breed',
async (width) => {
const { page } = await openPage(server.origin + '/', {
width,
prepare: mock(200, many(4)),
});
await waitForHydration(page);
await eventually(() => cards(page).count()).toBe(4);
const found = await boxes(page);
expect(new Set(found.map((box) => box.x)).size).toBe(1);
expect(new Set(found.map((box) => box.y)).size).toBe(4);
},
);
const topBar =
(status: number, body?: unknown) =>
async (page: OpenedPage['page']) => {
await page.route(
/\/api\/v1\/offerings\/banner\?position=top/,
(route) =>
route.fulfill({
status,
contentType: 'application/json',
body: body === undefined ? '' : JSON.stringify(body),
}),
);
};
it('toont de slanke balk boven de kaarten, op één regel op desktop', async () => {
const { page } = await openPage(server.origin + '/', {
prepare: topBar(200, {
title: 'Nieuw',
text: 'Nog twee plekken in december',
linkLabel: 'Boek nu',
linkUrl: '/contact',
}),
});
await waitForHydration(page);
const bar = page.getByTestId('price-top-bar');
await eventually(() => bar.count()).toBe(1);
const barBox = await bar.boundingBox();
const cardBox = await cards(page).first().boundingBox();
expect(barBox!.y + barBox!.height).toBeLessThan(cardBox!.y);
// Slank: een regel tekst plus opvulling
expect(barBox!.height).toBeLessThan(70);
});
});
+11 -2
View File
@@ -1,5 +1,6 @@
import type { AddressInfo } from 'node:net';
import { resolve } from 'node:path';
import type { InjectOptions } from '../../config/hostInjector.ts';
import { startPreviewServer } from '../../config/previewServer.ts';
// De gebouwde site: `pnpm build` schrijft hem, de tests bouwen niets. Relatief
@@ -10,8 +11,16 @@ export const clientDir = resolve('dist/client');
// Dezelfde server als `pnpm preview`, met de productie-CSP en echte 404's,
// op een poort die het systeem kiest zodat tests elkaar niet in de weg zitten.
// auditRoute zet de opt-in route /__audit/404 aan, zoals Lighthouse hem start.
export async function startServer(options: { auditRoute?: boolean } = {}) {
const server = await startPreviewServer(clientDir, 0, options);
// De contact-API wordt standaard nagebootst (CI heeft geen CMS-host); een
// test die iets anders nodig heeft vervangt het met page.route.
// inject laat de server doen alsof de CMS-host de markers vult (hostInjector)
export async function startServer(
options: { auditRoute?: boolean; inject?: () => InjectOptions | null } = {},
) {
const server = await startPreviewServer(clientDir, 0, {
contactStub: true,
...options,
});
const { port } = server.address() as AddressInfo;
return {
origin: `http://127.0.0.1:${port}`,
+65
View File
@@ -3,6 +3,7 @@ import globals from 'globals';
import tseslint from 'typescript-eslint';
import reactHooks from 'eslint-plugin-react-hooks';
import jsxA11y from 'eslint-plugin-jsx-a11y';
import react from 'eslint-plugin-react';
// Alleen regels die fouten vinden; opmaak is aan Prettier
export default tseslint.config(
@@ -31,6 +32,70 @@ export default tseslint.config(
globals: globals.browser,
},
},
{
// Texts of the site live in the language files (src/i18n), not in the
// JSX (an error, so a new hardcoded text is stopped). Left out: the hero (becomes a CMS module), tests and
// the build-only helpers.
files: ['src/components/**/*.tsx', 'src/routes/**/*.tsx'],
ignores: [
'src/components/Hero/**',
// The privacy statement is its own feature, not moved yet
'src/routes/privacyverklaring.tsx',
'**/*.test.tsx',
'src/routeTree.gen.ts',
],
plugins: { react },
rules: {
// Text in attributes that people read or hear (labels, alt text)
'no-restricted-syntax': [
'error',
{
selector:
"JSXAttribute[name.name=/^(aria-label|aria-description|alt|title|placeholder|label)$/][value.type='Literal'][value.value!='']",
message:
'Put the text in a language file (src/i18n) and use t().',
},
],
'react/jsx-no-literals': [
'error',
{
noStrings: false,
ignoreProps: true,
// Technical signs that are not words
allowedStrings: [
'/',
'|',
'·',
'–',
'—',
'×',
'+',
'-',
':',
'…',
],
},
],
},
},
{
// The copied cms-client package stays headless: it may only import
// react and its own files (also enforced by its boundary test)
files: ['src/cms-client/**/*.{ts,tsx}'],
rules: {
'no-restricted-imports': [
'error',
{
patterns: [
{
group: ['@/*'],
message: 'cms-client must not import from the app',
},
],
},
],
},
},
{
files: ['config/**/*.ts', 'e2e/**/*.ts', 'vitest.e2e.config.ts'],
languageOptions: {
+1 -1
View File
@@ -140,7 +140,7 @@ module.exports = {
ci: {
collect: {
startServerCommand:
'pnpm preview --port 4173 --strictPort --audit-route',
'pnpm preview --port 4173 --strictPort --audit-route --contact-stub',
startServerReadyPattern: 'Local',
url: [...indexedPaths, ...noindexPaths, notFoundPath].map(
(path) => origin + path,
+7 -1
View File
@@ -6,7 +6,7 @@
"packageManager": "pnpm@12.11.2",
"scripts": {
"dev": "vite",
"build": "tsc && vite build && node config/externalizeInlineScripts.ts",
"build": "node config/fetchOfferings.ts && tsc && vite build && node config/externalizeInlineScripts.ts",
"preview": "node config/previewServer.ts",
"e2e": "vitest run --config vitest.e2e.config.ts",
"postinstall": "chakra typegen ./src/theme.ts",
@@ -20,6 +20,8 @@
"audit:dev": "pnpm audit || echo Meldingen in ontwikkeltools blokkeren niet, zie NFR-SEC-05",
"lighthouse": "lhci autorun && lhci autorun --config=lighthouserc.desktop.cjs",
"server-config": "node config/writeServerConfig.ts",
"baseline:save": "node config/htmlBaseline.ts save",
"baseline:check": "node config/htmlBaseline.ts check",
"check": "pnpm lint && pnpm format:check && pnpm test && pnpm build && pnpm e2e && pnpm audit:deps && pnpm audit:dev && pnpm lighthouse"
},
"devDependencies": {
@@ -40,6 +42,7 @@
"axe-core": "^4.14.0",
"eslint": "^9.39.5",
"eslint-plugin-jsx-a11y": "^6.10.2",
"eslint-plugin-react": "^7.37.5",
"eslint-plugin-react-hooks": "^7.1.1",
"fast-check": "^4.10.2",
"globals": "^17.13.0",
@@ -54,8 +57,11 @@
"dependencies": {
"@chakra-ui/react": "^3.37.0",
"@emotion/react": "^11.14.0",
"@fontsource/cormorant-garamond": "^5.3.0",
"@fontsource/jost": "^5.3.0",
"@fontsource/marcellus": "^5.3.0",
"@fontsource/mulish": "^5.3.0",
"@friendlycaptcha/sdk": "^1.1.3",
"@sentry/react": "^11.8.0",
"@tanstack/react-router": "1.170.46",
"@tanstack/react-start": "1.169.4",
+211
View File
@@ -178,12 +178,21 @@ importers:
'@emotion/react':
specifier: ^11.14.0
version: 11.14.0(@types/react@19.3.0)(react@19.3.0)(supports-color@5.5.0)
'@fontsource/cormorant-garamond':
specifier: ^5.3.0
version: 5.3.0
'@fontsource/jost':
specifier: ^5.3.0
version: 5.3.0
'@fontsource/marcellus':
specifier: ^5.3.0
version: 5.3.0
'@fontsource/mulish':
specifier: ^5.3.0
version: 5.3.0
'@friendlycaptcha/sdk':
specifier: ^1.1.3
version: 1.1.3
'@sentry/react':
specifier: ^11.8.0
version: 11.8.0(react@19.3.0)
@@ -251,6 +260,9 @@ importers:
eslint-plugin-jsx-a11y:
specifier: ^6.10.2
version: 6.10.2(eslint@9.39.5(jiti@2.7.0)(supports-color@5.5.0))
eslint-plugin-react:
specifier: ^7.37.5
version: 7.37.5(eslint@9.39.5(jiti@2.7.0)(supports-color@5.5.0))
eslint-plugin-react-hooks:
specifier: ^7.1.1
version: 7.1.1(eslint@9.39.5(jiti@2.7.0)(supports-color@5.5.0))(supports-color@5.5.0)
@@ -737,12 +749,18 @@ packages:
'@floating-ui/utils@0.2.12':
resolution: {integrity: sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==}
'@fontsource/cormorant-garamond@5.3.0':
resolution: {integrity: sha512-weuGsCirGVWBWqpt6YUp0yLThTe4G8YO45noq8wxeJCRvEpq5lFrxNMFSTxcyOyV5k5otzJ8guDzYegdYlcLMQ==}
'@fontsource/jost@5.3.0':
resolution: {integrity: sha512-lORv5y49hSoLVxjGb0qNuBzXvnaNYI3B94200uGPGJFei8fao6d6LLz2ziWbOZubGfZnibzuT6GVNX8fBw8WQQ==}
'@fontsource/marcellus@5.3.0':
resolution: {integrity: sha512-cMnanjpiPIC7Rq4GXIA/Zal5WLSoDV5Mc681tMkWsWfKHXnRnLGlhuGeBnLF6HrqtFkiSdiuy4NCSPfOrz266w==}
'@fontsource/mulish@5.3.0':
resolution: {integrity: sha512-Fru/fmJwg4ZlKUU4jELz6/guZhba6Lz1vraAROqooYnUbtj1iMi7BXFkQU7AkB6QP5swpvwRnO5chUp6mNh5mA==}
'@formatjs/ecma402-abstract@2.3.6':
resolution: {integrity: sha512-HJnTFeRM2kVFVr5gr5kH1XP6K0JcJtE7Lzvtr3FS/so5f1kpsqqqxy5JF+FRaO6H2qmcMfAUIox7AJteieRtVw==}
@@ -758,6 +776,9 @@ packages:
'@formatjs/intl-localematcher@0.6.2':
resolution: {integrity: sha512-XOMO2Hupl0wdd172Y06h6kLpBz6Dv+J4okPLl4LPtzbr8f66WbIoy4ev98EBuZ6ZK4h5ydTN6XneT4QVpD7cdA==}
'@friendlycaptcha/sdk@1.1.3':
resolution: {integrity: sha512-a2wJ46Ag6MGeZ/b+zyAO3MLT32816fgDN6fwQsVU6bRIUHyuU2/DHAWgQi5EiWAAr7Jj0uMrEdvukWhMPdnh1g==}
'@humanfs/core@0.19.2':
resolution: {integrity: sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==}
engines: {node: '>=18.18.0'}
@@ -1710,6 +1731,10 @@ packages:
resolution: {integrity: sha512-VXY5eFRarnXcYxwBjJzPmEhH55+rmP79/+ueDhi0F+TuqfHCItagIHqxeUZrmgrOPa31QTh9H85DjX3FfJ0FTg==}
engines: {node: '>= 0.4'}
array.prototype.findlast@1.2.5:
resolution: {integrity: sha512-CVvd6FHg1Z3POpBLxO6E6zr+rSKEQ9L6rZHAaY7lLfhKsWYUBBOuMs0e9o24oopj6H+geRCX0YJ+TJLBK2eHyQ==}
engines: {node: '>= 0.4'}
array.prototype.flat@1.3.3:
resolution: {integrity: sha512-rwG/ja1neyLqCuGZ5YYrznA62D4mZXg0i1cIskIUKSiqF3Cje9/wXAls9B9s1Wa2fomMsIv8czB8jZcPmxCXFg==}
engines: {node: '>= 0.4'}
@@ -1718,6 +1743,10 @@ packages:
resolution: {integrity: sha512-Y7Wt51eKJSyi80hFrJCePGGNo5ktJCslFuboqJsbf57CCPcm5zztluPlc4/aD8sWsKvlwatezpV4U1efk8kpjg==}
engines: {node: '>= 0.4'}
array.prototype.tosorted@1.1.4:
resolution: {integrity: sha512-p6Fx8B7b7ZhL/gmUsAy0D15WhvDccw3mnGNbZpi3pmeJdxtWsj2jEaI4Y6oo3XiHfzuSgPwKc04MYt6KgvC/wA==}
engines: {node: '>= 0.4'}
arraybuffer.prototype.slice@1.0.4:
resolution: {integrity: sha512-BNoCY6SXXPQ7gF2opIP4GBE+Xw7U+pHMYKuzjgCN3GwiaIR09UUeKfheyIry77QtrCBlC0KK0q5/TER/tYh3PQ==}
engines: {node: '>= 0.4'}
@@ -2108,6 +2137,10 @@ packages:
resolution: {integrity: sha512-svtcdpS8CgJyqAjEQIXdb3OjhFVVYjzGAPO8WGCmRbrml64SPw/jJD4GoE98aR7r25A0XcgrK3F02yw9R/vhQw==}
engines: {node: '>=0.3.1'}
doctrine@2.1.0:
resolution: {integrity: sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==}
engines: {node: '>=0.10.0'}
dom-accessibility-api@0.5.16:
resolution: {integrity: sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==}
@@ -2172,6 +2205,10 @@ packages:
resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==}
engines: {node: '>= 0.4'}
es-iterator-helpers@1.4.0:
resolution: {integrity: sha512-c/A0P0oxkACDc+cKWw8evLXK83oBKgn0qPOqCYT4x9uolpCIJAcYvJC9QYKNDRPsTeGyCrQ326jrvgZWdCdK5Q==}
engines: {node: '>= 0.4'}
es-module-lexer@2.3.2:
resolution: {integrity: sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==}
@@ -2228,6 +2265,12 @@ packages:
peerDependencies:
eslint: ^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0 || ^10.0.0
eslint-plugin-react@7.37.5:
resolution: {integrity: sha512-Qteup0SqU15kdocexFNAJMvCJEfa2xUKNV4CC1xsVMrIIqEy3SQ/rqyxCWNzfrd3/ldy6HMlD2e0JDVpDg2qIA==}
engines: {node: '>=4'}
peerDependencies:
eslint: ^3 || ^4 || ^5 || ^6 || ^7 || ^8 || ^9.7
eslint-scope@8.4.0:
resolution: {integrity: sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
@@ -2763,6 +2806,10 @@ packages:
isomorphic-fetch@3.0.0:
resolution: {integrity: sha512-qvUtwJ3j6qwsF3jLxkZ72qCgjMysPzDfeV240JHiGZsANBYd+EEuu35v7dfrJ9Up0Ak07D7GGSkGhCHTqg/5wA==}
iterator.prototype@1.1.5:
resolution: {integrity: sha512-H0dkQoCa3b2VEeKQBOxFph+JAbcrQdE7KC0UkqwpLmv2EC4P41QXP+rqo9wYodACiG5/WM5s9oDApTU8utwj9g==}
engines: {node: '>= 0.4'}
jiti@2.7.0:
resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==}
hasBin: true
@@ -2960,6 +3007,10 @@ packages:
lookup-closest-locale@6.2.0:
resolution: {integrity: sha512-/c2kL+Vnp1jnV6K6RpDTHK3dgg0Tu2VVp+elEiJpjfS1UyY7AjOYHohRug6wT0OpoX2qFgNORndE9RqesfVxWQ==}
loose-envify@1.4.0:
resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==}
hasBin: true
lru-cache@11.5.3:
resolution: {integrity: sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==}
engines: {node: 20 || >=22}
@@ -3091,6 +3142,10 @@ packages:
resolution: {integrity: sha512-eonl3sLUha+S1GzTPxychyhnUzKyeQkZ7jLjKrBagJgPla13F+uQ71HgpFefyHgqrjEbCPkDArxYsjY8/+gLKA==}
engines: {node: '>= 0.4.0'}
node-exports-info@1.6.2:
resolution: {integrity: sha512-kXs9Go0cah0qHVV2v389IXQLdLCeE1xfFtjOAF+iobu0OIoG1pje8At2vMHyaPMiPMnG/LWP50twML21eMcAag==}
engines: {node: '>= 0.4'}
node-fetch@2.7.0:
resolution: {integrity: sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==}
engines: {node: 4.x || >=6.0.0}
@@ -3104,6 +3159,10 @@ packages:
resolution: {integrity: sha512-kQK9LGGFiHtrWiNhZtA7Qbw17AQz+dmsEKODRIVTXA9+e5MS/2gZEBhYJt13GrAz5/IOZKddH/0Z3TP/Zgo+yw==}
engines: {node: '>=18'}
object-assign@4.1.1:
resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==}
engines: {node: '>=0.10.0'}
object-inspect@1.13.4:
resolution: {integrity: sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==}
engines: {node: '>= 0.4'}
@@ -3116,6 +3175,10 @@ packages:
resolution: {integrity: sha512-nK28WOo+QIjBkDduTINE4JkF/UJJKyf2EJxvJKfblDpyg0Q+pkOHNTL0Qwy6NP6FhE/EnzV73BxxqcJaXY9anw==}
engines: {node: '>= 0.4'}
object.entries@1.1.9:
resolution: {integrity: sha512-8u/hfXFRBD1O0hPUjioLhoWFHRmt6tKA4/vZPyckBr18l1KE9uHrFaFaUi8MDRTpi4uak2goyPTSNJLXX2k2Hw==}
engines: {node: '>= 0.4'}
object.fromentries@2.0.8:
resolution: {integrity: sha512-k6E21FzySsSK5a21KRADBd/NGneRegFO5pLHfdQLpRDETUNJueLXs3WCzyQ3tFRDYgbq3KHGXfTbi2bs8WQ6rQ==}
engines: {node: '>= 0.4'}
@@ -3289,6 +3352,9 @@ packages:
resolution: {integrity: sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==}
engines: {node: '>=0.4.0'}
prop-types@15.8.1:
resolution: {integrity: sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==}
proxy-addr@2.0.8:
resolution: {integrity: sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==}
engines: {node: '>= 0.10'}
@@ -3393,6 +3459,11 @@ packages:
engines: {node: '>= 0.4'}
hasBin: true
resolve@2.0.0-next.7:
resolution: {integrity: sha512-tqt+NBWwyaMgw3zDsnygx4CByWjQEJHOPMdslYhppaQSJUtL/D4JO9CcBBlhPoI8lz9oJIDXkwXfhF4aWqP8xQ==}
engines: {node: '>= 0.4'}
hasBin: true
restore-cursor@2.0.0:
resolution: {integrity: sha512-6IzJLuGi4+R14vwagDHX+JrXmPVtPpn4mffDJ1UdR7/Edm87fl6yi8mMBIVvFtJaNTUvjughmW4hwLhRG7gC1Q==}
engines: {node: '>=4'}
@@ -3608,6 +3679,13 @@ packages:
resolution: {integrity: sha512-o7+c9bW6zpAdJHTtujeePODAhkuicdAryFsfVKwA+wGw89wJ4GTY484WTucM9hLtDEOpOvI+aHnzqnC5lHp4Rg==}
engines: {node: '>= 0.4'}
string.prototype.matchall@4.1.0:
resolution: {integrity: sha512-tHNHTxInrYLCga9O9YGxWA3G9/nnzQw8UGAyqGx3Ar1pSTTzIuM4woFSq4SowkXCjJIwq5sIiQvEfRI9tCH1qQ==}
engines: {node: '>= 0.4'}
string.prototype.repeat@1.0.0:
resolution: {integrity: sha512-0u/TldDbKD8bFCQ/4f5+mNRrXwZ8hg2w7ZR8wa16e8z9XpePWl3eGEcUD0OXpEH/VJH/2G3gjUtR3ZOiBe2S/w==}
string.prototype.trim@1.2.11:
resolution: {integrity: sha512-PwvK7BU+CMTJGYQCTZb5RWXIML92lftJLhQz1tBzgKiqGxJaMlBAa48POXaNAC2s4y8jr3EFqrkF9+44neS46w==}
engines: {node: '>= 0.4'}
@@ -4700,10 +4778,14 @@ snapshots:
'@floating-ui/utils@0.2.12': {}
'@fontsource/cormorant-garamond@5.3.0': {}
'@fontsource/jost@5.3.0': {}
'@fontsource/marcellus@5.3.0': {}
'@fontsource/mulish@5.3.0': {}
'@formatjs/ecma402-abstract@2.3.6':
dependencies:
'@formatjs/fast-memoize': 2.2.7
@@ -4730,6 +4812,8 @@ snapshots:
dependencies:
tslib: 2.8.1
'@friendlycaptcha/sdk@1.1.3': {}
'@humanfs/core@0.19.2':
dependencies:
'@humanfs/types': 0.15.0
@@ -6112,6 +6196,15 @@ snapshots:
is-string: 1.1.1
math-intrinsics: 1.1.0
array.prototype.findlast@1.2.5:
dependencies:
call-bind: 1.0.9
define-properties: 1.2.1
es-abstract: 1.24.2
es-errors: 1.3.0
es-object-atoms: 1.1.2
es-shim-unscopables: 1.1.0
array.prototype.flat@1.3.3:
dependencies:
call-bind: 1.0.9
@@ -6126,6 +6219,14 @@ snapshots:
es-abstract: 1.24.2
es-shim-unscopables: 1.1.0
array.prototype.tosorted@1.1.4:
dependencies:
call-bind: 1.0.9
define-properties: 1.2.1
es-abstract: 1.24.2
es-errors: 1.3.0
es-shim-unscopables: 1.1.0
arraybuffer.prototype.slice@1.0.4:
dependencies:
array-buffer-byte-length: 1.0.2
@@ -6524,6 +6625,10 @@ snapshots:
diff@9.0.0: {}
doctrine@2.1.0:
dependencies:
esutils: 2.0.3
dom-accessibility-api@0.5.16: {}
dom-accessibility-api@0.6.3: {}
@@ -6633,6 +6738,25 @@ snapshots:
es-errors@1.3.0: {}
es-iterator-helpers@1.4.0:
dependencies:
call-bind: 1.0.9
call-bound: 1.0.4
define-properties: 1.2.1
es-abstract: 1.24.2
es-errors: 1.3.0
es-set-tostringtag: 2.1.0
function-bind: 1.1.2
get-intrinsic: 1.3.0
globalthis: 1.0.4
gopd: 1.2.0
has-property-descriptors: 1.0.2
has-proto: 1.2.0
has-symbols: 1.1.0
internal-slot: 1.1.0
iterator.prototype: 1.1.5
math-intrinsics: 1.1.0
es-module-lexer@2.3.2: {}
es-object-atoms@1.1.2:
@@ -6734,6 +6858,28 @@ snapshots:
transitivePeerDependencies:
- supports-color
eslint-plugin-react@7.37.5(eslint@9.39.5(jiti@2.7.0)(supports-color@5.5.0)):
dependencies:
array-includes: 3.2.0
array.prototype.findlast: 1.2.5
array.prototype.flatmap: 1.3.3
array.prototype.tosorted: 1.1.4
doctrine: 2.1.0
es-iterator-helpers: 1.4.0
eslint: 9.39.5(jiti@2.7.0)(supports-color@5.5.0)
estraverse: 5.3.0
hasown: 2.0.4
jsx-ast-utils: 3.3.5
minimatch: 3.1.5
object.entries: 1.1.9
object.fromentries: 2.0.8
object.values: 1.2.1
prop-types: 15.8.1
resolve: 2.0.0-next.7
semver: 6.3.1
string.prototype.matchall: 4.1.0
string.prototype.repeat: 1.0.0
eslint-scope@8.4.0:
dependencies:
esrecurse: 4.3.0
@@ -7349,6 +7495,15 @@ snapshots:
transitivePeerDependencies:
- encoding
iterator.prototype@1.1.5:
dependencies:
define-data-property: 1.1.4
es-object-atoms: 1.1.2
get-intrinsic: 1.3.0
get-proto: 1.0.1
has-symbols: 1.1.0
set-function-name: 2.0.2
jiti@2.7.0: {}
jpeg-js@0.4.4: {}
@@ -7560,6 +7715,10 @@ snapshots:
lookup-closest-locale@6.2.0: {}
loose-envify@1.4.0:
dependencies:
js-tokens: 4.0.0
lru-cache@11.5.3: {}
lru-cache@5.1.1:
@@ -7655,12 +7814,21 @@ snapshots:
netmask@2.1.1: {}
node-exports-info@1.6.2:
dependencies:
array.prototype.flatmap: 1.3.3
es-errors: 1.3.0
object.entries: 1.1.9
semver: 6.3.1
node-fetch@2.7.0:
dependencies:
whatwg-url: 5.0.0
node-releases@2.0.57: {}
object-assign@4.1.1: {}
object-inspect@1.13.4: {}
object-keys@1.1.1: {}
@@ -7674,6 +7842,13 @@ snapshots:
has-symbols: 1.1.0
object-keys: 1.1.1
object.entries@1.1.9:
dependencies:
call-bind: 1.0.9
call-bound: 1.0.4
define-properties: 1.2.1
es-object-atoms: 1.1.2
object.fromentries@2.0.8:
dependencies:
call-bind: 1.0.9
@@ -7838,6 +8013,12 @@ snapshots:
progress@2.0.3: {}
prop-types@15.8.1:
dependencies:
loose-envify: 1.4.0
object-assign: 4.1.1
react-is: 16.13.1
proxy-addr@2.0.8:
dependencies:
forwarded: 0.2.0
@@ -7969,6 +8150,15 @@ snapshots:
path-parse: 1.0.7
supports-preserve-symlinks-flag: 1.0.0
resolve@2.0.0-next.7:
dependencies:
es-errors: 1.3.0
is-core-module: 2.17.0
node-exports-info: 1.6.2
object-keys: 1.1.1
path-parse: 1.0.7
supports-preserve-symlinks-flag: 1.0.0
restore-cursor@2.0.0:
dependencies:
onetime: 2.0.1
@@ -8221,6 +8411,27 @@ snapshots:
define-properties: 1.2.1
es-abstract: 1.24.2
string.prototype.matchall@4.1.0:
dependencies:
call-bind: 1.0.9
call-bound: 1.0.4
define-properties: 1.2.1
es-abstract: 1.24.2
es-errors: 1.3.0
es-object-atoms: 1.1.2
get-intrinsic: 1.3.0
gopd: 1.2.0
has-symbols: 1.1.0
internal-slot: 1.1.0
regexp.prototype.flags: 1.5.4
set-function-name: 2.0.2
side-channel: 1.1.1
string.prototype.repeat@1.0.0:
dependencies:
define-properties: 1.2.1
es-abstract: 1.24.2
string.prototype.trim@1.2.11:
dependencies:
call-bind: 1.0.9
+4 -4
View File
@@ -191,7 +191,7 @@ describe('app', () => {
await screen.findByTestId('contact-form-shoot', undefined, {
timeout: 10_000,
}),
).toHaveValue('newborn');
).toHaveValue('Newborn');
await waitFor(() => expect(router.state.location.searchStr).toBe(''));
expect(router.state.location.pathname).toBe('/contact');
expect(document.activeElement).toBe(document.body);
@@ -451,7 +451,7 @@ describe('homepage ?pakket=', () => {
await screen.findByTestId('contact-form-shoot', undefined, {
timeout: 10_000,
}),
).toHaveValue('newborn');
).toHaveValue('Newborn');
await waitFor(() =>
expect(
scrolls.mock.contexts.some(
@@ -468,11 +468,11 @@ describe('homepage ?pakket=', () => {
await screen.findByTestId('contact-form-shoot', undefined, {
timeout: 10_000,
}),
).toHaveValue('newborn');
).toHaveValue('Newborn');
await waitFor(() => expect(router.state.location.searchStr).toBe(''));
expect(router.state.location.hash).toBe('contact');
// The form stays once loaded, also now that ?pakket= is gone
expect(screen.getByTestId('contact-form-shoot')).toHaveValue('newborn');
expect(screen.getByTestId('contact-form-shoot')).toHaveValue('Newborn');
// within the section: the footer has a "Contact" heading too
expect(
within(screen.getByRole('region', { name: 'Contact' })).getByRole(
Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

+7
View File
@@ -1,13 +1,20 @@
import { StrictMode, startTransition } from 'react';
import { hydrateRoot } from 'react-dom/client';
import { StartClient } from '@tanstack/react-start/client';
import { readCmsData } from './lib/cmsData';
import { startSentry } from './monitoring/sentry';
import { setSiteUrl } from './seo';
// Foutmeldingen naar Sentry, alleen op test en productie (M1). Dit bestand
// draait alleen in de browser, dus niet tijdens het prerenderen, en loopt voor
// op het hydrateren zodat ook vroege fouten gemeld worden.
startSentry();
// The CMS host writes the address of the site it serves into the data block;
// the script files cannot carry it. Without a block the built-in one stays.
const page = readCmsData(document);
if (page?.siteUrl) setSiteUrl(page.siteUrl);
startTransition(() => {
hydrateRoot(
document,
+16
View File
@@ -0,0 +1,16 @@
# cms-client (draft package)
Headless client for the SLP CMS API, written inside the SlpSoftware frontend first and meant to move to the SlpModularCms repository as the package `cms-client` (decision of the product owner, 2026-11-09).
- **Boundary**: nothing in this folder may import from the rest of the app (`features`, `components`, `shared`, `theme`, `utils`, ...); enforced by ESLint (`no-restricted-imports`) and a test. Allowed: `react` and files inside `src/cms-client`.
- **Parts** (import only what a site uses): `contact/` (validation, reducer, client, `useContactForm`), `http/` (internal helpers). `offerings/` follows later.
- **Contract**: see `aidlc-docs/features/redesign-modern-timetravel/inception/application-design/contact-api-contract.md` and the CMS file `openapi/slpsoftware.v1.json`.
- **No markup, no styling**: sites render their own fields from `useContactForm().getFieldProps`.
- **Privacy**: nothing here logs form values, tokens or idempotency keys.
## Captcha slot and initial subject
- The token response may carry `captcha: { provider, siteKey, apiEndpoint }` (`apiEndpoint` is `global` or `eu`, default `global`). `useContactForm` returns `captcha`, `captchaRequired`, `captchaToken`, `setCaptchaToken(token | null)` and `captchaResetCount`. The package renders no widget: the site mounts the provider widget client-side, calls `setCaptchaToken(response)` when solved and `setCaptchaToken(null)` when it expires or fails, and resets the widget whenever `captchaResetCount` changes (a response can be used once).
- With captcha required, submit sends nothing until a response is set and shows `messages.captchaRequired`; the payload then carries `captchaToken`. Without captcha the field is omitted.
- `initialSubject` (option of `useContactForm`) applies a subject chosen before the form was mounted, as soon as it exists in `subjectOptions` and unless the visitor already picked one. Unknown values are ignored.
- Subject values are the readable labels (they appear in the mail and the CMS message list); a site keeps its own ids only for links/preselect.
@@ -0,0 +1,47 @@
import { describe, expect, it } from 'vitest';
// All source files of the package (tests excluded), as raw text.
const sources = import.meta.glob(['../**/*.{ts,tsx}', '!../**/__tests__/**'], {
query: '?raw',
import: 'default',
eager: true,
}) as Record<string, string>;
const files = Object.entries(sources);
describe('cms-client boundary (movable package)', () => {
it('finds the package sources', () => {
expect(files.length).toBeGreaterThan(5);
});
it('only imports react and files inside src/cms-client', () => {
const offenders: string[] = [];
for (const [file, text] of files) {
for (const match of text.matchAll(/from\s+['"]([^'"]+)['"]/g)) {
const spec = match[1];
if (spec === 'react') continue;
if (spec.startsWith('./')) continue;
if (spec.startsWith('../')) {
// Count how far the import climbs out of the package: file path is ../<inside>/x.ts
const depthInside = file.replace(/^\.\.\//, '').split('/').length - 1;
const climbs = spec.split('/').filter((part) => part === '..').length;
if (climbs <= depthInside) continue;
}
offenders.push(`${file}: ${spec}`);
}
}
expect(offenders).toEqual([]);
});
it('reads configuration only through import.meta.env.VITE_API_BASE_URL', () => {
const uses = files.flatMap(([, text]) =>
[...text.matchAll(/import\.meta\.env\.(\w+)/g)].map((m) => m[1]),
);
expect([...new Set(uses)]).toEqual(['VITE_API_BASE_URL']);
});
it('does not log anything', () => {
const logging = files.filter(([, text]) => /console\.(log|info|warn|error|debug)/.test(text));
expect(logging).toEqual([]);
});
});
@@ -0,0 +1,163 @@
import fc from 'fast-check';
import { describe, expect, it } from 'vitest';
import {
contactFormReducer,
initialContactState,
type ContactEvent,
type ContactState,
} from '../contactFormReducer';
import type { ContactField } from '../types';
function run(events: ContactEvent[], from: ContactState = initialContactState): ContactState {
return events.reduce(contactFormReducer, from);
}
const fill: ContactEvent[] = [
{ type: 'change', field: 'name', value: 'Jan' },
{ type: 'change', field: 'email', value: 'jan@example.nl' },
{ type: 'change', field: 'subject', value: 'website' },
{ type: 'change', field: 'message', value: 'Hallo' },
];
describe('contactFormReducer (examples)', () => {
it('starts empty and editing', () => {
expect(initialContactState.status).toBe('editing');
expect(initialContactState.values.name).toBe('');
});
it('shows an error only after blur of a touched field, and clears it when valid', () => {
let state = run([{ type: 'change', field: 'email', value: 'nope' }]);
expect(state.errors.email).toBeUndefined();
state = run([{ type: 'blur', field: 'email' }], state);
expect(state.errors.email).toBe('invalid');
state = run([{ type: 'change', field: 'email', value: 'a@b.nl' }], state);
expect(state.errors.email).toBeUndefined();
});
it('shows all errors after a submit attempt and stays editing', () => {
const state = run([{ type: 'submit' }]);
expect(Object.keys(state.errors).sort()).toEqual(['email', 'message', 'name', 'subject']);
expect(state.status).toBe('editing');
});
it('refuses to start sending while invalid', () => {
expect(run([{ type: 'sending' }]).status).toBe('editing');
});
it('goes editing -> sending -> sent and ignores edits while sending', () => {
let state = run([...fill, { type: 'sending' }]);
expect(state.status).toBe('sending');
const during = run(
[{ type: 'change', field: 'name', value: 'Piet' }, { type: 'submit' }],
state,
);
expect(during).toBe(state);
state = run([{ type: 'succeeded' }], state);
expect(state.status).toBe('sent');
});
it('keeps all input after a failure and returns to editing on change', () => {
let state = run([...fill, { type: 'sending' }, { type: 'failed' }]);
expect(state.status).toBe('failed');
expect(state.values.message).toBe('Hallo');
state = run([{ type: 'change', field: 'message', value: 'Hallo!' }], state);
expect(state.status).toBe('editing');
});
it('maps server field errors back to editing with the errors shown', () => {
const state = run([
...fill,
{ type: 'sending' },
{ type: 'fieldErrors', errors: { email: 'invalid' } },
]);
expect(state.status).toBe('editing');
expect(state.errors).toEqual({ email: 'invalid' });
});
it('never leaves sent except through reset', () => {
const sent = run([...fill, { type: 'sending' }, { type: 'succeeded' }]);
expect(
run(
[{ type: 'change', field: 'name', value: 'X' }, { type: 'failed' }, { type: 'submit' }],
sent,
),
).toBe(sent);
expect(run([{ type: 'reset' }], sent)).toEqual(initialContactState);
});
it('applies a preselect to the subject', () => {
expect(run([{ type: 'preselect', subject: 'maatwerk' }]).values.subject).toBe('maatwerk');
});
});
describe('contactFormReducer (properties)', () => {
const field = fc.constantFrom<ContactField>('name', 'email', 'subject', 'message');
const event: fc.Arbitrary<ContactEvent> = fc.oneof(
fc.record({ type: fc.constant('change' as const), field, value: fc.string({ maxLength: 40 }) }),
fc.record({ type: fc.constant('blur' as const), field }),
fc.constant({ type: 'submit' } as ContactEvent),
fc.constant({ type: 'sending' } as ContactEvent),
fc.constant({ type: 'succeeded' } as ContactEvent),
fc.constant({ type: 'failed' } as ContactEvent),
fc.record({ type: fc.constant('preselect' as const), subject: fc.string({ maxLength: 10 }) }),
);
it('sent is absorbing except for reset', () => {
fc.assert(
fc.property(fc.array(event, { maxLength: 30 }), (rest) => {
const sent = run([...fill, { type: 'sending' }, { type: 'succeeded' }]);
expect(run(rest, sent)).toBe(sent);
}),
);
});
it('ignores edits and submits while sending', () => {
fc.assert(
fc.property(
fc.array(
fc.oneof(
fc.record({
type: fc.constant('change' as const),
field,
value: fc.string({ maxLength: 10 }),
}),
fc.constant({ type: 'submit' } as ContactEvent),
fc.record({
type: fc.constant('preselect' as const),
subject: fc.string({ maxLength: 10 }),
}),
),
{ maxLength: 20 },
),
(edits) => {
const sending = run([...fill, { type: 'sending' }]);
expect(run(edits, sending)).toBe(sending);
},
),
);
});
it('never loses typed values on failure', () => {
fc.assert(
fc.property(fc.array(event, { maxLength: 30 }), (events) => {
const before = run([...fill, { type: 'sending' }]);
const after = run([{ type: 'failed' }], before);
expect(after.values).toEqual(before.values);
void events;
}),
);
});
it('only reaches sending from a valid form', () => {
fc.assert(
fc.property(fc.array(event, { maxLength: 40 }), (events) => {
const state = run(events);
if (state.status === 'sending' || state.status === 'sent') {
expect(
Object.keys(run([{ type: 'submit' }], { ...state, status: 'editing' }).errors),
).toEqual([]);
}
}),
);
});
});
@@ -0,0 +1,251 @@
import fc from 'fast-check';
import { describe, expect, it, vi } from 'vitest';
import { createContactClient } from '../createContactClient';
import { parseProblem } from '../../http/problem';
import { retryAfterMinutes } from '../messages.nl';
import type { ContactPayload } from '../types';
const payload: ContactPayload = {
name: 'Jan',
email: 'jan@example.nl',
subject: 'website',
message: 'Hallo',
hpCheck: '',
token: 'tok',
};
function client(response: Response | Error) {
const fetchMock = vi.fn(async () => {
if (response instanceof Error) throw response;
return response;
});
return {
api: createContactClient({ baseUrl: '', fetch: fetchMock as unknown as typeof fetch }),
fetchMock,
};
}
function json(body: unknown, status: number, headers: Record<string, string> = {}) {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json', ...headers },
});
}
describe('getToken', () => {
it('returns the token on 200 and calls the contract path', async () => {
const { api, fetchMock } = client(json({ token: 'abc', minSeconds: 3, captcha: null }, 200));
expect(await api.getToken()).toEqual({
kind: 'ok',
token: { token: 'abc', minSeconds: 3, captcha: null },
});
expect((fetchMock.mock.calls[0] as unknown as [string])[0]).toBe(
'/api/v1/contact-messages/token',
);
});
it('parses captcha info', async () => {
const { api } = client(
json({ token: 'abc', minSeconds: 3, captcha: { provider: 'fc', siteKey: 'k' } }, 200),
);
const result = await api.getToken();
expect(result.kind === 'ok' && result.token.captcha).toEqual({
provider: 'fc',
siteKey: 'k',
apiEndpoint: 'global',
});
});
it('takes the captcha api endpoint from the server and falls back to global', async () => {
const eu = client(
json(
{ token: 'a', minSeconds: 3, captcha: { provider: 'fc', siteKey: 'k', apiEndpoint: 'eu' } },
200,
),
);
const euResult = await eu.api.getToken();
expect(euResult.kind === 'ok' && euResult.token.captcha?.apiEndpoint).toBe('eu');
const odd = client(
json(
{ token: 'a', minSeconds: 3, captcha: { provider: 'fc', siteKey: 'k', apiEndpoint: 'x' } },
200,
),
);
const oddResult = await odd.api.getToken();
expect(oddResult.kind === 'ok' && oddResult.token.captcha?.apiEndpoint).toBe('global');
});
it.each([
[404, 'closed'],
[429, 'failed'],
[500, 'failed'],
[503, 'failed'],
])('maps status %i to %s', async (status, kind) => {
const { api } = client(new Response(null, { status }));
expect((await api.getToken()).kind).toBe(kind);
});
it('treats a malformed 200 body and network errors as failed', async () => {
expect((await client(json({ nope: true }, 200)).api.getToken()).kind).toBe('failed');
expect((await client(new Error('offline')).api.getToken()).kind).toBe('failed');
});
});
describe('submit', () => {
it('posts the contract body with the idempotency key and treats 202 as ok', async () => {
const { api, fetchMock } = client(json({ status: 'received' }, 202));
expect(await api.submit(payload, { idempotencyKey: 'key-1' })).toEqual({ kind: 'ok' });
const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
expect(url).toBe('/api/v1/contact-messages');
expect(init.method).toBe('POST');
expect((init.headers as Record<string, string>)['Idempotency-Key']).toBe('key-1');
expect(JSON.parse(init.body as string)).toEqual(payload);
});
it('maps 400 field errors and ignores unknown fields/codes', async () => {
const { api } = client(
json(
{
errors: {
email: ['invalid'],
message: ['tooLong'],
other: ['required'],
name: ['weird'],
},
},
400,
),
);
expect(await api.submit(payload, { idempotencyKey: 'k' })).toEqual({
kind: 'invalid',
fields: { email: 'invalid', message: 'tooLong' },
tokenExpired: false,
});
});
it('flags an expired token', async () => {
const { api } = client(json({ errors: { token: ['expired'] } }, 400));
expect(await api.submit(payload, { idempotencyKey: 'k' })).toEqual({
kind: 'invalid',
fields: {},
tokenExpired: true,
});
});
it('treats a 400 without usable errors (body, idempotencyKey) as failed', async () => {
const { api } = client(json({ errors: { body: ['invalid'] } }, 400));
expect((await api.submit(payload, { idempotencyKey: 'k' })).kind).toBe('failed');
});
it('maps 413, 404, 429 (with Retry-After) and 5xx', async () => {
expect(
(
await client(new Response(null, { status: 413 })).api.submit(payload, {
idempotencyKey: 'k',
})
).kind,
).toBe('tooLarge');
expect(
(
await client(new Response(null, { status: 404 })).api.submit(payload, {
idempotencyKey: 'k',
})
).kind,
).toBe('closed');
expect(
await client(json({}, 429, { 'Retry-After': '120' })).api.submit(payload, {
idempotencyKey: 'k',
}),
).toEqual({ kind: 'rateLimited', retryAfterSeconds: 120 });
expect(
(
await client(new Response(null, { status: 500 })).api.submit(payload, {
idempotencyKey: 'k',
})
).kind,
).toBe('failed');
});
it('never throws on network errors', async () => {
const { api } = client(new Error('offline'));
expect((await api.submit(payload, { idempotencyKey: 'k' })).kind).toBe('failed');
});
it('times out hanging requests', async () => {
vi.useFakeTimers();
const hanging = vi.fn(
(_url: string, init?: RequestInit) =>
new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener('abort', () =>
reject(new DOMException('aborted', 'AbortError')),
);
}),
);
const api = createContactClient({ baseUrl: '', fetch: hanging as unknown as typeof fetch });
const promise = api.submit(payload, { idempotencyKey: 'k' });
await vi.advanceTimersByTimeAsync(10_001);
expect((await promise).kind).toBe('failed');
vi.useRealTimers();
});
});
describe('serialization round trips (properties)', () => {
it('payload JSON survives a stringify/parse round trip', () => {
fc.assert(
fc.property(
fc.record({
name: fc.string({ maxLength: 100 }),
email: fc.string({ maxLength: 254 }),
subject: fc.string({ maxLength: 100 }),
message: fc.string({ maxLength: 500 }),
hpCheck: fc.constant(''),
token: fc.string({ minLength: 1, maxLength: 50 }),
}),
(p) => {
expect(JSON.parse(JSON.stringify(p))).toEqual(p);
},
),
);
});
it('parseProblem recovers the error map of a serialized problem', () => {
fc.assert(
fc.property(
fc.dictionary(
fc.constantFrom('name', 'email', 'subject', 'message', 'token'),
fc.array(fc.constantFrom('required', 'tooLong', 'invalid', 'expired'), {
minLength: 1,
maxLength: 3,
}),
),
(errors) => {
const body = JSON.parse(
JSON.stringify({ type: 'about:blank', title: 't', status: 400, errors }),
);
expect(parseProblem(400, body, null).errors).toEqual(errors);
},
),
);
});
it('parseProblem never throws on arbitrary JSON', () => {
fc.assert(
fc.property(fc.anything(), (body) => {
expect(() => parseProblem(400, body, null)).not.toThrow();
}),
);
});
it('retryAfterMinutes rounds up and is at least 1', () => {
fc.assert(
fc.property(fc.integer({ min: -10, max: 100_000 }), (seconds) => {
const minutes = retryAfterMinutes(seconds);
expect(minutes).toBeGreaterThanOrEqual(1);
if (seconds > 0) expect(minutes * 60).toBeGreaterThanOrEqual(seconds);
}),
);
expect(retryAfterMinutes(null)).toBe(1);
expect(retryAfterMinutes(61)).toBe(2);
});
});
@@ -0,0 +1,221 @@
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import { useContactForm } from '../useContactForm';
import type { ContactClient, ContactPayload, ContactToken, SubmitResult } from '../types';
const OPTIONS = [
{ value: 'Website', label: 'Website' },
{ value: 'Overig', label: 'Overig' },
];
const CAPTCHA_TOKEN: ContactToken = {
token: 'tok',
minSeconds: 3,
captcha: { provider: 'friendlycaptcha', siteKey: 'FCMKEY', apiEndpoint: 'global' },
};
const PLAIN_TOKEN: ContactToken = { token: 'tok', minSeconds: 3, captcha: null };
function makeClient(results: SubmitResult[] = [{ kind: 'ok' }]) {
const payloads: ContactPayload[] = [];
const submit = vi.fn(async (payload: ContactPayload) => {
payloads.push(payload);
return results.shift() ?? ({ kind: 'ok' } as SubmitResult);
});
const client: ContactClient = {
getToken: async () => ({ kind: 'ok', token: PLAIN_TOKEN }),
submit,
};
return { client, payloads, submit };
}
function Harness(props: {
token: ContactToken;
client: ContactClient;
options?: typeof OPTIONS;
initialSubject?: string | null;
}) {
const form = useContactForm({
idPrefix: 'c',
subjectOptions: props.options ?? OPTIONS,
initialSubject: props.initialSubject,
client: props.client,
token: props.token,
refreshToken: async () => ({ kind: 'ok', token: props.token }),
fallbackAddress: 'info@example.nl',
});
const name = form.getFieldProps('name');
const email = form.getFieldProps('email');
const subject = form.getFieldProps('subject');
const message = form.getFieldProps('message');
return (
<form {...form.formProps}>
<input aria-label="naam" {...name.inputProps} />
<input aria-label="mail" {...email.inputProps} />
<select aria-label="onderwerp" {...subject.inputProps}>
<option value="" />
{(props.options ?? OPTIONS).map((o) => (
<option key={o.value} value={o.value}>
{o.label}
</option>
))}
</select>
<textarea aria-label="bericht" {...message.inputProps} />
<button type="submit">verstuur</button>
<output data-testid="captcha-required">{String(form.captchaRequired)}</output>
<output data-testid="captcha-site-key">{form.captcha?.siteKey ?? '-'}</output>
<output data-testid="captcha-endpoint">{form.captcha?.apiEndpoint ?? '-'}</output>
<output data-testid="reset-count">{form.captchaResetCount}</output>
<output data-testid="failure">{form.failureMessage ?? ''}</output>
<output data-testid="status">{form.status}</output>
<button type="button" onClick={() => form.setCaptchaToken('frc-response')}>
solved
</button>
<button type="button" onClick={() => form.setCaptchaToken(null)}>
expired
</button>
</form>
);
}
function fill() {
fireEvent.change(screen.getByLabelText('naam'), { target: { value: 'Jan' } });
fireEvent.change(screen.getByLabelText('mail'), { target: { value: 'jan@example.nl' } });
fireEvent.change(screen.getByLabelText('onderwerp'), { target: { value: 'Website' } });
fireEvent.change(screen.getByLabelText('bericht'), { target: { value: 'Hallo daar' } });
}
describe('captcha slot', () => {
it('exposes the captcha info from the token response', () => {
render(<Harness token={CAPTCHA_TOKEN} client={makeClient().client} />);
expect(screen.getByTestId('captcha-required')).toHaveTextContent('true');
expect(screen.getByTestId('captcha-site-key')).toHaveTextContent('FCMKEY');
expect(screen.getByTestId('captcha-endpoint')).toHaveTextContent('global');
});
it('reports no captcha when the server asks for none', () => {
render(<Harness token={PLAIN_TOKEN} client={makeClient().client} />);
expect(screen.getByTestId('captcha-required')).toHaveTextContent('false');
});
it('does not send until the captcha is solved and shows the message', async () => {
const { client, submit } = makeClient();
render(<Harness token={CAPTCHA_TOKEN} client={client} />);
fill();
fireEvent.submit(screen.getByRole('button', { name: 'verstuur' }).closest('form')!);
await waitFor(() =>
expect(screen.getByTestId('failure')).toHaveTextContent(
'Bevestig eerst dat je geen robot bent.',
),
);
expect(submit).not.toHaveBeenCalled();
expect(screen.getByTestId('status')).toHaveTextContent('editing');
});
it('sends the captcha response with the payload and asks for a widget reset afterwards', async () => {
const { client, payloads } = makeClient();
render(<Harness token={CAPTCHA_TOKEN} client={client} />);
fill();
fireEvent.click(screen.getByText('solved'));
fireEvent.submit(screen.getByRole('button', { name: 'verstuur' }).closest('form')!);
await waitFor(() => expect(screen.getByTestId('status')).toHaveTextContent('sent'));
expect(payloads[0].captchaToken).toBe('frc-response');
expect(screen.getByTestId('reset-count')).toHaveTextContent('1');
});
it('never sends an expired captcha response', async () => {
const { client, submit } = makeClient();
render(<Harness token={CAPTCHA_TOKEN} client={client} />);
fill();
fireEvent.click(screen.getByText('solved'));
fireEvent.click(screen.getByText('expired'));
fireEvent.submit(screen.getByRole('button', { name: 'verstuur' }).closest('form')!);
await waitFor(() => expect(screen.getByTestId('failure')).toHaveTextContent('geen robot'));
expect(submit).not.toHaveBeenCalled();
});
it('needs a new captcha response after a failed attempt', async () => {
const { client, submit } = makeClient([{ kind: 'failed' }]);
render(<Harness token={CAPTCHA_TOKEN} client={client} />);
fill();
fireEvent.click(screen.getByText('solved'));
fireEvent.submit(screen.getByRole('button', { name: 'verstuur' }).closest('form')!);
await waitFor(() => expect(screen.getByTestId('status')).toHaveTextContent('failed'));
expect(screen.getByTestId('reset-count')).toHaveTextContent('1');
fireEvent.submit(screen.getByRole('button', { name: 'verstuur' }).closest('form')!);
await waitFor(() => expect(screen.getByTestId('failure')).toHaveTextContent('geen robot'));
expect(submit).toHaveBeenCalledTimes(1);
});
it('omits captchaToken when no captcha is configured', async () => {
const { client, payloads } = makeClient();
render(<Harness token={PLAIN_TOKEN} client={client} />);
fill();
fireEvent.submit(screen.getByRole('button', { name: 'verstuur' }).closest('form')!);
await waitFor(() => expect(screen.getByTestId('status')).toHaveTextContent('sent'));
expect('captchaToken' in payloads[0]).toBe(false);
});
});
describe('initialSubject', () => {
it('applies a subject chosen before the form was mounted', async () => {
render(<Harness token={PLAIN_TOKEN} client={makeClient().client} initialSubject="Website" />);
await waitFor(() =>
expect((screen.getByLabelText('onderwerp') as HTMLSelectElement).value).toBe('Website'),
);
});
it('waits until the option exists and ignores unknown values', async () => {
const { rerender } = render(
<Harness
token={PLAIN_TOKEN}
client={makeClient().client}
options={[{ value: 'Overig', label: 'Overig' }]}
initialSubject="Website"
/>,
);
expect((screen.getByLabelText('onderwerp') as HTMLSelectElement).value).toBe('');
await act(async () => {
rerender(
<Harness
token={PLAIN_TOKEN}
client={makeClient().client}
options={OPTIONS}
initialSubject="Website"
/>,
);
});
await waitFor(() =>
expect((screen.getByLabelText('onderwerp') as HTMLSelectElement).value).toBe('Website'),
);
});
it('does not override a subject the visitor already chose', async () => {
const { rerender } = render(
<Harness
token={PLAIN_TOKEN}
client={makeClient().client}
options={[{ value: 'Overig', label: 'Overig' }]}
initialSubject="Website"
/>,
);
fireEvent.change(screen.getByLabelText('onderwerp'), { target: { value: 'Overig' } });
await act(async () => {
rerender(
<Harness
token={PLAIN_TOKEN}
client={makeClient().client}
options={OPTIONS}
initialSubject="Website"
/>,
);
});
expect((screen.getByLabelText('onderwerp') as HTMLSelectElement).value).toBe('Overig');
});
it('ignores an unknown initial subject', () => {
render(
<Harness token={PLAIN_TOKEN} client={makeClient().client} initialSubject="Bestaat niet" />,
);
expect((screen.getByLabelText('onderwerp') as HTMLSelectElement).value).toBe('');
});
});
@@ -0,0 +1,112 @@
import fc from 'fast-check';
import { describe, expect, it } from 'vitest';
import { CONTACT_LIMITS, EMPTY_FIELDS, type ContactFields } from '../types';
import { hasErrors, trimFields, validateContact } from '../validateContact';
const valid: ContactFields = {
name: 'Jan Jansen',
email: 'jan@example.nl',
subject: 'website',
message: 'Ik wil graag een offerte.',
};
describe('validateContact (examples)', () => {
it('accepts valid values', () => {
expect(validateContact(valid)).toEqual({});
expect(hasErrors(validateContact(valid))).toBe(false);
});
it('requires every field (after trimming)', () => {
expect(validateContact(EMPTY_FIELDS)).toEqual({
name: 'required',
email: 'required',
subject: 'required',
message: 'required',
});
expect(validateContact({ ...valid, name: ' ', message: '\n\t ' })).toEqual({
name: 'required',
message: 'required',
});
});
it.each([
['plain', false],
['a@b', false],
['a@b.c', false],
['a b@c.nl', false],
['a@b.nl', true],
['first.last+tag@sub.example.nl', true],
])('email %s valid=%s', (email, ok) => {
const errors = validateContact({ ...valid, email });
expect(errors.email).toBe(ok ? undefined : 'invalid');
});
it('reports the first failing rule per field: required, then length, then format', () => {
const tooLongInvalid = 'x'.repeat(CONTACT_LIMITS.email + 1);
expect(validateContact({ ...valid, email: tooLongInvalid }).email).toBe('tooLong');
expect(validateContact({ ...valid, email: 'nope' }).email).toBe('invalid');
});
it('rejects control characters in name, email and subject, but allows line breaks in the message', () => {
expect(validateContact({ ...valid, name: 'Jan\nJansen' }).name).toBe('invalid');
expect(validateContact({ ...valid, subject: 'a\u0007b' }).subject).toBe('invalid');
expect(validateContact({ ...valid, message: 'regel 1\nregel 2\tmet tab' })).toEqual({});
expect(validateContact({ ...valid, message: 'bel\u0007' }).message).toBe('invalid');
});
it('trims before measuring', () => {
expect(validateContact({ ...valid, name: ` ${'a'.repeat(100)} ` })).toEqual({});
});
});
describe('validateContact (properties)', () => {
const text = fc.string({ maxLength: 300 });
const fields = fc.record({ name: text, email: text, subject: text, message: text });
it('is invariant under trimming', () => {
fc.assert(
fc.property(fields, (values) => {
expect(validateContact(values)).toEqual(validateContact(trimFields(values)));
}),
);
});
it('treats the length limits as inclusive for every field', () => {
fc.assert(
fc.property(fc.constantFrom('name', 'subject', 'message' as const), (field) => {
const limit = CONTACT_LIMITS[field];
const at = { ...valid, [field]: 'a'.repeat(limit) };
const over = { ...valid, [field]: 'a'.repeat(limit + 1) };
expect(validateContact(at)[field]).toBeUndefined();
expect(validateContact(over)[field]).toBe('tooLong');
}),
);
const localPart = 'a'.repeat(CONTACT_LIMITS.email - '@b.nl'.length);
expect(validateContact({ ...valid, email: `${localPart}@b.nl` }).email).toBeUndefined();
expect(validateContact({ ...valid, email: `${localPart}a@b.nl` }).email).toBe('tooLong');
});
it('rejects any control character inside name', () => {
fc.assert(
fc.property(
fc.string({ minLength: 1, maxLength: 20 }).filter((s) => s.trim().length > 0),
fc.integer({ min: 0, max: 0x1f }),
(base, code) => {
const name = `${base.trim()}${String.fromCharCode(code)}x`;
if (name.trim() !== name) return; // trimming would remove edge whitespace controls
expect(validateContact({ ...valid, name }).name).toBe('invalid');
},
),
);
});
it('only ever yields known codes', () => {
fc.assert(
fc.property(fields, (values) => {
for (const code of Object.values(validateContact(values))) {
expect(['required', 'tooLong', 'invalid']).toContain(code);
}
}),
);
});
});
@@ -0,0 +1,108 @@
import {
EMPTY_FIELDS,
type ContactField,
type ContactFieldErrors,
type ContactFields,
type ContactStatus,
} from './types';
import { hasErrors, validateContact } from './validateContact';
export interface ContactState {
status: ContactStatus;
values: ContactFields;
touched: Partial<Record<ContactField, boolean>>;
/** Errors currently shown (touched fields or after a submit attempt, plus server errors). */
errors: ContactFieldErrors;
/** True after a submit attempt: every field then shows its error. */
submitted: boolean;
}
export type ContactEvent =
| { type: 'change'; field: ContactField; value: string }
| { type: 'blur'; field: ContactField }
| { type: 'submit' }
| { type: 'sending' }
| { type: 'succeeded' }
| { type: 'failed' }
| { type: 'fieldErrors'; errors: ContactFieldErrors }
| { type: 'preselect'; subject: string }
| { type: 'reset' };
export const initialContactState: ContactState = {
status: 'editing',
values: EMPTY_FIELDS,
touched: {},
errors: {},
submitted: false,
};
function visibleErrors(state: Pick<ContactState, 'values' | 'touched' | 'submitted'>) {
const all = validateContact(state.values);
const shown: ContactFieldErrors = {};
for (const field of Object.keys(all) as ContactField[]) {
if (state.submitted || state.touched[field]) {
shown[field] = all[field];
}
}
return shown;
}
/**
* Pure reducer of the contact form (BR-U4-4, BR-U4-5). Invariants: `sent` only changes through
* `reset`; input is kept on `failed`; edits are ignored while `sending`.
*/
export function contactFormReducer(state: ContactState, event: ContactEvent): ContactState {
if (state.status === 'sent' && event.type !== 'reset') {
return state;
}
switch (event.type) {
case 'reset':
return initialContactState;
case 'change': {
if (state.status === 'sending') {
return state;
}
const values = { ...state.values, [event.field]: event.value };
const next = { ...state, values, status: 'editing' as const };
return { ...next, errors: visibleErrors(next) };
}
case 'preselect': {
if (state.status === 'sending') {
return state;
}
const values = { ...state.values, subject: event.subject };
const next = { ...state, values, status: 'editing' as const };
return { ...next, errors: visibleErrors(next) };
}
case 'blur': {
const touched = { ...state.touched, [event.field]: true };
return { ...state, touched, errors: visibleErrors({ ...state, touched }) };
}
case 'submit': {
if (state.status === 'sending') {
return state;
}
const next = { ...state, submitted: true };
return { ...next, errors: visibleErrors(next) };
}
case 'sending':
return hasErrors(validateContact(state.values)) ? state : { ...state, status: 'sending' };
case 'succeeded':
return state.status === 'sending' ? { ...state, status: 'sent', errors: {} } : state;
case 'failed':
return state.status === 'sending' ? { ...state, status: 'failed' } : state;
case 'fieldErrors':
return state.status === 'sending'
? { ...state, status: 'editing', submitted: true, errors: event.errors }
: state;
}
}
@@ -0,0 +1,118 @@
import { apiUrl } from '../http/apiUrl';
import { fetchJson } from '../http/fetchJson';
import { parseProblem } from '../http/problem';
import type {
ContactClient,
ContactErrorCode,
ContactField,
ContactFieldErrors,
ContactPayload,
ContactToken,
SubmitResult,
TokenResult,
} from './types';
const TOKEN_PATH = '/api/v1/contact-messages/token';
const SUBMIT_PATH = '/api/v1/contact-messages';
const FIELDS: ContactField[] = ['name', 'email', 'subject', 'message'];
const CODES: ContactErrorCode[] = ['required', 'tooLong', 'invalid', 'expired'];
function parseToken(body: unknown): ContactToken | null {
if (!body || typeof body !== 'object') {
return null;
}
const { token, minSeconds, captcha } = body as Record<string, unknown>;
if (typeof token !== 'string' || token.length === 0 || typeof minSeconds !== 'number') {
return null;
}
let parsedCaptcha: ContactToken['captcha'] = null;
if (captcha && typeof captcha === 'object') {
const { provider, siteKey, apiEndpoint } = captcha as Record<string, unknown>;
if (typeof provider !== 'string' || typeof siteKey !== 'string') {
return null;
}
// Additive field: absent or unknown means the default (global) endpoint.
parsedCaptcha = { provider, siteKey, apiEndpoint: apiEndpoint === 'eu' ? 'eu' : 'global' };
}
return { token, minSeconds, captcha: parsedCaptcha };
}
function mapFieldErrors(errors: Record<string, string[]>): ContactFieldErrors {
const result: ContactFieldErrors = {};
for (const field of FIELDS) {
const code = errors[field]?.find((c): c is ContactErrorCode => (CODES as string[]).includes(c));
if (code) {
result[field] = code;
}
}
return result;
}
/**
* Client for the contact endpoints of the CMS API (contract v0.3.x). Never throws: every outcome
* is a typed result. Request and response bodies are never logged.
*/
export function createContactClient(
options: { baseUrl?: string; fetch?: typeof fetch } = {},
): ContactClient {
const fetchImpl = options.fetch ?? ((...args) => fetch(...args));
return {
async getToken(): Promise<TokenResult> {
try {
const response = await fetchJson(fetchImpl, apiUrl(TOKEN_PATH, options.baseUrl), {
method: 'GET',
headers: { Accept: 'application/json' },
});
if (response.status === 200) {
const token = parseToken(response.body);
return token ? { kind: 'ok', token } : { kind: 'failed' };
}
return response.status === 404 ? { kind: 'closed' } : { kind: 'failed' };
} catch {
return { kind: 'failed' };
}
},
async submit(payload: ContactPayload, context): Promise<SubmitResult> {
try {
const response = await fetchJson(fetchImpl, apiUrl(SUBMIT_PATH, options.baseUrl), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'Idempotency-Key': context.idempotencyKey,
},
body: JSON.stringify(payload),
});
switch (response.status) {
case 202:
return { kind: 'ok' };
case 400: {
const problem = parseProblem(400, response.body, response.retryAfter);
const fields = mapFieldErrors(problem.errors);
const tokenExpired = Boolean(problem.errors.token?.includes('expired'));
if (tokenExpired || Object.keys(fields).length > 0) {
return { kind: 'invalid', fields, tokenExpired };
}
return { kind: 'failed' };
}
case 404:
return { kind: 'closed' };
case 413:
return { kind: 'tooLarge' };
case 429:
return {
kind: 'rateLimited',
retryAfterSeconds: parseProblem(429, response.body, response.retryAfter)
.retryAfterSeconds,
};
default:
return { kind: 'failed' };
}
} catch {
return { kind: 'failed' };
}
},
};
}

Some files were not shown because too many files have changed in this diff Show More