From 65c850e949da779b66627b5fd553c3368fc3bd1d Mon Sep 17 00:00:00 2001
From: Sluijsens
Date: Sat, 31 Oct 2026 17:41:12 +0100
Subject: [PATCH 01/49] Adds the prerendering requirements, design and baseline
Records the requirements, execution plan, application design, the first unit's
functional design and code generation plan, and the baseline on master.
Co-Authored-By: Claude Opus 5.5
---
aidlc-docs/active-features.md | 1 +
.../features/prerendering/aidlc-state.md | 65 +++
aidlc-docs/features/prerendering/audit.md | 217 ++++++++
.../start-migration-code-generation-plan.md | 514 ++++++++++++++++++
.../plans/start-migration-fd-questions.md | 12 +
.../start-migration-functional-design-plan.md | 16 +
.../start-migration/code/baseline-checks.md | 29 +
.../code/measurement-baseline.md | 61 +++
.../functional-design/business-logic-model.md | 285 ++++++++++
.../functional-design/business-rules.md | 272 +++++++++
.../functional-design/domain-entities.md | 105 ++++
.../functional-design/frontend-components.md | 147 +++++
.../application-design/application-design.md | 95 ++++
.../component-dependency.md | 67 +++
.../application-design/component-methods.md | 73 +++
.../application-design/components.md | 49 ++
.../inception/application-design/services.md | 48 ++
.../plans/application-design-plan.md | 23 +
.../inception/plans/execution-plan.md | 171 ++++++
.../requirement-clarification-questions.md | 42 ++
.../requirement-verification-questions.md | 129 +++++
.../inception/requirements/requirements.md | 148 +++++
22 files changed, 2569 insertions(+)
create mode 100644 aidlc-docs/features/prerendering/aidlc-state.md
create mode 100644 aidlc-docs/features/prerendering/audit.md
create mode 100644 aidlc-docs/features/prerendering/construction/plans/start-migration-code-generation-plan.md
create mode 100644 aidlc-docs/features/prerendering/construction/plans/start-migration-fd-questions.md
create mode 100644 aidlc-docs/features/prerendering/construction/plans/start-migration-functional-design-plan.md
create mode 100644 aidlc-docs/features/prerendering/construction/start-migration/code/baseline-checks.md
create mode 100644 aidlc-docs/features/prerendering/construction/start-migration/code/measurement-baseline.md
create mode 100644 aidlc-docs/features/prerendering/construction/start-migration/functional-design/business-logic-model.md
create mode 100644 aidlc-docs/features/prerendering/construction/start-migration/functional-design/business-rules.md
create mode 100644 aidlc-docs/features/prerendering/construction/start-migration/functional-design/domain-entities.md
create mode 100644 aidlc-docs/features/prerendering/construction/start-migration/functional-design/frontend-components.md
create mode 100644 aidlc-docs/features/prerendering/inception/application-design/application-design.md
create mode 100644 aidlc-docs/features/prerendering/inception/application-design/component-dependency.md
create mode 100644 aidlc-docs/features/prerendering/inception/application-design/component-methods.md
create mode 100644 aidlc-docs/features/prerendering/inception/application-design/components.md
create mode 100644 aidlc-docs/features/prerendering/inception/application-design/services.md
create mode 100644 aidlc-docs/features/prerendering/inception/plans/application-design-plan.md
create mode 100644 aidlc-docs/features/prerendering/inception/plans/execution-plan.md
create mode 100644 aidlc-docs/features/prerendering/inception/requirements/requirement-clarification-questions.md
create mode 100644 aidlc-docs/features/prerendering/inception/requirements/requirement-verification-questions.md
create mode 100644 aidlc-docs/features/prerendering/inception/requirements/requirements.md
diff --git a/aidlc-docs/active-features.md b/aidlc-docs/active-features.md
index e4f8074..1cffb32 100644
--- a/aidlc-docs/active-features.md
+++ b/aidlc-docs/active-features.md
@@ -10,3 +10,4 @@
| 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 | ๐ต Inception | 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 |
diff --git a/aidlc-docs/features/prerendering/aidlc-state.md b/aidlc-docs/features/prerendering/aidlc-state.md
new file mode 100644
index 0000000..1d6ced4
--- /dev/null
+++ b/aidlc-docs/features/prerendering/aidlc-state.md
@@ -0,0 +1,65 @@
+# AI-DLC State Tracking
+
+## Project Information
+- **Feature Name**: Prerendering (static HTML per page at build time, for performance and SEO)
+- **Feature Slug**: prerendering
+- **Project Type**: Brownfield
+- **Start Date**: 2026-10-31T14:15:01Z
+- **Current Stage**: CONSTRUCTION - Code Generation (unit 1): plan approved; batch B0 running
+- **Branch**: feature/prerendering (from master c4c2f83)
+- **Worktree**: K:\Development\SlpSoftware\Projects\AndreaSlopFotografie-prerendering
+
+## Workspace State
+- **Existing Code**: Yes
+- **Programming Languages**: TypeScript (React/TSX)
+- **Build System**: pnpm + Vite (`tsc && vite build`), Gitea Actions CI
+- **Project Structure**: Single front-end SPA in `web/`; static HTML design reference in `design/andreaslop-static/`; `api/` (.NET back-end)
+- **Reverse Engineering Needed**: No (team agreement: no full RE refresh per feature; only this feature's own lines are updated in `_shared/reverse-engineering/`)
+- **Workspace Root**: K:\Development\SlpSoftware\Projects\AndreaSlopFotografie-prerendering
+
+## Code Location Rules
+- **Application Code**: Workspace root (NEVER in aidlc-docs/) โ front-end lives in `web/`
+- **Feature Documentation**: aidlc-docs/features/prerendering/ only
+- **Shared Artifacts**: aidlc-docs/_shared/
+- **Structure patterns**: See code-generation.md Critical Rules
+
+## Language Configuration
+- **Documentation Language**: English
+- **Conversation Language**: User Language (Dutch)
+- **Source**: inherited from aidlc-docs/language-preference.md (answer A); user may override
+
+## Orchestration
+- The main session orchestrates and is the only Opus. Sub-agents: Haiku where it can handle the task, otherwise Sonnet. Parallel only on disjoint files; results reviewed by the main session before presenting
+- Inception stages were done in the main session; from Functional Design onward the work goes to sub-agents
+
+## Extension Configuration
+| Extension | Enabled | Decided At |
+|---|---|---|
+| Security Baseline | Yes | Requirements Analysis |
+| Property-Based Testing | Yes (full enforcement) | Requirements Analysis |
+
+## Operations Configuration
+- **Include Operations Phase**: No
+- **Decided At**: Requirements Analysis
+
+## Stage Progress
+
+### ๐ต INCEPTION PHASE
+- [x] Workspace Detection
+- [x] Reverse Engineering - SKIP (shared artifacts used; delta lines only)
+- [x] Requirements Analysis (approved)
+- [x] User Stories - SKIP (single visitor type; concrete requirements)
+- [x] Workflow Planning (approved)
+- [x] Application Design - EXECUTE (approved; decisions D1-D13)
+- [x] Units Generation - SKIP (three units fixed in the plan)
+
+### ๐ข CONSTRUCTION PHASE
+- [ ] Functional Design - EXECUTE (units 1, 2) / SKIP (unit 3): unit 1 approved; unit 2 open
+- [ ] NFR Requirements - SKIP
+- [ ] NFR Design - SKIP
+- [ ] Infrastructure Design - EXECUTE (unit 3)
+- [ ] Code Generation - EXECUTE (per unit): 1 Start migration and script step โ decision gate โ 2 Fade-in, no JavaScript, first photo โ 3 Hosting and targets
+- [ ] Build and Test - EXECUTE
+
+### ๐ก OPERATIONS PHASE
+- [ ] Deployment Setup, Monitoring Setup, Production Readiness Validation - SKIP (Operations = No)
diff --git a/aidlc-docs/features/prerendering/audit.md b/aidlc-docs/features/prerendering/audit.md
new file mode 100644
index 0000000..c9c2ab6
--- /dev/null
+++ b/aidlc-docs/features/prerendering/audit.md
@@ -0,0 +1,217 @@
+# Audit log: prerendering
+
+## Workspace Detection
+
+**Timestamp**: 2026-10-31T14:15:01Z
+
+**User Input**: "Ik wil een nieuwe feature toevoegen met aidlc. Namelijk de pre-rendering voor het verbeteren van performance en SEO."
+
+**AI Response**: "Classified as Feature (brownfield). Created worktree ../AndreaSlopFotografie-prerendering on branch feature/prerendering from master c4c2f83. Reverse Engineering skipped: shared artifacts exist and the team agreement is no full refresh per feature. Language inherited from aidlc-docs/language-preference.md (English documentation, Dutch conversation)."
+
+**Context**: Workspace Detection. All items in active-features.md are complete, so no registry conflicts. Peer session 'Shoot-specifieke pagina's' was active at the start and was informed of the affected components.
+
+---
+
+## Requirements Analysis - Verification Questions
+
+**Timestamp**: 2026-10-31T14:15:01Z
+
+**User Input**: "(none: questions generated by the AI)"
+
+**AI Response**: "Created inception/requirements/requirement-verification-questions.md with 11 questions, based on web/vite.config.ts, web/src/main.tsx, web/config/serverConfig.ts, web/config/securityHeaders.ts, web/lighthouserc.cjs, web/src/hooks/useReveal.ts and the CI workflow."
+
+**Context**: Requirements Analysis, Step 6. Awaiting the user's answers.
+
+---
+
+## Peer Session Input
+
+**Timestamp**: 2026-10-31T14:15:01Z
+
+**User Input**: "(none: message from peer session 'Shoot-specifieke pagina's', not from the user)"
+
+**AI Response**: "Recorded for requirements and design: no file overlap, shoot-type-pages is complete in c4c2f83. The owner kept the fade-in on the first story block on 2026-10-30, so changing Reveal needs owner approval (question 3). Peer's mobile Lighthouse on its PC, budget 0.85: newborn 0.86, zwangerschap 0.85, portret 0.85, gezin 0.84-0.85, loveshoot 0.83; photo loads in 15-24 ms, LCP render delay about 2.9 s because the image appears only after the main bundle has run. JSON-LD renders through components/StructuredData with dangerouslySetInnerHTML, to be checked against the CSP. NotFound reads the pathname through useRouterState and shows two extra buttons under /soorten-fotoshoots/ (FR-ST-14), which depends on client-side rendering of the requested URL; noted in question 5, option A. Shoot pages still contain 98 DRAFT and 7 OPEN markers, see features/shoot-type-pages/content-pending.md."
+
+**Context**: Requirements Analysis, while awaiting the user's answers. Peer's figures have not been re-measured in this feature.
+
+---
+
+## Requirements Analysis - Answers Received
+
+**Timestamp**: 2026-10-31T14:15:01Z
+
+**User Input**: "ik heb de vragen beantwoord"
+
+**AI Response**: "Read the answers: Q1 A, Q2 B, Q3 A, Q4 B, Q5 A, Q6 A, Q7 A, Q8 B, Security A, PBT A, Operations B. Checking Q2 (TanStack Start) against the fixed premises (strict CSP, static hosting) and Q8 (external build trigger) for ambiguities before writing requirements."
+
+**Context**: Requirements Analysis, answer validation. Q3 A knowingly replaces the owner's 2026-10-30 choice to keep the fade-in on the first story block.
+
+---
+
+## Requirements Analysis - Spike and Clarification Questions
+
+**Timestamp**: 2026-10-31T14:15:01Z
+
+**User Input**: "(none: validation by the AI)"
+
+**AI Response**: "Ran a throwaway spike outside the repository: @tanstack/react-start 1.169.4 with @tanstack/react-router 1.170.46 and Chakra, prerendered and tested in Chrome with the production script-src. Findings: output in dist/client with HTML and Emotion styles per page; two inline scripts per page, the first with a per-page hash; under the current CSP the scripts are blocked, a page error occurs and the content disappears; after moving the inline scripts to external files in /assets, with the CSP unchanged, the button and client-side link worked and no CSP violations remained. One 404 remained in both variants, not traced; the spike has no favicon. Main bundle 165.0 kB gzip with almost no app code, versus 148.7 kB in an older local build and 152.58 kB recorded in architecture.md for the current site; a rough comparison. Created inception/requirements/requirement-clarification-questions.md with 2 questions: resolving Q2 B against the fixed CSP premise, and the scope of the external build trigger from Q8 B."
+
+**Context**: Requirements Analysis, contradiction and ambiguity check. Decided without a question: Q4 B covers all mobile navigation links including the shoot submenu. Awaiting the user's answers.
+
+---
+
+## Requirements Analysis - Clarifications and Approval Prompt
+
+**Timestamp**: 2026-10-31T14:15:01Z
+
+**User Input**: "ik heb de vragen beantwoord" (clarification 1: "A"; clarification 2: "x, moet er van buiten getriggert worden? Front-end triggeren is voor nu prima want pagina-teksten worden grotendeels vast. de CMS zal alleen gallerijen, pakketten etc doen, maar de belangrijkste teksten worden mogelijk niet aanpasbaar in het CMS. Als dat wel zo is kunnen we tegen die tijd kijken hoe we dat gaan doen")
+
+**AI Response**: "Interpreted clarification 2 as: no external trigger is built now; revisit if the CMS makes page texts editable. Wrote inception/requirements/requirements.md with 21 functional and 15 non-functional requirements and asked for approval. User Stories proposed as skipped. The Gitea API check is no longer needed."
+
+**Context**: Requirements Analysis, Steps 7-9. Awaiting approval.
+
+---
+
+## Requirements Analysis - Approval
+
+**Timestamp**: 2026-10-31T14:15:01Z
+
+**User Input**: "ga verder"
+
+**AI Response**: "Requirements approved; User Stories skipped. Started Workflow Planning."
+
+**Context**: Requirements Analysis approved.
+
+---
+
+## Workflow Planning - Approval Prompt
+
+**Timestamp**: 2026-10-31T14:15:01Z
+
+**User Input**: "(none: plan generated by the AI)"
+
+**AI Response**: "Wrote inception/plans/execution-plan.md: three units with a decision gate after unit 1; Application Design, Functional Design (units 1 and 2), Infrastructure Design (unit 3), Code Generation and Build and Test execute. Asked: ready to proceed with this plan?"
+
+**Context**: Workflow Planning. Awaiting approval.
+
+---
+
+## Workflow Planning - Approval
+
+**Timestamp**: 2026-10-31T14:15:01Z
+
+**User Input**: "plan goedgekeurd. ga verder"
+
+**AI Response**: "Plan approved. Started Application Design."
+
+**Context**: Workflow Planning approved.
+
+---
+
+## Application Design - Approval Prompt
+
+**Timestamp**: 2026-10-31T14:15:01Z
+
+**User Input**: "(none: design generated by the AI)"
+
+**AI Response**: "Extended the spike: autoSubfolderIndex false gives /over-mij without redirect; a 404-status route fails the prerender; a separate /404 route and the SPA shell give React error #418, and the SPA shell also drops index.html; a catch-all $ route with URL-dependent output after hydration gives a real 404 without errors; search values read in the first render give #418, and applied after hydration give none. Wrote application-design artifacts with decisions D1-D13. No question file: each choice was tested or purely technical. Asked for approval."
+
+**Context**: Application Design. Awaiting approval.
+
+---
+
+## Application Design - Approval
+
+**Timestamp**: 2026-10-31T14:15:01Z
+
+**User Input**: "ga verder"
+
+**AI Response**: "Design approved. Started Functional Design for unit 1."
+
+**Context**: Application Design approved; Units Generation stays skipped.
+
+---
+
+## Functional Design - Unit 1 Question and Agent Agreement
+
+**Timestamp**: 2026-10-31T14:15:01Z
+
+**User Input**: "weet jij de afspraken wat betreft gebruik van agents?"
+
+**AI Response**: "Stated the agreement: the main session orchestrates and is the only Opus; sub-agents use Haiku where capable, otherwise Sonnet; parallel only on disjoint files; results are reviewed before presenting. Acknowledged that all stages so far were done in the main session, including the application design artifacts, which should have been reconsidered. Remaining Functional Design and Construction work goes to sub-agents. Created construction/plans/start-migration-fd-questions.md: the e-mail address is deliberately absent from the page, which conflicts with FR-PR-11 and FR-PR-13 once pages are prerendered."
+
+**Context**: Functional Design unit 1, awaiting the owner's answer. Technical point decided without a question: the copyright year must not cause a hydration mismatch when the build year and the visitor's year differ.
+
+---
+
+## Functional Design - Unit 1 Answer
+
+**Timestamp**: 2026-10-31T14:15:01Z
+
+**User Input**: "ik heb de vraag beantwoord" (answer: A)
+
+**AI Response**: "Added FR-PR-22 and an exception in FR-PR-11; removed the mailto route from FR-PR-13. Delegated the unit 1 functional design artifacts to a Sonnet sub-agent; the main session reviews the result."
+
+**Context**: Functional Design unit 1.
+
+---
+
+## Functional Design - Unit 1 Review and Approval Prompt
+
+**Timestamp**: 2026-10-31T14:15:01Z
+
+**User Input**: "(none: sub-agent report and review by the main session)"
+
+**AI Response**: "Reviewed the artifacts and verified in code: Chakra's ssr false behaviour, document.hidden in useHeroSlider, the hostname default in UmamiAnalytics, the e-mail assembly. Corrected requirements (FR-PR-05 wording, NFR-PR-SEC-02), the execution plan and application design coverage, and components.md. Added BR-MEA-05 (the gate also shows an indicative measurement with Reveal visible, because unit 1 alone understates the gain) and preview server arguments in BR-SRV-08. Decided: all reviews in the HTML with the others visually hidden (BR-LZY-02), revisit at the gate; the bare footer Contact title is hidden without JavaScript in unit 2. Asked for approval."
+
+**Context**: Functional Design unit 1. Awaiting approval. Compliance: PBT-01 compliant; security rules as in application design.
+
+---
+
+## Functional Design - Unit 1 Approval
+
+**Timestamp**: 2026-10-31T14:15:01Z
+
+**User Input**: "ga verder naar code generation"
+
+**AI Response**: "Functional design of unit 1 approved. Started Code Generation Part 1 (planning) for unit 1."
+
+**Context**: Functional Design unit 1 approved.
+
+---
+
+## Code Generation - Unit 1 Plan Approval Prompt
+
+**Timestamp**: 2026-10-31T14:15:01Z
+
+**User Input**: "(none: plan written by a Sonnet sub-agent, reviewed by the main session)"
+
+**AI Response**: "Reviewed construction/plans/start-migration-code-generation-plan.md: 34 steps in 7 batches. Decided the open Lighthouse point: if Lighthouse refuses a 404-status document, notFoundPath becomes /404.html. Asked for approval of the plan and for permission to make local commits on feature/prerendering during this unit."
+
+**Context**: Code Generation Part 1, unit 1. Awaiting approval.
+
+---
+
+## Code Generation - Unit 1 Plan Approval
+
+**Timestamp**: 2026-10-31T14:15:01Z
+
+**User Input**: "approve plan"
+
+**AI Response**: "Plan approved. The commit question was not answered, so no commits are made until the owner says so. Started batch B0 with a Haiku sub-agent."
+
+**Context**: Code Generation Part 2, unit 1.
+
+---
+
+## Commit and Push Permission
+
+**Timestamp**: 2026-10-31T14:15:01Z
+
+**User Input**: "ja je mag committen en pushen"
+
+**AI Response**: "Recorded: commits and pushes on feature/prerendering are allowed for this feature. A pull request and merge are not part of this permission. The first commit waits until the baseline measurement has finished."
+
+**Context**: Code Generation Part 2, unit 1. Permission ends when this feature ends.
+
+---
diff --git a/aidlc-docs/features/prerendering/construction/plans/start-migration-code-generation-plan.md b/aidlc-docs/features/prerendering/construction/plans/start-migration-code-generation-plan.md
new file mode 100644
index 0000000..e5b07d4
--- /dev/null
+++ b/aidlc-docs/features/prerendering/construction/plans/start-migration-code-generation-plan.md
@@ -0,0 +1,514 @@
+# Code Generation Plan - Unit 1: Start migration and script step
+
+Feature: prerendering. Unit: 1 "start-migration". This plan is the single source of truth for Code Generation (Part 2). Execute the steps in order, mark each checkbox `[x]` as soon as its "Done when" is met, and do not deviate from the plan.
+
+## 0. Context an executor needs
+
+### 0.1 What is built
+
+React 19 + Vite + TanStack Router + Chakra UI v3 SPA in `web/` moves to TanStack Start static prerendering. Every page is written as an HTML file; a post-build step moves Start's inline scripts into files so the strict CSP (`script-src 'self'` + Umami) stays unchanged. Unit 1 covers: FR-PR-01 to 08, 19, 20, 22; the catch-all route part of FR-PR-14 and 15; NFR-PR-P-03, P-04, S-02, SEC-01 to 04, Q-01 to 05.
+
+Out of scope (do not build, do not "prepare"): `Reveal` behaviour (the only allowed `Reveal` change is the temporary, never committed one in Step 34), `DeferredImage` no-JavaScript image, `NoScriptNav`, photo preload, nginx/IIS/`serverConfig.ts`/`deploy/`, Lighthouse targets in `lighthouserc*.cjs` (Step 24 may change only `notFoundPath`), upload order in the CI deploy jobs.
+
+There are no user stories; the unit is traced to requirements. Dependencies on other units: none. Unit 2 and 3 depend on this unit (what it must leave: business-rules.md ยง 3).
+
+### 0.2 Files to read (design, all under `aidlc-docs/features/prerendering/`)
+
+1. `construction/start-migration/functional-design/business-rules.md` (rules BR-xxx, ยง 3 end state, ยง 4 verification points V1 to V18). Rule ids in this plan refer to it.
+2. `construction/start-migration/functional-design/business-logic-model.md` (algorithms, properties P1 to P17).
+3. `construction/start-migration/functional-design/domain-entities.md` (entities, hydration inventory).
+4. `construction/start-migration/functional-design/frontend-components.md` (per-component contract, test list).
+5. `inception/application-design/` (decisions D1 to D13, spike evidence), `inception/requirements/requirements.md`.
+
+Read 1 to 4 completely before the first step of your batch.
+
+### 0.3 Locations and commands
+
+- Worktree (work only here): `K:\Development\SlpSoftware\Projects\AndreaSlopFotografie-prerendering`. Application code under `web/`, CI under `.gitea/workflows/`, documentation under `aidlc-docs/`. Never put application code in `aidlc-docs/`.
+- Run commands from `web/`. Package manager: pnpm (version from `packageManager`). Scripts: `pnpm lint`, `pnpm format:check` (fix with `pnpm exec prettier --write `), `pnpm test` (vitest with coverage and thresholds), `pnpm build`, `pnpm audit:deps`.
+- Targeted tests while working: `pnpm exec vitest run ` (no coverage). Full suite only at checkpoints.
+- Shell is Git Bash on Windows (also PowerShell). Use forward slashes in bash. Use plain `rm`/`cp`, never `git rm`/`git mv`.
+- Verification outcomes V1 to V18 are recorded in ONE file: `aidlc-docs/features/prerendering/construction/start-migration/code/verification-log.md` (created in Step 4: a table with columns V#, Point, Step, Outcome, Evidence, Status OK/BLOCKED/DEVIATION). Update the row in the step that settles it.
+- Reports and summaries are markdown only, in `aidlc-docs/features/prerendering/construction/start-migration/code/`.
+
+### 0.4 Rules for every executor
+
+1. **No git write commands** (`add`, `commit`, `push`, `stash`, `reset`, `checkout --`, `rm`, `mv`, branch operations). `git status`, `git diff`, `git log`, `git rev-parse` are allowed. The main session commits, only when the owner approved. Never edit `aidlc-docs/features/prerendering/audit.md` or `aidlc-state.md`; the main session does.
+2. **Do not install anything except in Steps 1 and 4** (`pnpm install`, `pnpm add`). Do not edit `pnpm-lock.yaml` by hand.
+3. **STOP rule.** If an unknown (V point) fails, a design rule cannot be implemented as written, a step's "Done when" cannot be reached, or a fix would change a design decision (any BR rule, any decision D1 to D13): stop at once. Write the finding in the verification log (Status BLOCKED or DEVIATION, with the exact error output and what you tried), leave the tree in a state where `pnpm exec tsc --noEmit` still runs (revert only your own unfinished edits of that step), do not continue with later steps, and return a report to the main session naming the step, the V point or rule, the evidence and the options you see. Never improvise around a design decision, never weaken a check, never delete or skip a test to get green.
+4. **Match the surrounding code.** Open the neighbouring files first and copy their idiom: 4-space indentation, single quotes, trailing commas (Prettier config in `web/.prettierrc`), `@/` alias in `src/` but relative imports with explicit `.ts` extension in `config/` (config files run under Node type stripping: no path aliases, no enums, no parameter properties, `import type` for types, `erasableSyntaxOnly`). Comments explain why, not what; density like the neighbours. Language of new comments, test titles and messages follows the neighbouring files: `config/*` and `src/lib` tests and the pages' older code are partly Dutch; hooks, `lib` implementations and newer components are English. When a file has Dutch comments, write Dutch; when its neighbours are English, write English.
+5. **Existing tests stay valid.** Change an existing test only where BR-TST-02 says behaviour changed, and say so in the step's record.
+6. **Automation-friendly code.** Every new interactive element gets a stable `data-testid` named `{component}-{role}` like the existing ones (`footer-email-link`, `contact-gate-mail`). Placeholders are not interactive but get a testid as listed in the steps.
+7. **Coverage.** Thresholds are 100% for `src/lib/**`, `src/seo.ts`, `src/sitemap.ts`; every new or changed function and branch in `src/lib` needs tests in the same batch.
+8. **Property-based tests** (fast-check, already a dependency): use the global seed from `config/testSeed.ts` (never set a `seed` yourself, never disable shrinking), put domain generators in shared files under `src/test/` (reuse `src/test/arbitraries.ts`: `validEmail`, `anyEmail`, `routePath`, `pathSegment`, `knownRoutePath` and others; new generators go in the new files named in the steps, not in `arbitraries.ts`), label each property test with its category in the title like the existing ones (`(round-trip)`, `(invariant)`, `(idempotent)`, `(oracle)`), and keep an example-based test next to it.
+9. **Concurrent batches** (see ยง 2): while batches run in parallel, run only targeted `vitest run `, never `pnpm build`, `pnpm test`, `pnpm install` or `pnpm add`, and only touch the files your batch owns.
+10. Mark the step `[x]` in this file when done and add one line under "Record" if the step asks for it. Keep the tree compiling after each step.
+
+## 1. Checkpoints
+
+| CP | After | State required |
+|---|---|---|
+| CP0 | Step 3 | `pnpm test` green (the unchanged old tests), `pnpm exec tsc --noEmit` clean |
+| CP1 | Step 5 | `pnpm build` green with Start (prerender writes all pages and `404.html`), `pnpm test` green |
+| CP2 | Steps 13, 15 to 23 all done (merge point after the parallel batches) | `pnpm test` green with coverage thresholds, `pnpm lint`, `pnpm exec tsc --noEmit`, `pnpm build` green (without the runner in `build` yet) |
+| CP3 | Step 24 | `pnpm build` green including the runner; the runner reports no violation on the real output |
+| CP4 | Step 28 | `pnpm lint`, `pnpm format:check`, `pnpm test`, `pnpm build`, `pnpm e2e`, `pnpm audit:deps` all green |
+| CP5 | Step 31 | Step 13.5 complete verification green |
+
+## 2. Batches, executors and parallelism
+
+One sub-agent takes one batch. Haiku (H) does mechanical work, running checks, measurements and log keeping; Sonnet (S) does code, tests and documents that need judgement. The executor per step is repeated in the step.
+
+| Batch | Steps | Executor | Parallel with | Files owned (disjoint from the parallel batches) |
+|---|---|---|---|---|
+| B0 Setup and baseline | 1, 2 | H | none (exclusive: port 4173 and CPU) | none in the repo |
+| B1 Early proof | 3 to 6 | S | none (sequential; risky unknowns first) | `vite.config.ts`, `package.json`, `config/sitemapPlugin.ts`, `src/router.tsx`, `src/client.tsx`, `src/routes/__root.tsx`, `src/routes/$.tsx`, `src/test/renderApp.tsx`, the hooks of Step 3, `UmamiAnalytics`, `NavigationBar` (ssr only), `ContactSection`, `TestimonialCarousel` |
+| B2 Script step | 7 to 13 | S | B3, B4 | `config/pageFiles*`, `config/inlineScripts*`, `config/externalizeInlineScripts*`, `src/test/htmlArbitraries.ts` |
+| B3 Hydration safety | 14 to 21 | S | B2, B4 | `src/**` except the B1 files and `src/test/htmlArbitraries.ts` and `src/test/requestArbitraries.ts` |
+| B4 Preview server | 22, 23 | S | B2, B3 | `config/previewServer*`, `src/test/requestArbitraries.ts` |
+| B5 Integration | 24 to 28 | H for 24 and 28, S for 25 to 27 | none (after CP2) | `package.json`, `tsconfig.json`, `eslint.config.js`, `.gitignore`, `vitest.e2e.config.ts`, `vite.config.ts` (test exclude only), `e2e/**`, `.gitea/workflows/continuous_integration.yaml` |
+| B6 Finish | 29 to 34 | H for 30, 31, 34 runs; S for 29, 32, 33, 34 report | none (34 is exclusive: port 4173 and CPU) | `aidlc-docs/**`, comments |
+
+B3 starts with Step 14 (needs nothing from B2 or B4) and may run its sub-steps sequentially. B2, B3 and B4 may run at the same time because their files are disjoint. If you run them one after another, the order B2, B4, B3 is fine. Step 24 and all of B5 wait for CP2.
+
+## 3. Traceability
+
+### 3.1 Properties (PBT-01) to steps
+
+| Property | Function | Test step |
+|---|---|---|
+| P1 to P8 | `externalizeInlineScripts`, `findExecutableInlineScripts` | 9 |
+| P9 | `externalizeInlineScripts` (split and join) | 9 |
+| P10 | `pageFile` and `pagePath` | 10 |
+| P11, P12 | `planExternalization` | 12 |
+| P13 | address scan helper | 12 |
+| P14, P15 | `contactChannels`, `isEmailAddressValid` | 15 |
+| P16, P17 | `resolveRequest` | 23 |
+
+PBT-02 (round-trip): P3, P10. PBT-03 (invariant): P1, P2, P5, P6, P8, P14, P16. PBT-04 (idempotence): P4, P11. PBT-05 (oracle): P7, P12, P13, P15, P17. PBT-06 (stateful): N/A, no stateful logic in this unit. PBT-07 (generators): domain generators in `src/test/htmlArbitraries.ts` and `src/test/requestArbitraries.ts`, reuse of `arbitraries.ts`. PBT-08: global seed, shrinking left on. PBT-10: each property has example-based tests next to it. P9 is the split-and-join variant of PBT-03/05.
+
+### 3.2 Verification points to steps
+
+| V | Settled in step | Recorded in |
+|---|---|---|
+| V1 client entry | 4 | verification log |
+| V2 `shellComponent` in jsdom | 5 | verification log |
+| V3 inline scripts per real page | 4 (first look), 13 (final list) | verification log |
+| V4 minimum moved scripts | 13 | verification log |
+| V5 `index.html`, crawling | 4 | verification log |
+| V6 code splitting, unused router plugin | 4, 30 | verification log |
+| V7 sitemap environment | 4 | verification log |
+| V8 lazy `ContactForm` in HTML and hydration | 27 | verification log |
+| V9 testimonials in HTML, hidden slides | 21, 27 | verification log |
+| V10 placeholder sizes, CLS below 0.01 | 17, 34 | verification log, measurement report |
+| V11 one title, one noindex meta | 4 (normal pages), 27 (`404.html`) | verification log |
+| V12 404 hydration with real shell | 27 | verification log |
+| V13 timestamps and build paths | 4, 13 | verification log |
+| V14 focus on first load, tidy navigation | 27 | verification log |
+| V15 Emotion/Chakra flicker | 4 (styles in HTML), 27 (screenshots) | verification log |
+| V16 `Intl` price text | 27 | verification log |
+| V17 no `on*=` or `javascript:` | 13, 27 | verification log |
+| V18 CI artifact layout | 28 | verification log |
+
+### 3.3 Requirements to steps
+
+| Requirement | Steps |
+|---|---|
+| FR-PR-01 to 04 | 4, 7, 11, 13, 24, 27 |
+| FR-PR-05 to 07 | 3, 16, 17, 18, 19 to 21, 27 |
+| FR-PR-08 | 3, 4, 27 |
+| FR-PR-19, 20 | 8, 9, 11, 12, 13, 24 |
+| FR-PR-22 | 14, 15, 17, 21, 11, 27 |
+| FR-PR-14, 15 (route part) | 4, 16, 20, 27 |
+| NFR-PR-P-03, P-04 | 2, 34 |
+| NFR-PR-S-02 | 27 |
+| NFR-PR-SEC-01 to 04 | 4, 11, 22, 27, 30 |
+| NFR-PR-Q-01 to 05 | 1, 5, 9 to 12, 15, 19 to 21, 23, 25 to 28, 29, 31 to 33 |
+
+---
+
+## Part A: Setup and baseline (batch B0, Haiku, exclusive)
+
+### Step 1: Install and confirm a green baseline [x]
+
+- Executor: Haiku.
+- Implements: NFR-PR-Q-01 (baseline), setup.
+- Do:
+ 1. In `web/`: `pnpm install --frozen-lockfile` (the worktree has no `node_modules`; `postinstall` runs `chakra typegen`).
+ 2. Run `pnpm lint`, `pnpm format:check`, `pnpm test`, `pnpm build`, in that order. Note the number of test files and tests passed and the fast-check seed line.
+ 3. Run `git rev-parse HEAD` and `git status --short`.
+- Done when: all four commands succeed on the untouched tree. If any fails, STOP (the baseline must be green before changes) and report the output.
+- Record: create `aidlc-docs/features/prerendering/construction/start-migration/code/baseline-checks.md` with the commit hash, the date, Node and pnpm versions, test counts, seed, and the `git status` output (the main session needs the pre-change status, including the untracked `web/.tanstack/`).
+
+### Step 2: Baseline measurement (BR-MEA-01) [x]
+
+- Record (2026-10-31): `code/measurement-baseline.md`; the summary script is in the scratch folder `summarize-lhr.mjs` (path in the report). Mobile and desktop both ran with no page errors (about 16 min for both).
+
+- Executor: Haiku. Exclusive: nothing else may run during this step.
+- Implements: BR-MEA-01; NFR-PR-P-03.
+- Preconditions: Step 1 done; `web/dist` is the master build from Step 1. **Port 4173 must be free** (`Get-NetTCPConnection -LocalPort 4173` in PowerShell must return nothing) because Lighthouse CI starts `pnpm preview --port 4173 --strictPort` itself. **No CPU-heavy work may run during the measurement**: no other build, test run, install, editor indexing job or other sub-agent. If the machine is busy, wait. Use the same machine, power plan and Node version for Step 34.
+- Do (all in `web/`; use a scratch folder outside the repository, for example `$env:TEMP\prerendering-measure`, for raw results and the helper script; neither is committed):
+ 1. Delete `.lighthouseci` and `lighthouse-reports` if present.
+ 2. Mobile: `pnpm exec lhci collect --config=lighthouserc.cjs --numberOfRuns=3`. Move `.lighthouseci` to `/baseline/mobile`.
+ 3. Desktop: `pnpm exec lhci collect --config=lighthouserc.desktop.cjs --numberOfRuns=3`. Move `.lighthouseci` to `/baseline/desktop`. (`collect` does not assert, so existing targets do not matter. The URL list includes `/bestaat-niet`, which master answers with 200 through the SPA fallback; keep it.)
+ 4. Write a small Node script in the scratch folder that reads every `lhr-*.json` of a folder and prints, per URL, the median over the three runs of: `categories.performance.score`, FCP, LCP, TBT (`audits.*.numericValue`), CLS, and the sum of `transferSize` of the `network-requests` items with `resourceType` `Script`. It takes the folder as an argument.
+ 5. Compute gzip sizes with Node `zlib.gzipSync` of: every file referenced by `` (BR-SCR-06). Parse attributes with quote awareness; compare tag and attribute names case-insensitively. A header comment explains why this step exists (NFR-PR-Q-05, BR-BLD-12): the strict `script-src 'self'` blocks Start's inline scripts.
+- Done when: `pnpm exec tsc --noEmit` clean; a quick manual call on the worked-example table of business-logic-model.md ยง 3.1 gives the listed outputs (the real tests come in Step 9).
+
+### Step 9: Tests for `inlineScripts` (P1 to P9) [ ]
+
+- Executor: Sonnet.
+- Implements: NFR-PR-Q-02; PBT-02 to 05, 07, 08, 10; P1 to P9.
+- Files: `web/src/test/htmlArbitraries.ts` (create), `web/config/inlineScripts.test.ts` (create).
+- Do:
+ 1. `htmlArbitraries.ts`: generators for HTML pieces with a model of what each is: executable inline scripts (classic and module, varied attributes, bodies without `` inside a quoted attribute, uppercase tag names, duplicate bodies. Property tests with titles carrying the category: P1 (invariant), P2 (invariant), P3 (round-trip), P4 (idempotent), P5 (invariant), P6 (invariant), P7 (oracle, `findExecutableInlineScripts` against the model), P8 (invariant), P9 (split and join).
+- Done when: `pnpm exec vitest run config/inlineScripts.test.ts` passes; the shrunk counterexample and seed would be printed on failure (do not catch or disable).
+
+### Step 10: Tests for `pageFiles` (P10) [ ]
+
+- Executor: Sonnet.
+- Implements: PBT-02, 10; P10.
+- Files: `web/config/pageFiles.test.ts` (create).
+- Do: examples for `/`, `/over-mij`, `/soorten-fotoshoots/newborn`, `404.html`, a non-page file; property (round-trip): `pagePath(pageFile(p)) === p` for every key of `sitePages` and for generated route-like paths (`routePath` from `arbitraries.ts`); invariant: the file never starts with `/` and ends with `.html`.
+- Done when: `pnpm exec vitest run config/pageFiles.test.ts` passes.
+
+### Step 11: Runner `config/externalizeInlineScripts.ts` [ ]
+
+- Executor: Sonnet.
+- Implements: BR-SCR-12 to 21, BR-MAIL-10, BR-SEC-02, 03, BR-BLD-04, 09 (check part); FR-PR-03, 19, 20, 22; NFR-PR-SEC-03, 04.
+- Do: create the module with
+ - `planExternalization(files, context)` (pure; shapes in domain-entities.md: `files` is a map of relative path to content for all text files under the client directory; `context` has the expected pages, the address or `null`, the sitemap text, the root paths) returning `{ writes, violations }`. It applies `externalizeInlineScripts` to every `.html`, then all checks: NO_HTML, PAGE_MISSING, NOT_FOUND_PAGE_MISSING, UNEXPECTED_HTML, NO_SCRIPTS_MOVED (final HTML references at least one `/assets/inline-<12 hex>.js`, so running twice is not an error), EXECUTABLE_REMAINS, COLLISION (an existing `assets/inline-.js` with other content), UNSUPPORTED_SCRIPT, UNTERMINATED_SCRIPT, EMAIL_IN_OUTPUT (all listed encodings, case-insensitive, in every text file including moved bodies; export the pure scan helper `containsAddress(text, address)` for P13), SITEMAP_MISSING, SITEMAP_DIFFERS, SOURCE_MAP_PRESENT, BUILD_PATH_LEAK (both slash styles of the root path). Messages `: : `; never print script bodies or the address (BR-SCR-21).
+ - `externalizeOutput(clientDir)` that reads the directory (`.html`, `.js`, `.css`, `.xml`, `.txt`, `.json`, `.webmanifest`, and detects `.map`), builds the context (`pageFile` of every `sitePages` key, `emailAddress(siteContent.email)`, `sitemapXml(pageList(sitePages), siteUrl)`, `path.resolve(clientDir, '../..')`), calls the plan, and on violations prints them all, sets exit code 1 and writes nothing; otherwise writes script files first, then the changed HTML, then prints one summary line (pages checked, scripts moved, files written).
+ - A guard so that importing the module for tests does not run it, and the CLI entry runs it for `dist/client` (default) with an optional directory argument.
+ Import `sitePages`, `siteContent`, `emailAddress`, `sitemapXml`, `seo` constants with relative `.ts` paths. A header comment explains why the step exists (BR-BLD-12).
+- Done when: `pnpm exec tsc --noEmit` clean; running `node config/externalizeInlineScripts.ts` on the Step 4 output prints violations (expected at this point: EMAIL_IN_OUTPUT until Step 17) and writes nothing.
+
+### Step 12: Tests for the runner core (P11 to P13) [ ]
+
+- Executor: Sonnet.
+- Implements: NFR-PR-Q-02; PBT-04, 05, 07, 08, 10; P11 to P13.
+- Files: `web/config/externalizeInlineScripts.test.ts` (create); generators for file maps may extend `src/test/htmlArbitraries.ts` (owned by B2).
+- Do: example-based test for each violation code and for the success path (including a second run being a no-op and a `404.html` present); use `anySiteContent`/`validEmail` from `arbitraries.ts` for addresses; a temp-directory test for `externalizeOutput` (writes script files first, writes nothing on violation, exit code via a returned or thrown result you can assert). Properties: P11 (idempotent: apply the plan's writes to the file map, plan again: no writes, no violations), P12 (oracle: violations equal a simple model), P13 (oracle for `containsAddress` with all encodings and random insertion; clean text never flagged).
+- Done when: `pnpm exec vitest run config/externalizeInlineScripts.test.ts` passes.
+
+### Step 13: Run the script step on the real output (V3, V4, V13, V17) [ ]
+
+- Executor: Sonnet.
+- Implements: FR-PR-19, 20; BR-SCR-17; V3, V4, V13, V17.
+- Preconditions: Steps 8 and 11 done. Because B3 and B4 may still be running, do not run `pnpm build` here; use the `dist/client` from Step 4 (or copy it to a scratch folder and run the runner on the copy: `node config/externalizeInlineScripts.ts `).
+- Do: run the runner on the copy. Expected violations: only EMAIL_IN_OUTPUT. Any other violation (for example UNSUPPORTED_SCRIPT because Start emits `async` or ` vb["vite build with Start: client and server bundles"]
+ vb --> pre["Start prerender: one HTML file per page and 404.html"]
+ pre --> plan["Runner reads dist/client and plans in memory"]
+ plan --> chk{"Any violation?"}
+ chk -->|"yes"| stop["Print all violations, exit 1, write nothing"]
+ chk -->|"no"| wr["Write inline-hash.js files, then the changed HTML"]
+ wr --> out["dist/client is the deployable output"]
+ pre -.-> srv["dist/server: build only, never deployed"]
+ classDef build fill:#63b3ed,stroke:#2b6cb0,stroke-width:1px,color:#000;
+ classDef check fill:#f6e05e,stroke:#c05621,stroke-width:1px,color:#000;
+ classDef output fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000;
+ classDef excluded fill:#e2e8f0,stroke:#4a5568,stroke-width:1px,color:#000;
+ class tsc,vb,pre,plan,wr build;
+ class chk,stop check;
+ class out output;
+ class srv excluded;
+```
+
+Text alternative: after type checking and the Start build, the runner plans the rewrite in memory, stops on any violation without writing, and otherwise writes the moved scripts and HTML into dist/client; dist/server is never deployed.
+
+The pages are `Object.keys(sitePages)` plus `/404` rendered to `404.html`. File names follow `pageFile(path)`: `/` gives `index.html`, `/x` gives `x.html`.
+
+## 2. Page lifetime: prerender, hydrating render, hydrated
+
+```mermaid
+sequenceDiagram
+ box rgba(99,179,237,0.4) Build machine
+ participant S as Start prerender
+ end
+ box rgba(246,224,94,0.4) Browser
+ participant B as First browser render
+ participant H as After hydration
+ end
+ S->>S: Render with search none, hydrated false, defaults for media and load state
+ S-->>B: HTML with moved scripts
+ B->>B: Hydrate with the same defaults, hydrated false
+ B->>H: useSyncExternalStore and effects run
+ H->>H: Apply search, real media values, year, e-mail address, observers
+```
+
+Text alternative: the build and the first browser render use the same defaults, and only after hydration are the real search, media values, year and e-mail address applied.
+
+Browser-dependent values and their first-render contract are listed in [domain-entities.md ยง 3](domain-entities.md). The principle is BR-HYD-01: the first browser render equals the HTML.
+
+Hooks that read the browser use the pattern of BR-HYD-03, `useSyncExternalStore(subscribe, clientSnapshot, serverSnapshot)`, with the server snapshot equal to what the HTML shows. This gives the HTML value while hydrating and the real value at once for components that mount later (client navigation, tests).
+
+| Hook | Server and hydrating render | After hydration |
+|---|---|---|
+| `useHydrated` | `false` | `true` |
+| `usePageLoaded` | `false` | `document.readyState === 'complete'`, then the `load` event |
+| `useInView` | `inView = skip` | `skip`, or observed, or `true` without `IntersectionObserver` |
+| `useHeroSlider.hidden` | `false` | `document.hidden`, `visibilitychange` |
+| `useMediaQuery` (Chakra, default `ssr`) | `false` per query | real matches, set in Chakra's effect |
+| `useBreakpointValue` (Chakra, default `ssr`) | value of key `base` | value of the real breakpoint |
+
+## 3. Script step
+
+### 3.1 Scanner and classification
+
+The scanner (BR-SCR-02) walks the HTML once and yields script elements with their start-tag attribute text, body and byte range. Comments, `style`, `textarea`, `title`, `noscript`, `xmp`, `iframe`, `noembed`, `noframes` bodies and attribute values are skipped, so their text never matches. The classification is flowchart 1.1 of the business rules.
+
+`externalizeInlineScripts(html)`:
+
+1. Scan. Throw UNTERMINATED_SCRIPT for a script without end tag.
+2. For each executable script, check the unsupported forms (BR-SCR-05); throw UNSUPPORTED_SCRIPT on a hit.
+3. Compute `hash` (BR-SCR-07) and the file name `inline-.js`; add `{ fileName, body }` to `moved` once per file name.
+4. Build the output by copying every byte outside the replaced ranges and writing `` for each replaced one.
+
+`findExecutableInlineScripts(html)` runs steps 1 and the classification only and returns the bodies in document order.
+
+Worked example (shape only; the real bodies are Start's):
+
+| Input fragment | Output fragment | `moved` |
+|---|---|---|
+| `` | `` | one entry for A |
+| `` | unchanged (external) | none |
+| `` | `` | one entry |
+| `` | unchanged (data) | none |
+| `` | unchanged (skipped) | none |
+| `` | unchanged (comment) | none |
+
+### 3.2 Runner
+
+```mermaid
+graph TD
+ r1["Read all .html under clientDir"] --> r2["Compute expected set: pageFile of each sitePages path, plus 404.html"]
+ r2 --> r3["Per file: externalize, then find on the result"]
+ r3 --> r4["Scan text files: e-mail address, source maps, build paths"]
+ r4 --> r5["Check sitemap.xml equals sitemapXml of the register"]
+ r5 --> r6{"Violations?"}
+ r6 -->|"yes"| r7["Print file, code, detail for each; exit 1"]
+ r6 -->|"no"| r8["Write script files, then HTML, print one summary line"]
+ classDef step fill:#63b3ed,stroke:#2b6cb0,stroke-width:1px,color:#000;
+ classDef decision fill:#f6e05e,stroke:#c05621,stroke-width:1px,color:#000;
+ classDef done fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000;
+ class r1,r2,r3,r4,r5 step;
+ class r6 decision;
+ class r7,r8 done;
+```
+
+Text alternative: the runner computes everything in memory, collects every violation, and writes files only when there are none.
+
+Violation codes (all in business-rules.md, BR-SCR-13 to 21):
+
+| Code | Raised when |
+|---|---|
+| NO_HTML | no `.html` file under `clientDir` |
+| PAGE_MISSING | a `sitePages` path has no `pageFile(path)` |
+| NOT_FOUND_PAGE_MISSING | no `404.html` |
+| UNEXPECTED_HTML | an `.html` file outside the expected set |
+| NO_SCRIPTS_MOVED | a page or `404.html` references no `/assets/inline-<12 hex>.js` after processing |
+| EXECUTABLE_REMAINS | an executable inline script survives the rewrite |
+| UNSUPPORTED_SCRIPT, UNTERMINATED_SCRIPT | forms the rewrite cannot move safely |
+| COLLISION | `inline-.js` exists with other content |
+| EMAIL_IN_OUTPUT | the assembled address occurs in a text file |
+| SITEMAP_MISSING, SITEMAP_DIFFERS | `sitemap.xml` absent or different from the register |
+| SOURCE_MAP_PRESENT, BUILD_PATH_LEAK | a `.map` file, or the repository root path in a text file |
+
+The pure core is `planExternalization(files, context)`, which takes a map of relative path to content plus the expected paths, the address and the sitemap text, and returns `{ writes, violations }`. The runner reads the directory into that map, calls it, and writes the result. This keeps all decisions testable without a file system.
+
+## 4. The e-mail address
+
+```mermaid
+graph TD
+ p["Parts user and domain in siteContent"] --> a{"isEmailAddressValid?"}
+ a -->|"no"| none["No column, item or link: nothing rendered"]
+ a -->|"yes"| h{"hydrated?"}
+ h -->|"no"| ph["Placeholder: empty, aria-hidden, reserved size"]
+ h -->|"yes"| real["emailAddress assembles it: text and mailto link"]
+ ph -->|"after hydration"| real
+ ph --> guard["Build check: assembled address in any text file fails the build"]
+ real -.-> only["Exists only in the browser"]
+ classDef data fill:#fbd38d,stroke:#92400e,stroke-width:1px,color:#000;
+ classDef decision fill:#f6e05e,stroke:#c05621,stroke-width:1px,color:#000;
+ classDef ui fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000;
+ classDef check fill:#e9d5ff,stroke:#6b21a8,stroke-width:1px,color:#000;
+ class p data;
+ class a,h decision;
+ class none,ph,real,only ui;
+ class guard check;
+```
+
+Text alternative: valid parts give an empty placeholder before hydration and the assembled address after it; invalid parts render nothing; a build check keeps the address out of every output file.
+
+Four call sites use it (verified in code): `Footer` (Contact column), `ContactDetails` through `contactChannels` (contact page, twice), `ContactFormGate` (sentence, link, button), `ContactForm` (failed state only). The slot per site is in [frontend-components.md](frontend-components.md).
+
+## 5. Search parameters
+
+| Page | Search | First render (HTML and browser) | After hydration |
+|---|---|---|---|
+| `/` | `pakket` | no package chosen | `ContactPanel` takes the package (`pakket !== seenPakket`), loads the form, `ContactSection` tidies the URL (`navigate` to `/` with hash `contact`, smooth scroll, focus on the heading) |
+| `/contact` | `pakket` | no package chosen | same panel behaviour; the tidy effect `navigate({ to: '/contact', search: {}, replace: true })` runs when `pakket` becomes defined |
+| `/portfolio` | `shoot` | filter "Alles", all photos | filter and photo list follow `shoot`; `onShootChange` keeps `replace` and `resetScroll: false` |
+
+On client navigation to these URLs `hydrated` is already `true`, so the value applies in the first render of the new page, exactly as today.
+
+## 6. Not found
+
+```mermaid
+graph TD
+ u["Unknown URL"] --> srv["Web server returns 404.html with status 404 (unit 3)"]
+ srv --> html["HTML prerendered from /404: shell, title, noindex, one home button"]
+ html --> hy["Hydration: router pathname is the real URL, NotFound ignores it while hydrated is false"]
+ hy --> sec{"Path under /soorten-fotoshoots/?"}
+ sec -->|"yes"| two["Two extra buttons appear"]
+ sec -->|"no"| one["Stays with the home button"]
+ nav["Client navigation to an unknown path"] --> hy2["Catch-all route renders NotFound with hydrated true"]
+ hy2 --> sec
+ classDef host fill:#fbd38d,stroke:#92400e,stroke-width:1px,color:#000;
+ classDef page fill:#63b3ed,stroke:#2b6cb0,stroke-width:1px,color:#000;
+ classDef decision fill:#f6e05e,stroke:#c05621,stroke-width:1px,color:#000;
+ classDef ui fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000;
+ class u,nav page;
+ class srv host;
+ class html,hy,hy2 page;
+ class sec decision;
+ class two,one ui;
+```
+
+Text alternative: an unknown URL gets the prerendered 404 page, and after hydration `NotFound` adds the two shoot buttons under `/soorten-fotoshoots/`; client navigation to an unknown path renders the same route.
+
+## 7. Preview server (unit 1 part)
+
+```mermaid
+graph TD
+ q["Request path"] --> dec{"Decodes once, no NUL, no backslash, no dot-dot segment?"}
+ dec -->|"no"| nf["404.html, status 404"]
+ dec -->|"yes"| root{"Path is /?"}
+ root -->|"yes"| idx["index.html, 200"]
+ root -->|"no"| dot{"Last segment has a dot?"}
+ dot -->|"yes"| fe{"File exists?"}
+ fe -->|"yes"| file["That file, 200"]
+ fe -->|"no"| nf
+ dot -->|"no"| pg{"pageFile exists?"}
+ pg -->|"yes"| page["x.html, 200"]
+ pg -->|"no"| nf
+ classDef decision fill:#f6e05e,stroke:#c05621,stroke-width:1px,color:#000;
+ classDef ok fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000;
+ classDef bad fill:#fbd38d,stroke:#92400e,stroke-width:1px,color:#000;
+ classDef in fill:#63b3ed,stroke:#2b6cb0,stroke-width:1px,color:#000;
+ class dec,root,dot,fe,pg decision;
+ class idx,file,page ok;
+ class nf bad;
+ class q in;
+```
+
+Text alternative: a safe path maps to index.html, an existing file, or its page file with status 200, and everything else, including unsafe paths, gets 404.html with status 404.
+
+Trailing slash and `/404` are final in unit 3 Infrastructure Design (BR-SRV-07).
+
+## 8. Measurement and decision gate
+
+Before the first code change and after unit 1, on the same machine: entry and total JavaScript (gzip), mobile and desktop Lighthouse for every page, plus the moved scripts' count, size and timing (BR-MEA-01 to 03). The owner sees both sets; if any is worse, the owner decides before units 2 and 3 (NFR-PR-P-03).
+
+## 9. Testable Properties (PBT-01)
+
+fast-check properties use the existing seed handling. Generators build HTML from known pieces (executable scripts, external scripts, data blocks, comments and style bodies containing script-like text, plain markup) and keep a model of what each piece is.
+
+| Id | Function | Category | Property |
+|---|---|---|---|
+| P1 | `externalizeInlineScripts` | Invariant | Removing the replaced script elements from the input and the output leaves identical text; everything else is byte-identical (BR-SCR-09) |
+| P2 | `externalizeInlineScripts` | Invariant | The references in the output appear in the same order as the executable scripts in the input (BR-SCR-06) |
+| P3 | `externalizeInlineScripts` | Round-trip | Replacing each moved reference by its body (looked up by file name) restores the input exactly, because attribute text is kept verbatim and only ` src="..."` was added |
+| P4 | `externalizeInlineScripts` | Idempotence | Applying it to its own output returns the same HTML and no moved files (BR-SCR-10) |
+| P5 | `externalizeInlineScripts` | Invariant | Data blocks, external scripts, empty scripts, comments and style bodies appear unchanged in the output |
+| P6 | both | Invariant | `findExecutableInlineScripts` of the output is empty (BR-SCR-11) |
+| P7 | `findExecutableInlineScripts` | Oracle | It returns exactly the bodies of the executable pieces of the generator model, in order, whatever decoys surround them |
+| P8 | `externalizeInlineScripts` | Invariant | The same body gives the same file name; different bodies give different names; names match `inline-[0-9a-f]{12}.js`; `moved` has no duplicate names |
+| P9 | `externalizeInlineScripts` | Commutativity (split and join) | For a list of independent fragments (each a complete element, comment or text), externalizing the concatenation equals concatenating the externalized fragments |
+| P10 | `pageFile` and its inverse | Round-trip | The path recovered from `pageFile(path)` equals `path`, for every `sitePages` path and generated route-like paths; the file never starts with `/` |
+| P11 | `planExternalization` | Idempotence | Applying a plan's writes to the file map and planning again gives no writes and no violations |
+| P12 | `planExternalization` | Oracle | Violations equal a simple model: missing pages, unexpected files, pages without references, address occurrences |
+| P13 | address scan (pure helper) | Oracle | For text built by inserting the address in any listed encoding at random positions, the scan finds it; text without it is never flagged |
+| P14 | `contactChannels` | Invariant | With `assemble` false the serialized result never contains the assembled address, and has the same number of channels as with `assemble` true |
+| P15 | `isEmailAddressValid` and `emailAddress` | Oracle | `isEmailAddressValid(p)` equals `emailAddress(p) !== null` for any parts |
+| P16 | `resolveRequest` | Invariant | For any path (including `..`, `%2e%2e`, `%00`, backslashes, unicode) the returned `file` has no `..` segment, is not absolute and has no backslash; status 404 comes only with `404.html` |
+| P17 | `resolveRequest` | Oracle | Against a small model over a generated set of existing files, `/`, `/x` and `/file.ext` resolve as BR-SRV-02 to 05 say |
+
+Components with no properties:
+
+| Component | Result |
+|---|---|
+| `startPreviewServer` | No PBT properties identified: thin HTTP wrapper around `resolveRequest`; example tests for headers and methods |
+| `externalizeOutput` (file system part) | No PBT properties identified: reading and writing files; its decisions are covered by P11 and P12 |
+| `useHydrated`, `usePageLoaded`, `useInView`, `useHeroSlider`, `useEmailAddress` | No PBT properties identified: React hooks with small state spaces and no pure transformation; example tests per phase (server snapshot, hydrated) |
+| `getRouter`, `client.tsx`, `__root.tsx` shell, `$` route | No PBT properties identified: configuration and wiring; covered by build, e2e and example tests |
+| Display and route components changed for hydration (Section 2 of frontend-components.md) | No PBT properties identified: markup with fixed small inputs; covered by example tests, axe and the e2e hydration checks |
+
+## 10. Requirement coverage
+
+| Requirement | Where |
+|---|---|
+| FR-PR-01 to 04 | BR-BLD-02 to 06, 09; BR-SCR-14 to 16 |
+| FR-PR-05 to 07 | BR-HYD-01 to 21, BR-ENT-06 |
+| FR-PR-08 | BR-MON-01 to 04 |
+| FR-PR-19, 20 | BR-SCR-01 to 23 |
+| FR-PR-22 | BR-MAIL-01 to 11 |
+| FR-PR-14, 15 (route part) | BR-404-01 to 07 |
+| NFR-PR-P-03, P-04 | BR-MEA-01 to 04 |
+| NFR-PR-S-02 | BR-TST-06 |
+| NFR-PR-SEC-01 to 04 | BR-SEC-01 to 06, BR-BLD-11, BR-SRV-06 |
+| NFR-PR-Q-01 to 05 | BR-TST-01 to 07, BR-BLD-07, 12 |
+
+## 11. Security Baseline and PBT compliance (unit 1)
+
+| Rule | Status | Note |
+|---|---|---|
+| SECURITY-04 | Compliant | CSP unchanged (BR-SEC-01); JSON-LD escaping kept (BR-SEC-06) |
+| SECURITY-09 | Compliant | No source maps, build paths or server output in `dist/client` (BR-SEC-02, 03, BLD-01) |
+| SECURITY-10 | Compliant | Lockfile, audit, overrides kept (BR-BLD-11) |
+| SECURITY-11 | Compliant | Path traversal is a tested property (P16) |
+| SECURITY-13 | Compliant | No external scripts added; moved scripts are same-origin files |
+| SECURITY-15 | Compliant | The runner fails closed and writes nothing on a violation (BR-SCR-12) |
+| PBT-01 | Compliant | Section 9 |
+| PBT-09 | Compliant | fast-check already in the project |
diff --git a/aidlc-docs/features/prerendering/construction/start-migration/functional-design/business-rules.md b/aidlc-docs/features/prerendering/construction/start-migration/functional-design/business-rules.md
new file mode 100644
index 0000000..02ec137
--- /dev/null
+++ b/aidlc-docs/features/prerendering/construction/start-migration/functional-design/business-rules.md
@@ -0,0 +1,272 @@
+# Business Rules - Unit 1: Start migration and script step
+
+Rule ids are scoped to this feature (the code comments of earlier features also use `BR-MAIL-01` for the mail subject; here it is the e-mail address protection). "Source" points at a requirement (FR/NFR) or design decision (D1 to D13 in [application-design.md](../../../inception/application-design/application-design.md)). Flows: [business-logic-model.md](business-logic-model.md). Components: [frontend-components.md](frontend-components.md). Data: [domain-entities.md](domain-entities.md).
+
+Groups: BR-BLD build, BR-ENT entry and document, BR-HYD hydration, BR-MAIL e-mail address, BR-404 not found, BR-LZY lazy code, BR-MON Sentry and Umami, BR-SCR script step, BR-SEC output hygiene, BR-SRV preview server, BR-TST tests, BR-MEA measurement.
+
+## 1. Decision flowcharts
+
+### 1.1 Is an inline script moved
+
+```mermaid
+graph TD
+ s["Script element found by the scanner"] --> src{"Has a src attribute?"}
+ src -->|"yes"| keepExt["Leave as is: external script"]
+ src -->|"no"| body{"Body empty after trim?"}
+ body -->|"yes"| keepEmpty["Leave as is: no effect"]
+ body -->|"no"| typ{"type absent, empty, a JavaScript type or module?"}
+ typ -->|"no"| keepData["Leave as is: data block such as ld+json"]
+ typ -->|"yes"| bad{"async or defer on a classic script, body contains comment opener, or relative import in a module?"}
+ bad -->|"yes"| fail["Error UNSUPPORTED_SCRIPT"]
+ bad -->|"no"| move["Replace by external reference, write file"]
+ classDef decision fill:#fbd38d,stroke:#92400e,stroke-width:1px,color:#000;
+ classDef keep fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000;
+ classDef act fill:#63b3ed,stroke:#2b6cb0,stroke-width:1px,color:#000;
+ classDef error fill:#f6e05e,stroke:#c05621,stroke-width:1px,color:#000;
+ class src,body,typ,bad decision;
+ class keepExt,keepEmpty,keepData keep;
+ class s,move act;
+ class fail error;
+```
+
+Text alternative: only scripts without src, with a non-empty body and a JavaScript or module type are moved; data blocks, external and empty scripts stay, and three unsupported forms fail the build.
+
+### 1.2 What a component renders before and after hydration
+
+```mermaid
+graph TD
+ v["Browser-dependent value"] --> kind{"Kind of value"}
+ kind -->|"search, pathname, year, media, visibility, load state"| def["First render uses the server-safe default, same on both sides"]
+ kind -->|"e-mail address"| mail["First render uses an empty placeholder with reserved size"]
+ kind -->|"observer or measurement"| eff["Set in an effect or external store after mount"]
+ def --> after["After hydration the real value replaces the default"]
+ mail --> after
+ eff --> after
+ classDef decision fill:#fbd38d,stroke:#92400e,stroke-width:1px,color:#000;
+ classDef act fill:#63b3ed,stroke:#2b6cb0,stroke-width:1px,color:#000;
+ classDef ok fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000;
+ class kind decision;
+ class v,def,mail,eff act;
+ class after ok;
+```
+
+Text alternative: every browser-dependent value starts from a default that equals the prerendered HTML (an empty placeholder for the e-mail address) and is replaced by the real value after hydration.
+
+## 2. Rules
+
+### BR-BLD: Build and output
+
+| Id | Rule | Source |
+|---|---|---|
+| BR-BLD-01 | `pnpm build` runs `tsc`, `vite build`, then `node config/externalizeInlineScripts.ts`, in that order. A failing step fails the build. The deployable output is `dist/client`; `dist/server` exists only during the build. | FR-PR-17, 19, 20; services.md |
+| BR-BLD-02 | The prerendered pages are every key of `sitePages` plus the catch-all route rendered from path `/404` to file `404.html`. `vite.config.ts` derives the list from `sitePages.ts`; paths are never typed a second time. | FR-PR-01, 03; D1, D5 |
+| BR-BLD-03 | `autoSubfolderIndex` is `false`. File mapping is `pageFile(path)`: `/` gives `index.html`, any other path gives its path without leading slash plus `.html` (`/over-mij` gives `over-mij.html`, `/soorten-fotoshoots/newborn` gives `soorten-fotoshoots/newborn.html`). `pageFile` lives in `config/pageFiles.ts` (pure) and is used by `vite.config.ts`, the runner and the preview server. | FR-PR-16; D1 |
+| BR-BLD-04 | Link crawling must not add pages beyond BR-BLD-02. The runner fails on any other `.html` file (UNEXPECTED_HTML). | FR-PR-03 |
+| BR-BLD-05 | Each page file has exactly one ``, one `description`, one `canonical`, the Open Graph tags and JSON-LD of its route, and no element with `data-fallback`. ``, charset, viewport, `favicon.png` icon and `apple-touch-icon` links move from `index.html` to the root route (`head()` or the shell). `index.html` and `src/main.tsx` are removed. | FR-PR-02 |
+| BR-BLD-06 | `/privacyverklaring` keeps `robots` `noindex` through `pageHead`. `404.html` has `noindex` too. Neither `/404` nor `/privacyverklaring` is in the sitemap. | FR-PR-04, 14 |
+| BR-BLD-07 | The fonts stay imported (`@fontsource/jost` 300, 400, 500; `@fontsource/marcellus` 400) so that their CSS is a same-origin stylesheet link in the HTML. Chakra and Emotion styles are in the HTML (inline `',
+ ],
+ ['commentaar', ''],
+ ['een attribuutwaarde', ''],
+ ])('laat %s ongemoeid', (_, html) => {
+ expect(externalizeInlineScripts(html)).toEqual({ html, moved: [] });
+ });
+
+ it('laat al het andere byte voor byte staan, ook regeleinden', () => {
+ const html =
+ '\r\n\r\n\r\n' +
+ '' +
+ '\r\n\r\n';
+ expect(externalizeInlineScripts(html).html).toBe(
+ html.replace('', referenceOf('', 'go()')),
+ );
+ });
+
+ it('hasht de inhoud zoals geschreven, zonder trimmen', () => {
+ const a = externalizeInlineScripts('');
+ const b = externalizeInlineScripts('');
+ expect(a.moved[0].fileName).not.toBe(b.moved[0].fileName);
+ expect(b.moved[0].body).toBe(' x() ');
+ expect(b.moved[0].fileName).toBe(fileOf(' x() '));
+ });
+
+ it('geeft gelijke inhoud รฉรฉn bestand, op volgorde van eerste voorkomen', () => {
+ const result = externalizeInlineScripts(
+ '',
+ );
+ expect(result.moved.map((m) => m.body)).toEqual(['b()', 'a()']);
+ expect(result.html).toBe(
+ referenceOf('', 'b()') +
+ referenceOf('', 'a()') +
+ referenceOf('', 'b()'),
+ );
+ });
+});
+
+describe('classificatie (BR-SCR-04)', () => {
+ it.each([
+ ' type="text/javascript"',
+ ' type="TEXT/JavaScript"',
+ ' type=" text/javascript "',
+ ' type="application/javascript"',
+ ' type="application/ecmascript"',
+ ' type="application/x-ecmascript"',
+ ' type="application/x-javascript"',
+ ' type="text/javascript1.0"',
+ ' type="text/javascript1.5"',
+ ' type="text/ecmascript"',
+ ' type="text/jscript"',
+ ' type="text/livescript"',
+ ' type="text/x-ecmascript"',
+ ' type="text/x-javascript"',
+ ' type=""',
+ ' type',
+ ' type="module"',
+ ' type="Module"',
+ ' language="vbscript"',
+ ])('verplaatst een script met %s', (attributes) => {
+ const html = ``;
+ expect(externalizeInlineScripts(html).html).toBe(
+ referenceOf(attributes, 'go()'),
+ );
+ expect(findExecutableInlineScripts(html)).toEqual(['go()']);
+ });
+
+ it.each([
+ ' type="application/ld+json"',
+ ' type="application/json"',
+ ' type="importmap"',
+ ' type="speculationrules"',
+ ' type="text/plain"',
+ ' type="text/javascript2.0"',
+ ' type="jscript"',
+ ])('laat een datablok met %s staan', (attributes) => {
+ const html = ``;
+ expect(externalizeInlineScripts(html)).toEqual({ html, moved: [] });
+ expect(findExecutableInlineScripts(html)).toEqual([]);
+ });
+
+ it.each([
+ ['src met waarde', ''],
+ ['src zonder waarde', ''],
+ ['lege src', ''],
+ ['src in hoofdletters', ''],
+ ])('laat een extern script staan: %s', (_, html) => {
+ expect(externalizeInlineScripts(html)).toEqual({ html, moved: [] });
+ expect(findExecutableInlineScripts(html)).toEqual([]);
+ });
+
+ it('laat een leeg script staan, ook met alleen witruimte', () => {
+ const html = '';
+ expect(externalizeInlineScripts(html)).toEqual({ html, moved: [] });
+ expect(findExecutableInlineScripts(html)).toEqual([]);
+ });
+
+ it('leest alleen het eerste type-attribuut, zoals een browser', () => {
+ const html = '';
+ expect(externalizeInlineScripts(html).moved).toEqual([]);
+ });
+});
+
+describe('niet-ondersteunde vormen (BR-SCR-05)', () => {
+ it.each([
+ '',
+ '',
+ '',
+ ])('(a) weigert een klassiek script met async of defer: %s', (html) => {
+ fails(html, 'UNSUPPORTED_SCRIPT');
+ });
+
+ it('(a) staat async op een module-script wel toe', () => {
+ expect(
+ externalizeInlineScripts(
+ '',
+ ).moved,
+ ).toHaveLength(1);
+ });
+
+ it('(b) weigert een commentaaropener in de body', () => {
+ fails('', 'UNSUPPORTED_SCRIPT');
+ });
+
+ it('(b) weigert ook in een module-script', () => {
+ fails('', 'UNSUPPORTED_SCRIPT');
+ });
+
+ it.each([
+ "import a from './x.js';",
+ 'import a from "../x.js";',
+ "import './side.js';",
+ "const m = await import('./x.js');",
+ 'const m = import( "../x.js" );',
+ "export * from './x.js';",
+ "import a from '.';",
+ ])('(c) weigert een module met relatieve import: %s', (body) => {
+ fails(``, 'UNSUPPORTED_SCRIPT');
+ });
+
+ it.each([
+ "import a from '/assets/x.js';",
+ "import a from 'https://cdn.test/x.js';",
+ "import a from 'pakket';",
+ 'const from = 1; const s = "x./y";',
+ ])('(c) staat een module zonder relatieve import toe: %s', (body) => {
+ expect(
+ externalizeInlineScripts(``)
+ .moved,
+ ).toHaveLength(1);
+ });
+
+ it('(c) geldt niet voor een klassiek script', () => {
+ expect(
+ externalizeInlineScripts("").moved,
+ ).toHaveLength(1);
+ });
+
+ it('noemt de regel en de code, nooit de inhoud van het script', () => {
+ const error = fails(
+ '
\n
\n',
+ 'UNSUPPORTED_SCRIPT',
+ );
+ expect(error.message).toContain('regel 3');
+ expect(error.message).not.toContain('geheim');
+ });
+
+ it('controleert alleen scripts die verplaatst zouden worden', () => {
+ const html =
+ '' +
+ '';
+ expect(externalizeInlineScripts(html).moved).toEqual([]);
+ });
+});
+
+describe('scriptgrenzen en scanner (BR-SCR-02, 03)', () => {
+ it('weigert een script zonder eindtag', () => {
+ const error = fails('go() {
+ fails('go()go()', () => {
+ const html = '';
+ expect(findExecutableInlineScripts(html)).toEqual([
+ 'a = ""; b = 1;',
+ ]);
+ expect(findExecutableInlineScripts('')).toEqual([
+ 'a',
+ ]);
+ expect(findExecutableInlineScripts('')).toEqual([
+ 'a',
+ ]);
+ });
+
+ it('neemt een > binnen een aanhalingsteken in een attribuut niet als einde van de tag', () => {
+ const attributes = ' data-x="a>b" data-y=\'c > d\'';
+ const result = externalizeInlineScripts(
+ ``,
+ );
+ expect(result.html).toBe(referenceOf(attributes, 'go()'));
+ });
+
+ it('behoudt een afsluitende / in de tag en leest de naam hoofdletterongevoelig', () => {
+ expect(externalizeInlineScripts('go()').html).toBe(
+ referenceOf(' /', 'go()'),
+ );
+ expect(
+ externalizeInlineScripts('')
+ .html,
+ ).toBe(referenceOf(' TYPE="Module"', 'go()'));
+ });
+
+ it('een ongeldig <-teken is tekst', () => {
+ const html = '
1 < 2
<3>';
+ expect(findExecutableInlineScripts(html)).toEqual(['go()', 'x']);
+ });
+
+ it('slaat tekstelementen over tot hun eindtag, ook zonder eindtag', () => {
+ expect(
+ findExecutableInlineScripts(
+ 'a',
+ ),
+ ).toEqual(['y']);
+ expect(
+ findExecutableInlineScripts('',
+ ),
+ ).toEqual(['y']);
+ });
+
+ it('slaat commentaar over, ook en een niet-afgesloten commentaar', () => {
+ expect(findExecutableInlineScripts('')).toEqual([
+ 'x',
+ ]);
+ expect(findExecutableInlineScripts('')).toEqual(
+ ['x'],
+ );
+ expect(findExecutableInlineScripts(' en zoals in een browser sluiten
+ const closing = html.indexOf('-->', lt + 2);
+ pos = closing === -1 ? length : closing + 3;
+ continue;
+ }
+ if (next === '!' || next === '?' || next === '/') {
+ const closing = html.indexOf('>', lt + 2);
+ pos = closing === -1 ? length : closing + 1;
+ continue;
+ }
+ if (!isLetter(next)) {
+ pos = lt + 1;
+ continue;
+ }
+
+ const tag = readStartTag(html, lt);
+ if (!tag) break;
+ const bodyStart = tag.close + 1;
+
+ if (tag.name === 'script') {
+ scriptEnd.lastIndex = bodyStart;
+ const endTag = scriptEnd.exec(html);
+ let body: string;
+ let end: number;
+ let terminated: boolean;
+ if (!endTag) {
+ body = html.slice(bodyStart);
+ end = length;
+ terminated = false;
+ } else {
+ body = html.slice(bodyStart, endTag.index);
+ const closing = html.indexOf('>', endTag.index);
+ terminated = closing !== -1;
+ end = terminated ? closing + 1 : length;
+ }
+ const { kind, module } = classify(tag.attributes, body);
+ found.push({
+ start: lt,
+ end,
+ attributeText: html.slice(tag.attributeStart, tag.close),
+ body,
+ terminated,
+ kind,
+ module,
+ asyncOrDefer:
+ tag.attributes.has('async') || tag.attributes.has('defer'),
+ });
+ pos = end;
+ continue;
+ }
+
+ if (RAW_TEXT_ELEMENTS.has(tag.name)) {
+ const pattern = endTagPattern(tag.name);
+ pattern.lastIndex = bodyStart;
+ const endTag = pattern.exec(html);
+ pos = endTag ? endTag.index : length;
+ continue;
+ }
+
+ pos = bodyStart;
+ }
+ return found;
+}
+
+// Een relatieve importspecifier ('./x', '../x') zou na het verplaatsen tegen
+// /assets/ oplossen in plaats van tegen de pagina
+const RELATIVE_IMPORT =
+ /\bfrom\s*['"`]\.{1,2}(?:\/|(?=['"`]))|\bimport\s*\(?\s*['"`]\.{1,2}(?:\/|(?=['"`]))/;
+
+function lineOf(html: string, index: number): number {
+ return html.slice(0, index).split('\n').length;
+}
+
+// Vormen die we niet veilig kunnen verplaatsen (BR-SCR-05): liever een
+// mislukte build dan stil ander gedrag als Start zijn uitvoer wijzigt.
+function unsupportedReason(script: ScriptElement): string | null {
+ if (!script.module && script.asyncOrDefer) {
+ return 'async of defer op een klassiek script';
+ }
+ if (script.body.includes('',
+ '',
+ '',
+ '',
+ '',
+ )
+ .map((html) => ({ kind: 'comment' as const, html }));
+
+const rawTextPiece: fc.Arbitrary = fc
+ .constantFrom(
+ '',
+ '',
+ '',
+ 'a ',
+ '',
+ '',
+ '',
+ )
+ .map((html) => ({ kind: 'rawText' as const, html }));
+
+const attributeDecoyPiece: fc.Arbitrary = fc
+ .constantFrom(
+ '
',
+ )
+ .map((html) => ({ kind: 'attributeDecoy' as const, html }));
+
+// Complete markup with no script in it. Text pieces never end in '<', so a
+// piece cannot glue onto the next one.
+const markupPiece: fc.Arbitrary = fc
+ .constantFrom(
+ '',
+ '',
+ '
text
',
+ '
1 < 2 and 3 > 2
',
+ ' ',
+ '',
+ '',
+ 'plain text',
+ '
',
+ )
+ .map((html) => ({ kind: 'markup' as const, html }));
+
+// Everything the step must leave alone, whatever surrounds it
+export const decoyPiece: fc.Arbitrary = fc.oneof(
+ externalPiece,
+ emptyPiece,
+ dataPiece,
+ commentPiece,
+ rawTextPiece,
+ attributeDecoyPiece,
+ markupPiece,
+);
+
+export const htmlPiece: fc.Arbitrary = fc.oneof(
+ { arbitrary: executablePiece, weight: 3 },
+ { arbitrary: decoyPiece, weight: 4 },
+);
+
+const canonicalHtmlPiece: fc.Arbitrary = fc.oneof(
+ { arbitrary: canonicalExecutablePiece, weight: 3 },
+ { arbitrary: decoyPiece, weight: 4 },
+);
+
+const separator = fc.constantFrom('', '\n', ' ');
+
+function modelOf(pieces: fc.Arbitrary): fc.Arbitrary {
+ return fc
+ .tuple(fc.array(pieces, { maxLength: 12 }), separator)
+ .map(([list, join]) => ({
+ html: list.map((piece) => piece.html).join(join),
+ pieces: list,
+ separator: join,
+ }));
+}
+
+// A document and what each part of it is
+export const htmlWithModel: fc.Arbitrary = modelOf(htmlPiece);
+
+// The same, with executable scripts written as ``
+// only, so that putting the moved bodies back restores the input exactly
+export const canonicalHtmlWithModel: fc.Arbitrary =
+ modelOf(canonicalHtmlPiece);
+
+// Independent complete fragments, for split-and-join properties: each one
+// parses the same alone as inside a larger document
+export const htmlFragments: fc.Arbitrary = fc.array(htmlPiece, {
+ maxLength: 10,
+});
+
+// A build output for the runner: which expected pages exist and what is wrong
+// with them, plus files that do not belong. The test turns this into a file
+// map and computes the expected violations from the same description.
+export type BadScript = 'none' | 'unsupported' | 'unterminated';
+
+export interface PageScenario {
+ present: boolean;
+ content: HtmlModel;
+ // Already processed: references a moved script without executable ones
+ reference: boolean;
+ bad: BadScript;
+ // The assembled address sits in the page text
+ leakAddress: boolean;
+}
+
+export interface ExtraFile {
+ name: string;
+ address: boolean;
+ rootPath: boolean;
+}
+
+export interface OutputScenario {
+ // index.html, over-mij.html, soorten-fotoshoots/newborn.html, 404.html
+ pages: PageScenario[];
+ unexpected: string[];
+ extras: ExtraFile[];
+ sourceMap: boolean;
+ sitemap: 'ok' | 'missing' | 'differs';
+}
+
+const pageScenario: fc.Arbitrary = fc.record({
+ present: fc.boolean(),
+ content: htmlWithModel,
+ reference: fc.boolean(),
+ bad: fc.constantFrom(
+ 'none',
+ 'none',
+ 'none',
+ 'unsupported',
+ 'unterminated',
+ ),
+ leakAddress: fc.boolean(),
+});
+
+const extraFile: fc.Arbitrary = fc.record({
+ name: fc.constantFrom(
+ 'assets/app.js',
+ 'assets/app.css',
+ 'robots.txt',
+ 'data.json',
+ 'manifest.webmanifest',
+ 'feed.xml',
+ ),
+ address: fc.boolean(),
+ rootPath: fc.boolean(),
+});
+
+export const outputScenario: fc.Arbitrary = fc.record({
+ pages: fc.tuple(pageScenario, pageScenario, pageScenario, pageScenario),
+ unexpected: fc.uniqueArray(
+ fc.constantFrom(
+ 'extra.html',
+ 'soorten-fotoshoots/index.html',
+ 'a/b.html',
+ ),
+ { maxLength: 2 },
+ ),
+ extras: fc.uniqueArray(extraFile, {
+ selector: (file) => file.name,
+ maxLength: 3,
+ }),
+ sourceMap: fc.boolean(),
+ sitemap: fc.constantFrom('ok', 'ok', 'missing', 'differs'),
+});
--
2.39.5
From 2c2e27e337c7b7fa973b6e3dc7e30c097e1067d8 Mon Sep 17 00:00:00 2001
From: Sluijsens
Date: Sat, 31 Oct 2026 18:17:26 +0100
Subject: [PATCH 04/49] Makes the first render match the prerendered HTML
Search values, the 404 buttons and the footer year now apply after hydration.
The e-mail address stays out of the HTML behind a placeholder, and all review
texts are in the page, so crawlers can read them.
Co-Authored-By: Claude Opus 5.5
---
.../ContactDetails/ContactDetails.test.tsx | 72 +++++++++
.../ContactDetails/ContactDetails.tsx | 99 +++++++-----
.../ContactForm/ContactForm.test.tsx | 19 +++
.../components/ContactForm/ContactForm.tsx | 4 +-
.../ContactForm/ContactFormGate.test.tsx | 76 +++++++++
.../ContactForm/ContactFormGate.tsx | 60 +++++--
web/src/components/Footer/Footer.test.tsx | 97 ++++++++++-
web/src/components/Footer/Footer.tsx | 44 +++--
.../components/Hero/useHeroSlider.test.tsx | 72 +++++++++
.../components/NavigationBar/MobileNav.tsx | 5 +
.../NavigationBar/NavigationBar.test.tsx | 41 +++++
.../NavigationBar/NavigationBar.tsx | 9 +-
.../components/StatusPage/NotFound.test.tsx | 49 ++++++
web/src/components/StatusPage/NotFound.tsx | 6 +-
.../home/Testimonials/Testimonials.test.tsx | 62 ++++++++
.../home/Testimonials/Testimonials.tsx | 16 +-
web/src/hooks/useEmailAddress.test.tsx | 72 +++++++++
web/src/hooks/useEmailAddress.ts | 18 +++
web/src/hooks/useHydrated.test.tsx | 35 ++++
web/src/hooks/useInView.test.tsx | 82 ++++++++++
web/src/hooks/useInView.ts | 3 +
web/src/hooks/usePageLoaded.test.tsx | 45 +++++-
web/src/hooks/useReveal.test.tsx | 33 ++++
web/src/lib/contactChannels.test.ts | 150 ++++++++++++------
web/src/lib/contactChannels.ts | 35 ++--
web/src/lib/emailAddress.test.ts | 32 +++-
web/src/lib/emailAddress.ts | 13 +-
web/src/routes/contact.tsx | 6 +-
web/src/routes/hydration.test.tsx | 73 +++++++++
web/src/routes/index.tsx | 6 +-
web/src/routes/portfolio.tsx | 6 +-
web/src/test/hydrate.tsx | 130 +++++++++++++++
32 files changed, 1322 insertions(+), 148 deletions(-)
create mode 100644 web/src/components/StatusPage/NotFound.test.tsx
create mode 100644 web/src/hooks/useEmailAddress.test.tsx
create mode 100644 web/src/hooks/useEmailAddress.ts
create mode 100644 web/src/hooks/useHydrated.test.tsx
create mode 100644 web/src/hooks/useInView.test.tsx
create mode 100644 web/src/routes/hydration.test.tsx
create mode 100644 web/src/test/hydrate.tsx
diff --git a/web/src/components/ContactDetails/ContactDetails.test.tsx b/web/src/components/ContactDetails/ContactDetails.test.tsx
index 8b0cb8b..4417089 100644
--- a/web/src/components/ContactDetails/ContactDetails.test.tsx
+++ b/web/src/components/ContactDetails/ContactDetails.test.tsx
@@ -1,7 +1,10 @@
import { screen, within } from '@testing-library/react';
+import fc from 'fast-check';
import { describe, expect, it } from 'vitest';
import siteContent from '@/content/siteContent';
+import { validEmail } from '@/test/arbitraries';
import { axeResults } from '@/test/axe';
+import { hydratePage, serverHtml } from '@/test/hydrate';
import { renderWithProviders } from '@/test/renderWithProviders';
import ContactDetails from './ContactDetails';
@@ -104,3 +107,72 @@ describe('ContactDetails', () => {
expect(await axeResults(container)).toHaveNoViolations();
});
});
+
+// The address is only there after hydrating; before, the first item is an
+// empty placeholder of the same height (BR-MAIL-04, BR-MAIL-07)
+describe('ContactDetails in the prerendered HTML', () => {
+ it('holds a placeholder first and the socials, but no address', async () => {
+ const html = await serverHtml(card());
+ expect(html.toLowerCase()).not.toContain('info@andreaslop.nl');
+ expect(html).not.toContain('mailto:');
+ expect(html).toContain('data-testid="contact-details-email-pending"');
+ expect(html.indexOf('contact-details-email-pending')).toBeLessThan(
+ html.indexOf('contact-details-instagram'),
+ );
+ expect(html).toContain('contact-details-facebook');
+ });
+
+ it('never holds the address, whatever the content (invariant)', async () => {
+ await fc.assert(
+ fc.asyncProperty(validEmail, async (email) => {
+ const html = await serverHtml(card({ email }));
+ expect(html.toLowerCase()).not.toContain(
+ `${email.user}@${email.domain}`.toLowerCase(),
+ );
+ expect(html).not.toContain('mailto:');
+ }),
+ );
+ });
+
+ it('swaps the placeholder for the link after hydrating', async () => {
+ const { errors } = await hydratePage(card());
+ const mail = await screen.findByTestId('contact-details-email');
+ expect(mail).toHaveAttribute(
+ 'href',
+ 'mailto:info@andreaslop.nl?subject=Vraag%20via%20andreaslop.nl',
+ );
+ expect(
+ screen.queryByTestId('contact-details-email-pending'),
+ ).not.toBeInTheDocument();
+ expect(errors).toEqual([]);
+ });
+
+ it('marks the placeholder hidden, empty and without a link', async () => {
+ const html = await serverHtml(card());
+ const doc = new DOMParser().parseFromString(html, 'text/html');
+ const pending = doc.querySelector('[data-email-pending]')!;
+ expect(pending.getAttribute('aria-hidden')).toBe('true');
+ expect(pending.textContent).toBe('');
+ expect(pending.querySelector('a')).toBeNull();
+ });
+
+ it('has no placeholder on a plain mount', async () => {
+ const { container } = await renderWithProviders(card());
+ expect(container.querySelector('[data-email-pending]')).toBeNull();
+ });
+
+ it('has no placeholder without a valid address, only the socials', async () => {
+ const html = await serverHtml(
+ card({ email: { user: '', domain: 'andreaslop.nl' } }),
+ );
+ expect(html).not.toContain('email-pending');
+ expect(html).toContain('contact-details-instagram');
+ });
+
+ it('renders nothing without an address and without socials', async () => {
+ const html = await serverHtml(
+ card({ email: { user: '', domain: '' }, socials: [] }),
+ );
+ expect(html).not.toContain('data-testid="details"');
+ });
+});
diff --git a/web/src/components/ContactDetails/ContactDetails.tsx b/web/src/components/ContactDetails/ContactDetails.tsx
index b551bee..92c5070 100644
--- a/web/src/components/ContactDetails/ContactDetails.tsx
+++ b/web/src/components/ContactDetails/ContactDetails.tsx
@@ -11,6 +11,7 @@ import { Icon } from '@iconify/react/offline';
import Eyebrow from '@/components/Eyebrow/Eyebrow';
import socialPlatforms from '@/content/socialPlatforms';
import type { ContentImage, EmailAddress, SocialLink } from '@/content/types';
+import useHydrated from '@/hooks/useHydrated';
import { contactChannels, type ContactChannel } from '@/lib/contactChannels';
type ContactDetailsProps = {
@@ -25,13 +26,18 @@ type ContactDetailsProps = {
'data-testid'?: string;
};
-const iconOf = (channel: ContactChannel) =>
+// Channels that render as a link; the pending e-mail item is not one
+type LinkChannel = Exclude;
+
+const iconOf = (channel: LinkChannel) =>
channel.kind === 'email'
? mailFilled
: socialPlatforms[channel.platform].icon;
// "Direct contact": a card with the ways to reach Andrea, each an icon and a
-// link (BR-CD-01..08). Renders nothing when no channel is valid.
+// link (BR-CD-01..08). Renders nothing when no channel is valid. Before
+// hydration the e-mail item is an empty placeholder of the same height
+// (BR-MAIL-04).
export default function ContactDetails({
titleId,
title,
@@ -40,7 +46,8 @@ export default function ContactDetails({
portrait,
'data-testid': testId,
}: ContactDetailsProps) {
- const channels = contactChannels(email, socials);
+ // The address is only assembled after hydration (BR-MAIL-07)
+ const channels = contactChannels(email, socials, useHydrated());
if (channels.length === 0) return null;
return (
@@ -71,47 +78,57 @@ export default function ContactDetails({
- {channels.map((channel) => (
-
-
+ channel.kind === 'email-pending' ? (
+
-
+ ) : (
+
+
-
-
- {/* Space outside the hidden text, or it drops out
+
+
+
+ {/* Space outside the hidden text, or it drops out
of the announced name */}
- {channel.label}
- {channel.external && (
- <>
- {' '}
-
- (opent in nieuw tabblad)
-
- >
- )}
-
-
- ))}
+ {channel.label}
+ {channel.external && (
+ <>
+ {' '}
+
+ (opent in nieuw tabblad)
+
+ >
+ )}
+
+
+ ),
+ )}
);
diff --git a/web/src/components/ContactForm/ContactForm.test.tsx b/web/src/components/ContactForm/ContactForm.test.tsx
index 11121e4..2a55818 100644
--- a/web/src/components/ContactForm/ContactForm.test.tsx
+++ b/web/src/components/ContactForm/ContactForm.test.tsx
@@ -5,6 +5,7 @@ import packages from '@/content/packages';
import siteContent from '@/content/siteContent';
import { shootOptions } from '@/lib/shootOptions';
import { axeResults } from '@/test/axe';
+import { serverHtml } from '@/test/hydrate';
import { renderWithProviders } from '@/test/renderWithProviders';
import ContactForm from './ContactForm';
@@ -234,3 +235,21 @@ describe('ContactForm', () => {
expect(container.querySelector('[data-robot-check]')).not.toBeNull();
});
});
+
+describe('ContactForm in the prerendered HTML', () => {
+ it('does not hold the address (BR-MAIL-06)', async () => {
+ const html = await serverHtml(
+ ,
+ );
+ expect(html).toContain('contact-form-submit');
+ expect(html.toLowerCase()).not.toContain('info@andreaslop.nl');
+ expect(html).not.toContain('mailto:');
+ });
+});
diff --git a/web/src/components/ContactForm/ContactForm.tsx b/web/src/components/ContactForm/ContactForm.tsx
index 40097d7..5f8a1b5 100644
--- a/web/src/components/ContactForm/ContactForm.tsx
+++ b/web/src/components/ContactForm/ContactForm.tsx
@@ -26,7 +26,7 @@ import {
INITIAL_CONTACT_STATE,
type ContactFormEvent,
} from '@/lib/contactFormReducer';
-import { emailAddress } from '@/lib/emailAddress';
+import useEmailAddress from '@/hooks/useEmailAddress';
import { mailtoLink } from '@/lib/mailLink';
import { toContactPayload } from '@/lib/toContactPayload';
import { CONTACT_FIELDS } from '@/lib/validateContact';
@@ -92,7 +92,7 @@ export default function ContactForm({
if (state.status === 'sent') sentMessage.current?.focus();
}, [state.status]);
- const address = emailAddress(email);
+ const { address } = useEmailAddress(email);
const disabled = state.status === 'sending';
if (state.status === 'sent') {
diff --git a/web/src/components/ContactForm/ContactFormGate.test.tsx b/web/src/components/ContactForm/ContactFormGate.test.tsx
index 39b3e79..f6895b0 100644
--- a/web/src/components/ContactForm/ContactFormGate.test.tsx
+++ b/web/src/components/ContactForm/ContactFormGate.test.tsx
@@ -2,6 +2,8 @@ import { screen } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import siteContent from '@/content/siteContent';
import { axeResults } from '@/test/axe';
+import { cssRulesFor } from '@/test/cssRules';
+import { hydratePage, serverHtml } from '@/test/hydrate';
import { renderWithProviders } from '@/test/renderWithProviders';
import ContactFormGate from './ContactFormGate';
@@ -71,3 +73,77 @@ describe('ContactFormGate', () => {
expect(await axeResults(container)).toHaveNoViolations();
});
});
+
+// Before hydrating the notice has the sentence only and reserves the room of
+// the address and the button (BR-MAIL-05)
+describe('ContactFormGate in the prerendered HTML', () => {
+ const gate = (email = siteContent.email) => (
+
+
+
+ );
+ const prerendered = async (email?: typeof siteContent.email) => {
+ const html = await serverHtml(gate(email));
+ const doc = new DOMParser().parseFromString(html, 'text/html');
+ return { html, doc };
+ };
+
+ it('holds the sentence only, hidden placeholders and no address', async () => {
+ const { html, doc } = await prerendered();
+ expect(html.toLowerCase()).not.toContain('info@andreaslop.nl');
+ expect(html).not.toContain('mailto:');
+ expect(html).not.toContain('Mail me voor nu op');
+ expect(html).not.toContain('data-testid="contact-gate-mail"');
+ expect(
+ doc.querySelector('[data-testid="contact-gate-notice"]')!
+ .textContent,
+ ).toContain('Het contactformulier komt binnenkort.');
+ const pending = doc.querySelector(
+ '[data-testid="contact-gate-mail-pending"]',
+ )!;
+ expect(pending.getAttribute('aria-hidden')).toBe('true');
+ expect(pending.hasAttribute('data-email-pending')).toBe(true);
+ expect(pending.getAttribute('href')).toBeNull();
+ });
+
+ it('reserves the width of the lead and the address in characters', async () => {
+ const { doc } = await prerendered();
+ const reserved = doc.querySelector('p [data-email-pending]')!;
+ // Hydrating makes React generate the same classes, which puts their
+ // rules in the document
+ await hydratePage(gate());
+ const probe = document.createElement('span');
+ probe.className = reserved.className;
+ // ' Mail me voor nu op ' (20) + 'info@andreaslop.nl' (18)
+ expect(cssRulesFor(probe).join(' ')).toContain('width: 38ch');
+ });
+
+ it('shows the address, link and button after hydrating', async () => {
+ const { errors } = await hydratePage(gate());
+ const mail = await screen.findByTestId('contact-gate-mail');
+ expect(mail).toHaveAttribute(
+ 'href',
+ 'mailto:info@andreaslop.nl?subject=Aanvraag%20fotoshoot%3A%20Newborn',
+ );
+ expect(screen.getByTestId('contact-gate-notice')).toHaveTextContent(
+ 'Het contactformulier komt binnenkort. Mail me voor nu op info@andreaslop.nl',
+ );
+ expect(
+ screen.queryByTestId('contact-gate-mail-pending'),
+ ).not.toBeInTheDocument();
+ expect(errors).toEqual([]);
+ });
+
+ it('has no placeholders without a valid address', async () => {
+ const { html } = await prerendered({
+ user: '',
+ domain: 'andreaslop.nl',
+ });
+ expect(html).not.toContain('email-pending');
+ expect(html).toContain('Het contactformulier komt binnenkort.');
+ });
+});
diff --git a/web/src/components/ContactForm/ContactFormGate.tsx b/web/src/components/ContactForm/ContactFormGate.tsx
index 41b3f10..e8081c5 100644
--- a/web/src/components/ContactForm/ContactFormGate.tsx
+++ b/web/src/components/ContactForm/ContactFormGate.tsx
@@ -3,7 +3,7 @@ import { Box, chakra, Link, Text, useRecipe } from '@chakra-ui/react';
import Eyebrow from '@/components/Eyebrow/Eyebrow';
import PrivacyNote from '@/components/PrivacyNote/PrivacyNote';
import type { EmailAddress } from '@/content/types';
-import { emailAddress } from '@/lib/emailAddress';
+import useEmailAddress from '@/hooks/useEmailAddress';
import { mailtoLink } from '@/lib/mailLink';
type ContactFormGateProps = {
@@ -13,6 +13,9 @@ type ContactFormGateProps = {
children: ReactNode;
};
+// The text that comes before the address once it is shown
+const MAIL_LEAD = ' Mail me voor nu op ';
+
// Until there is a back-end the form stays visible but dimmed and inert
// under a "coming soon" notice with a mail button (FR-HP-07). inert keeps
// keyboard and screen reader users out of a form that does nothing.
@@ -23,10 +26,11 @@ export default function ContactFormGate({
children,
}: ContactFormGateProps) {
const linkButton = useRecipe({ key: 'linkButton' });
+ // Assembled after hydration, so the address is nowhere in the HTML or the
+ // bundle (BR-MAIL-05)
+ const { available, address } = useEmailAddress(email);
if (enabled) return <>{children}>;
- // Assembled in the browser, so the address is nowhere in the bundle
- const address = emailAddress(email);
const href = address ? mailtoLink(address, subject) : undefined;
return (
@@ -49,26 +53,52 @@ export default function ContactFormGate({
data-testid="contact-gate-notice"
>
Binnenkort
-
+
Het contactformulier komt binnenkort.
- {address && (
+ {address ? (
<>
- {' Mail me voor nu op '}
+ {MAIL_LEAD}
{address}
>
+ ) : (
+ available && (
+ // Reserves the width of the lead and the address
+ // (counted without assembling it), so the line
+ // breaks where it will after hydration
+
+ )
)}
- {address && (
-
- Stuur een e-mail
-
- )}
+ {available &&
+ (address ? (
+
+ Stuur een e-mail
+
+ ) : (
+ // Same recipe and label, so the notice is as high as
+ // it will be; hidden from sight and from readers
+
+ Stuur een e-mail
+
+ ))}
{/* Readable now, while the form's own line is inert (BR-PR-03) */}
diff --git a/web/src/components/Footer/Footer.test.tsx b/web/src/components/Footer/Footer.test.tsx
index 3220347..90a3fca 100644
--- a/web/src/components/Footer/Footer.test.tsx
+++ b/web/src/components/Footer/Footer.test.tsx
@@ -1,8 +1,11 @@
import { screen, within } from '@testing-library/react';
-import { describe, expect, it } from 'vitest';
+import fc from 'fast-check';
+import { describe, expect, it, vi } from 'vitest';
import siteContent from '@/content/siteContent';
import type { SiteContent } from '@/content/types';
+import { validEmail } from '@/test/arbitraries';
import { axeResults } from '@/test/axe';
+import { hydratePage, serverHtml } from '@/test/hydrate';
import { renderWithProviders } from '@/test/renderWithProviders';
import Footer from './Footer';
@@ -126,3 +129,95 @@ describe('Footer', () => {
expect(screen.queryByTestId('footer-email-link')).toBeNull();
});
});
+
+// The page is prerendered and hydrated in the browser: the address and the
+// current year only come after hydrating (BR-MAIL-01, BR-HYD-14)
+describe('Footer in the prerendered HTML', () => {
+ const noAddress = (html: string, address: string) => {
+ expect(html.toLowerCase()).not.toContain(address.toLowerCase());
+ expect(html).not.toContain('mailto:');
+ };
+
+ it('holds an empty placeholder instead of the address', async () => {
+ const html = await serverHtml();
+ noAddress(html, 'info@andreaslop.nl');
+ expect(html).not.toContain('footer-email-link');
+ expect(html).toContain('data-testid="footer-email-pending"');
+ expect(html).toContain('>Contact');
+ });
+
+ it('never holds the address, whatever the content (invariant)', async () => {
+ await fc.assert(
+ fc.asyncProperty(validEmail, async ({ user, domain }) => {
+ const html = await serverHtml(
+ ,
+ );
+ noAddress(html, `${user}@${domain}`);
+ }),
+ );
+ });
+
+ it('has no Contact column and no placeholder without a valid address', async () => {
+ const html = await serverHtml(
+ ,
+ );
+ expect(html).not.toContain('>Contact');
+ expect(html).not.toContain('footer-email-pending');
+ });
+
+ it('shows the placeholder, no link and an empty hidden item while hydrating, then the link', async () => {
+ const html = await serverHtml();
+ const { container, errors } = await hydratePage(
+ ,
+ );
+ expect(errors).toEqual([]);
+ expect(html).toContain('aria-hidden="true"');
+ await screen.findByTestId('footer-email-link');
+ expect(screen.getByTestId('footer-email-link')).toHaveAttribute(
+ 'href',
+ 'mailto:info@andreaslop.nl',
+ );
+ expect(
+ container.querySelector('[data-email-pending]'),
+ ).not.toBeInTheDocument();
+ });
+
+ it('uses the build year while hydrating and the current year after', async () => {
+ vi.stubEnv('VITE_BUILD_YEAR', '2001');
+ try {
+ const html = await serverHtml();
+ expect(html).toContain('ยฉ 2001 Andrea Slop Fotografie');
+
+ const { container, errors } = await hydratePage(
+ ,
+ );
+ expect(container).toHaveTextContent(
+ `ยฉ ${new Date().getFullYear()} Andrea Slop Fotografie`,
+ );
+ expect(errors).toEqual([]);
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ });
+
+ it('shows the current year at once on a plain mount', async () => {
+ vi.stubEnv('VITE_BUILD_YEAR', '2001');
+ try {
+ await renderFooter();
+ expect(
+ screen.getByText(
+ `ยฉ ${new Date().getFullYear()} Andrea Slop Fotografie`,
+ ),
+ ).toBeInTheDocument();
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ });
+});
diff --git a/web/src/components/Footer/Footer.tsx b/web/src/components/Footer/Footer.tsx
index 41eed28..88ea1a3 100644
--- a/web/src/components/Footer/Footer.tsx
+++ b/web/src/components/Footer/Footer.tsx
@@ -10,8 +10,9 @@ import {
} from '@chakra-ui/react';
import socialPlatforms from '@/content/socialPlatforms';
import type { SiteContent } from '@/content/types';
+import useEmailAddress from '@/hooks/useEmailAddress';
+import useHydrated from '@/hooks/useHydrated';
import { copyrightLine } from '@/lib/copyrightLine';
-import { emailAddress } from '@/lib/emailAddress';
import { visibleSocials } from '@/lib/visibleSocials';
import { footerNav } from '@/navigation';
import RouterLink from '../RouterLink';
@@ -29,9 +30,15 @@ type FooterProps = {
// copyright en het footermenu. Een lege kolom valt weg (BR-FOOT-01).
export default function Footer({ content }: FooterProps) {
const socials = visibleSocials(content.socials);
- // Pas hier samengevoegd, zodat het adres nergens letterlijk staat
- const email = emailAddress(content.email);
- const year = new Date().getFullYear();
+ // Het adres wordt pas na de hydratatie samengevoegd, zodat het nergens
+ // letterlijk in de HTML of de bundel staat (BR-MAIL-01). Ervoor houdt een
+ // lege plek de ruimte vrij.
+ const { available, address } = useEmailAddress(content.email);
+ // Het jaar van de build tot de hydratatie, zodat server en browser
+ // dezelfde HTML hebben; daarna het huidige jaar (BR-HYD-14)
+ const year = useHydrated()
+ ? new Date().getFullYear()
+ : Number(import.meta.env.VITE_BUILD_YEAR);
return (
)}
- {email && (
+ {available && (
-
-
- {email}
-
-
+ {address === null ? (
+ // Even hoog als FooterLink (44px onder lg, daarna
+ // een tekstregel), zodat de kolom niet verspringt
+
+ ) : (
+
+
+ {address}
+
+
+ )}
)}
diff --git a/web/src/components/Hero/useHeroSlider.test.tsx b/web/src/components/Hero/useHeroSlider.test.tsx
index 50830ff..c51d1eb 100644
--- a/web/src/components/Hero/useHeroSlider.test.tsx
+++ b/web/src/components/Hero/useHeroSlider.test.tsx
@@ -1,5 +1,6 @@
import { act, fireEvent, render, renderHook } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
+import { hydrate, renderToString } from '@/test/hydrate';
import useHeroSlider from './useHeroSlider';
// De automatische wissel komt in de browser van animationend op de
@@ -84,3 +85,74 @@ describe('useHeroSlider', () => {
expect(slider).toMatchObject({ stopped: false, paused: false });
});
});
+
+// In de HTML is het tabblad zichtbaar en loopt autoplay; pas na de hydratatie
+// telt wat de browser meldt (BR-HYD-09)
+describe('useHeroSlider tijdens het hydrateren', () => {
+ const seen: { paused: boolean; autoplay: boolean }[] = [];
+
+ function Probe() {
+ const { paused, autoplay } = useHeroSlider(3);
+ seen.push({ paused, autoplay });
+ return (
+
;
+}
+
+const info = { user: 'info', domain: 'andreaslop.nl' };
+
+describe('useEmailAddress', () => {
+ it('is pending in the server render: available, without the address', () => {
+ expect(renderToString()).toBe('
pending
');
+ });
+
+ it('is absent in the server render for invalid parts', () => {
+ expect(renderToString()).toBe(
+ '
absent
',
+ );
+ });
+
+ it('assembles the address only after the hydrating render', () => {
+ seen.length = 0;
+ const { container, errors } = hydrate();
+ expect(seen[0]).toEqual({ available: true, address: null });
+ expect(seen.at(-1)).toEqual({
+ available: true,
+ address: 'info@andreaslop.nl',
+ });
+ expect(container).toHaveTextContent('info@andreaslop.nl');
+ expect(errors).toEqual([]);
+ });
+
+ it('gives the address at once for a component that mounts later', () => {
+ const { result } = renderHook(() => useEmailAddress(info));
+ expect(result.current).toEqual({
+ available: true,
+ address: 'info@andreaslop.nl',
+ });
+ });
+
+ it('gives neither for invalid parts', () => {
+ const { result } = renderHook(() =>
+ useEmailAddress({ user: 'info', domain: 'nodot' }),
+ );
+ expect(result.current).toEqual({ available: false, address: null });
+ });
+
+ it('agrees with emailAddress once hydrated (oracle)', () => {
+ fc.assert(
+ fc.property(anyEmail, (parts) => {
+ const { result, unmount } = renderHook(() =>
+ useEmailAddress(parts),
+ );
+ const expected = emailAddress(parts);
+ expect(result.current).toEqual({
+ available: expected !== null,
+ address: expected,
+ });
+ unmount();
+ }),
+ );
+ });
+});
diff --git a/web/src/hooks/useEmailAddress.ts b/web/src/hooks/useEmailAddress.ts
new file mode 100644
index 0000000..753f874
--- /dev/null
+++ b/web/src/hooks/useEmailAddress.ts
@@ -0,0 +1,18 @@
+import type { EmailAddress } from '@/content/types';
+import { emailAddress, isEmailAddressValid } from '@/lib/emailAddress';
+import useHydrated from './useHydrated';
+
+// `available` is the same on the server and in the browser, so the layout can
+// reserve room for the address. `address` is assembled only after hydration,
+// which keeps it out of the prerendered HTML (BR-MAIL-01).
+export default function useEmailAddress(email: EmailAddress): {
+ available: boolean;
+ address: string | null;
+} {
+ const hydrated = useHydrated();
+ const available = isEmailAddressValid(email);
+ return {
+ available,
+ address: hydrated && available ? emailAddress(email) : null,
+ };
+}
diff --git a/web/src/hooks/useHydrated.test.tsx b/web/src/hooks/useHydrated.test.tsx
new file mode 100644
index 0000000..5e4fa32
--- /dev/null
+++ b/web/src/hooks/useHydrated.test.tsx
@@ -0,0 +1,35 @@
+import { render } from '@testing-library/react';
+import { describe, expect, it } from 'vitest';
+import { hydrate, renderToString } from '@/test/hydrate';
+import useHydrated from './useHydrated';
+
+// Records the value of every render, to see the hydrating one
+const seen: boolean[] = [];
+
+function Probe() {
+ const hydrated = useHydrated();
+ seen.push(hydrated);
+ return
{String(hydrated)}
;
+}
+
+describe('useHydrated', () => {
+ it('is false in the server render', () => {
+ expect(renderToString()).toBe('
false
');
+ });
+
+ it('is false in the hydrating render and true right after', () => {
+ seen.length = 0;
+ const { container, errors } = hydrate();
+ expect(seen[0]).toBe(false);
+ expect(seen.at(-1)).toBe(true);
+ expect(container).toHaveTextContent('true');
+ expect(errors).toEqual([]);
+ });
+
+ it('is true at once for a component that mounts later', () => {
+ seen.length = 0;
+ const { container } = render();
+ expect(seen).toEqual([true]);
+ expect(container).toHaveTextContent('true');
+ });
+});
diff --git a/web/src/hooks/useInView.test.tsx b/web/src/hooks/useInView.test.tsx
new file mode 100644
index 0000000..9f92996
--- /dev/null
+++ b/web/src/hooks/useInView.test.tsx
@@ -0,0 +1,82 @@
+import { act, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { FakeIntersectionObserver as FakeObserver } from '@/test/fakeIntersectionObserver';
+import { hydrate, renderToString } from '@/test/hydrate';
+import useInView from './useInView';
+
+const seen: boolean[] = [];
+
+function Probe({ skip }: { skip?: boolean }) {
+ const { ref, inView } = useInView({ skip });
+ seen.push(inView);
+ return (
+
+ {inView ? 'in view' : 'not in view'}
+
+ );
+}
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ FakeObserver.reset();
+});
+
+describe('useInView without IntersectionObserver', () => {
+ it('is not in view in the server render', () => {
+ expect(renderToString()).toContain('not in view');
+ });
+
+ it('is in view only after the hydrating render', () => {
+ seen.length = 0;
+ const { container, errors } = hydrate();
+ expect(seen[0]).toBe(false);
+ expect(seen.at(-1)).toBe(true);
+ expect(container).toHaveTextContent(/^in view$/);
+ expect(errors).toEqual([]);
+ });
+
+ it('is in view at once for a component that mounts later', () => {
+ seen.length = 0;
+ render();
+ expect(seen).toEqual([true]);
+ });
+
+ it('respects skip in every render', () => {
+ expect(renderToString()).not.toContain('not in view');
+ seen.length = 0;
+ const { errors } = hydrate();
+ expect(seen.every(Boolean)).toBe(true);
+ expect(errors).toEqual([]);
+ });
+});
+
+describe('useInView with IntersectionObserver', () => {
+ it('is not in view in the server render and observes only after hydrating', () => {
+ vi.stubGlobal('IntersectionObserver', FakeObserver);
+ expect(renderToString()).toContain('not in view');
+ expect(FakeObserver.instances).toHaveLength(0);
+
+ const { container, errors } = hydrate();
+ expect(container).toHaveTextContent('not in view');
+ expect(FakeObserver.instances).toHaveLength(1);
+ expect(errors).toEqual([]);
+
+ act(() => FakeObserver.instances[0].trigger(true));
+ expect(container).toHaveTextContent(/^in view$/);
+ });
+
+ it('is not in view on a plain mount until the element intersects', () => {
+ vi.stubGlobal('IntersectionObserver', FakeObserver);
+ render();
+ expect(screen.getByTestId('probe')).toHaveTextContent('not in view');
+ act(() => FakeObserver.instances[0].trigger(true));
+ expect(screen.getByTestId('probe')).toHaveTextContent(/^in view$/);
+ });
+
+ it('does not observe when skip is set', () => {
+ vi.stubGlobal('IntersectionObserver', FakeObserver);
+ render();
+ expect(screen.getByTestId('probe')).toHaveTextContent(/^in view$/);
+ expect(FakeObserver.instances).toHaveLength(0);
+ });
+});
diff --git a/web/src/hooks/useInView.ts b/web/src/hooks/useInView.ts
index 320a814..deacd8c 100644
--- a/web/src/hooks/useInView.ts
+++ b/web/src/hooks/useInView.ts
@@ -29,6 +29,9 @@ export default function useInView({
useEffect(() => {
const element = ref.current;
if (!element || skip || unsupported || intersected) return;
+ // The effect of the hydrating render still sees the server's
+ // `unsupported` (false), so check the browser itself as well
+ if (typeof IntersectionObserver === 'undefined') return;
const observer = new IntersectionObserver(
(entries) => {
diff --git a/web/src/hooks/usePageLoaded.test.tsx b/web/src/hooks/usePageLoaded.test.tsx
index 8c3d655..a6752f4 100644
--- a/web/src/hooks/usePageLoaded.test.tsx
+++ b/web/src/hooks/usePageLoaded.test.tsx
@@ -1,7 +1,16 @@
-import { act, renderHook } from '@testing-library/react';
+import { act, render, renderHook } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
+import { hydrate, renderToString } from '@/test/hydrate';
import usePageLoaded from './usePageLoaded';
+const seen: boolean[] = [];
+
+function Probe() {
+ const loaded = usePageLoaded();
+ seen.push(loaded);
+ return
{String(loaded)}
;
+}
+
describe('usePageLoaded', () => {
it('is true when the page had already loaded', () => {
const { result } = renderHook(() => usePageLoaded());
@@ -22,4 +31,38 @@ describe('usePageLoaded', () => {
});
expect(result.current).toBe(true);
});
+
+ it('is false in the server render, even when the page has loaded', () => {
+ expect(renderToString()).toBe('
false
');
+ });
+
+ it('is false in the hydrating render and true right after on a loaded page', () => {
+ seen.length = 0;
+ const { container, errors } = hydrate();
+ expect(seen[0]).toBe(false);
+ expect(seen.at(-1)).toBe(true);
+ expect(container).toHaveTextContent('true');
+ expect(errors).toEqual([]);
+ });
+
+ it('stays false after hydrating until the load event', () => {
+ const readyState = vi
+ .spyOn(document, 'readyState', 'get')
+ .mockReturnValue('interactive');
+ const { container, errors } = hydrate();
+ expect(container).toHaveTextContent('false');
+
+ act(() => {
+ readyState.mockReturnValue('complete');
+ window.dispatchEvent(new Event('load'));
+ });
+ expect(container).toHaveTextContent('true');
+ expect(errors).toEqual([]);
+ });
+
+ it('is true at once for a component that mounts on a loaded page', () => {
+ seen.length = 0;
+ render();
+ expect(seen).toEqual([true]);
+ });
});
diff --git a/web/src/hooks/useReveal.test.tsx b/web/src/hooks/useReveal.test.tsx
index 1d1ccd7..71b9d30 100644
--- a/web/src/hooks/useReveal.test.tsx
+++ b/web/src/hooks/useReveal.test.tsx
@@ -2,6 +2,7 @@ import { act, render, screen } from '@testing-library/react';
import { ChakraProvider } from '@chakra-ui/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { FakeIntersectionObserver as FakeObserver } from '@/test/fakeIntersectionObserver';
+import { hydrate, renderToString } from '@/test/hydrate';
import system from '../theme';
import useReveal from './useReveal';
@@ -88,3 +89,35 @@ describe('useReveal', () => {
expect(FakeObserver.instances[0].disconnected).toBe(true);
});
});
+
+describe('useReveal while hydrating', () => {
+ const page = (
+
+
+
+ );
+
+ it('is hidden in the server render', () => {
+ vi.stubGlobal('IntersectionObserver', FakeObserver);
+ expect(renderToString(page)).toContain('hidden');
+ });
+
+ it('assumes no reduced motion in the hydrating render, then follows the preference', () => {
+ vi.stubGlobal('IntersectionObserver', FakeObserver);
+ mockReducedMotion();
+ const markup = renderToString(page);
+ const { container, errors } = hydrate(page, markup);
+ expect(container).toHaveTextContent('visible');
+ expect(errors).toEqual([]);
+ });
+
+ it('stays hidden after hydrating until the element scrolls into view', () => {
+ vi.stubGlobal('IntersectionObserver', FakeObserver);
+ const { container, errors } = hydrate(page);
+ expect(container).toHaveTextContent('hidden');
+ expect(errors).toEqual([]);
+
+ act(() => FakeObserver.instances.at(-1)!.trigger(true));
+ expect(container).toHaveTextContent('visible');
+ });
+});
diff --git a/web/src/lib/contactChannels.test.ts b/web/src/lib/contactChannels.test.ts
index a2886ef..84482e6 100644
--- a/web/src/lib/contactChannels.test.ts
+++ b/web/src/lib/contactChannels.test.ts
@@ -2,43 +2,52 @@ import fc from 'fast-check';
import { describe, expect, it } from 'vitest';
import siteContent from '../content/siteContent';
import socialPlatforms from '../content/socialPlatforms';
-import { anyEmail, socialLink } from '../test/arbitraries';
-import { contactChannels } from './contactChannels';
+import { anyEmail, socialLink, validEmail } from '../test/arbitraries';
+import { type ContactChannel, contactChannels } from './contactChannels';
import { emailAddress } from './emailAddress';
import { visibleSocials } from './visibleSocials';
const socialLinks = fc.array(socialLink, { maxLength: 5 });
+// With the address assembled there is no placeholder channel, so the narrowed
+// type lets the existing tests read href, label and external
+const assembled = (
+ email: Parameters[0],
+ socials: Parameters[1],
+) =>
+ contactChannels(email, socials, true) as Exclude<
+ ContactChannel,
+ { kind: 'email-pending' }
+ >[];
+
describe('contactChannels', () => {
it('lists e-mail, Instagram and Facebook for the site content', () => {
- expect(contactChannels(siteContent.email, siteContent.socials)).toEqual(
- [
- {
- kind: 'email',
- href: 'mailto:info@andreaslop.nl?subject=Vraag%20via%20andreaslop.nl',
- label: 'info@andreaslop.nl',
- external: false,
- },
- {
- kind: 'social',
- platform: 'instagram',
- href: 'https://www.instagram.com/andreaslopfotografie/',
- label: '@andreaslopfotografie',
- external: true,
- },
- {
- kind: 'social',
- platform: 'facebook',
- href: 'https://www.facebook.com/andreaslopfotografie/',
- label: 'Andrea Slop Fotografie',
- external: true,
- },
- ],
- );
+ expect(assembled(siteContent.email, siteContent.socials)).toEqual([
+ {
+ kind: 'email',
+ href: 'mailto:info@andreaslop.nl?subject=Vraag%20via%20andreaslop.nl',
+ label: 'info@andreaslop.nl',
+ external: false,
+ },
+ {
+ kind: 'social',
+ platform: 'instagram',
+ href: 'https://www.instagram.com/andreaslopfotografie/',
+ label: '@andreaslopfotografie',
+ external: true,
+ },
+ {
+ kind: 'social',
+ platform: 'facebook',
+ href: 'https://www.facebook.com/andreaslopfotografie/',
+ label: 'Andrea Slop Fotografie',
+ external: true,
+ },
+ ]);
});
it('leaves out an invalid e-mail address and invalid links', () => {
- const channels = contactChannels({ user: 'info', domain: 'nodot' }, [
+ const channels = assembled({ user: 'info', domain: 'nodot' }, [
{ platform: 'facebook', href: 'javascript:alert(1)' },
{ platform: 'instagram', href: 'https://instagram.com/x' },
]);
@@ -46,7 +55,7 @@ describe('contactChannels', () => {
});
it('falls back to the platform name without a usable label', () => {
- const channels = contactChannels({ user: '', domain: '' }, [
+ const channels = assembled({ user: '', domain: '' }, [
{ platform: 'instagram', href: 'https://instagram.com/x' },
{
platform: 'facebook',
@@ -61,13 +70,13 @@ describe('contactChannels', () => {
});
it('is empty when nothing is valid', () => {
- expect(contactChannels({ user: '', domain: '' }, [])).toEqual([]);
+ expect(assembled({ user: '', domain: '' }, [])).toEqual([]);
});
it('puts the e-mail channel first exactly when the address is valid (invariant)', () => {
fc.assert(
fc.property(anyEmail, socialLinks, (email, socials) => {
- const channels = contactChannels(email, socials);
+ const channels = assembled(email, socials);
const valid = emailAddress(email) !== null;
expect(channels[0]?.kind === 'email').toBe(valid);
expect(
@@ -80,16 +89,15 @@ describe('contactChannels', () => {
it('shows exactly the visible social links, in order (oracle)', () => {
fc.assert(
fc.property(anyEmail, socialLinks, (email, socials) => {
- const shown = contactChannels(email, socials).flatMap(
- (channel) =>
- channel.kind === 'social'
- ? [
- {
- platform: channel.platform,
- href: channel.href,
- },
- ]
- : [],
+ const shown = assembled(email, socials).flatMap((channel) =>
+ channel.kind === 'social'
+ ? [
+ {
+ platform: channel.platform,
+ href: channel.href,
+ },
+ ]
+ : [],
);
expect(shown).toEqual(
visibleSocials(socials).map(({ platform, href }) => ({
@@ -104,10 +112,7 @@ describe('contactChannels', () => {
it('labels a social link with its trimmed label, or else the platform name (invariant)', () => {
fc.assert(
fc.property(socialLinks, (socials) => {
- const channels = contactChannels(
- { user: '', domain: '' },
- socials,
- );
+ const channels = assembled({ user: '', domain: '' }, socials);
visibleSocials(socials).forEach((link, index) => {
const expected =
link.label?.trim() ||
@@ -122,7 +127,7 @@ describe('contactChannels', () => {
it('only links to mailto: or https: (invariant)', () => {
fc.assert(
fc.property(anyEmail, socialLinks, (email, socials) => {
- for (const channel of contactChannels(email, socials)) {
+ for (const channel of assembled(email, socials)) {
const scheme = new URL(channel.href).protocol;
expect(
channel.kind === 'email' ? 'mailto:' : 'https:',
@@ -135,7 +140,7 @@ describe('contactChannels', () => {
it('opens exactly the social channels in a new tab (invariant)', () => {
fc.assert(
fc.property(anyEmail, socialLinks, (email, socials) => {
- for (const channel of contactChannels(email, socials)) {
+ for (const channel of assembled(email, socials)) {
expect(channel.external).toBe(channel.kind === 'social');
}
}),
@@ -145,9 +150,56 @@ describe('contactChannels', () => {
it('has at most one channel per link plus the e-mail (invariant)', () => {
fc.assert(
fc.property(anyEmail, socialLinks, (email, socials) => {
- expect(
- contactChannels(email, socials).length,
- ).toBeLessThanOrEqual(1 + socials.length);
+ expect(assembled(email, socials).length).toBeLessThanOrEqual(
+ 1 + socials.length,
+ );
+ }),
+ );
+ });
+});
+
+describe('contactChannels before the address may be assembled', () => {
+ it('puts a placeholder without href and label first for valid parts', () => {
+ expect(
+ contactChannels(siteContent.email, siteContent.socials, false)[0],
+ ).toEqual({ kind: 'email-pending' });
+ });
+
+ it('keeps the social channels the same as when assembling', () => {
+ const socials = (assemble: boolean) =>
+ contactChannels(
+ siteContent.email,
+ siteContent.socials,
+ assemble,
+ ).filter((channel) => channel.kind === 'social');
+ expect(socials(false)).toEqual(socials(true));
+ });
+
+ it('gives no placeholder for invalid parts', () => {
+ expect(
+ contactChannels({ user: 'info', domain: 'nodot' }, [], false),
+ ).toEqual([]);
+ });
+
+ it('never contains the assembled address (invariant)', () => {
+ fc.assert(
+ fc.property(validEmail, socialLinks, (email, socials) => {
+ const address = emailAddress(email)!;
+ const json = JSON.stringify(
+ contactChannels(email, socials, false),
+ );
+ expect(json).not.toContain(address);
+ expect(json).not.toContain('mailto:');
+ }),
+ );
+ });
+
+ it('has as many channels as when assembling (invariant)', () => {
+ fc.assert(
+ fc.property(anyEmail, socialLinks, (email, socials) => {
+ expect(contactChannels(email, socials, false)).toHaveLength(
+ contactChannels(email, socials, true).length,
+ );
}),
);
});
diff --git a/web/src/lib/contactChannels.ts b/web/src/lib/contactChannels.ts
index d237ac7..6cfa39a 100644
--- a/web/src/lib/contactChannels.ts
+++ b/web/src/lib/contactChannels.ts
@@ -2,13 +2,16 @@ import socialPlatforms, {
type SocialPlatform,
} from '../content/socialPlatforms.ts';
import type { EmailAddress, SocialLink } from '../content/types.ts';
-import { emailAddress } from './emailAddress.ts';
+import { emailAddress, isEmailAddressValid } from './emailAddress.ts';
import { mailSubject, mailtoLink } from './mailLink.ts';
import { visibleSocials } from './visibleSocials.ts';
// One way to reach Andrea, as the contact card shows it
export type ContactChannel =
| { kind: 'email'; href: string; label: string; external: false }
+ // Stands in for the e-mail item until the address may be assembled
+ // (BR-MAIL-07): no href and no label, so nothing readable or clickable
+ | { kind: 'email-pending' }
| {
kind: 'social';
platform: SocialPlatform;
@@ -21,22 +24,28 @@ export type ContactChannel =
// The channels of the contact card (BR-CD-01..05): the e-mail address first
// when it is valid, then the valid social links in content order, each with
// its label or else the platform name. Only mailto: and https: links come
-// out, because both helpers already drop everything else.
+// out, because both helpers already drop everything else. Without `assemble`
+// (prerender and hydrating render) a valid address gives an `email-pending`
+// placeholder, so the address stays out of the HTML (BR-MAIL-01).
export function contactChannels(
email: EmailAddress,
socials: readonly SocialLink[],
+ assemble: boolean,
): ContactChannel[] {
- const address = emailAddress(email);
- const mail: ContactChannel[] = address
- ? [
- {
- kind: 'email',
- href: mailtoLink(address, mailSubject()),
- label: address,
- external: false,
- },
- ]
- : [];
+ const mail: ContactChannel[] = [];
+ if (isEmailAddressValid(email)) {
+ if (assemble) {
+ const address = emailAddress(email)!;
+ mail.push({
+ kind: 'email',
+ href: mailtoLink(address, mailSubject()),
+ label: address,
+ external: false,
+ });
+ } else {
+ mail.push({ kind: 'email-pending' });
+ }
+ }
const social = visibleSocials(socials).map((link): ContactChannel => ({
kind: 'social',
platform: link.platform,
diff --git a/web/src/lib/emailAddress.test.ts b/web/src/lib/emailAddress.test.ts
index 00eeba3..d89250b 100644
--- a/web/src/lib/emailAddress.test.ts
+++ b/web/src/lib/emailAddress.test.ts
@@ -1,7 +1,7 @@
import fc from 'fast-check';
import { describe, expect, it } from 'vitest';
import { anyEmail, validEmail } from '../test/arbitraries';
-import { emailAddress } from './emailAddress';
+import { emailAddress, isEmailAddressValid } from './emailAddress';
describe('emailAddress', () => {
it('voegt geldige delen samen', () => {
@@ -46,3 +46,33 @@ describe('emailAddress', () => {
);
});
});
+
+describe('isEmailAddressValid', () => {
+ it('is waar voor geldige delen', () => {
+ expect(
+ isEmailAddressValid({ user: 'info', domain: 'andreaslop.nl' }),
+ ).toBe(true);
+ });
+
+ it('is onwaar bij ongeldige delen', () => {
+ for (const parts of [
+ { user: '', domain: 'andreaslop.nl' },
+ { user: 'info', domain: '' },
+ { user: 'in fo', domain: 'andreaslop.nl' },
+ { user: 'info', domain: 'andreaslop' },
+ { user: 'info', domain: 'andrea@slop.nl' },
+ ]) {
+ expect(isEmailAddressValid(parts)).toBe(false);
+ }
+ });
+
+ it('is precies dan waar als emailAddress een adres geeft (oracle)', () => {
+ fc.assert(
+ fc.property(anyEmail, (parts) => {
+ expect(isEmailAddressValid(parts)).toBe(
+ emailAddress(parts) !== null,
+ );
+ }),
+ );
+ });
+});
diff --git a/web/src/lib/emailAddress.ts b/web/src/lib/emailAddress.ts
index fe4ca78..2643795 100644
--- a/web/src/lib/emailAddress.ts
+++ b/web/src/lib/emailAddress.ts
@@ -2,11 +2,14 @@ import type { EmailAddress } from '../content/types';
const invalidPart = (part: string) => part === '' || /[\s@]/.test(part);
+// Zegt of de delen een geldig adres geven, zonder het samen te voegen. Zo
+// weten de pagina's al voor de hydratatie of er een adres is (BR-MAIL-08).
+export function isEmailAddressValid({ user, domain }: EmailAddress): boolean {
+ return !invalidPart(user) && !invalidPart(domain) && domain.includes('.');
+}
+
// Voegt het e-mailadres pas in de browser samen (BR-EMAIL-01). Geeft null bij
// ongeldige delen, zodat de footer de Contact-kolom kan weglaten (BR-EMAIL-02).
-export function emailAddress({ user, domain }: EmailAddress): string | null {
- if (invalidPart(user) || invalidPart(domain) || !domain.includes('.')) {
- return null;
- }
- return `${user}@${domain}`;
+export function emailAddress(parts: EmailAddress): string | null {
+ return isEmailAddressValid(parts) ? `${parts.user}@${parts.domain}` : null;
}
diff --git a/web/src/routes/contact.tsx b/web/src/routes/contact.tsx
index ba613c1..1fdd055 100644
--- a/web/src/routes/contact.tsx
+++ b/web/src/routes/contact.tsx
@@ -11,6 +11,7 @@ import contactContent from '../content/contactContent';
import packages from '../content/packages';
import siteContent from '../content/siteContent';
import { withReplyTime } from '../lib/withReplyTime';
+import useHydrated from '../hooks/useHydrated';
import { contactPage, pageHead, structuredDataScript } from '../seo';
// ?pakket= from a link elsewhere on the site. Only text is kept; the panel
@@ -34,7 +35,10 @@ export const Route = createFileRoute('/contact')({
// form (BR-CP-01..04). The card is in the page twice, one per layout, so the
// reading order always matches what is shown.
function Contact() {
- const { pakket } = Route.useSearch();
+ const { pakket: searched } = Route.useSearch();
+ // The search only counts after hydration, so the prerendered HTML and the
+ // first browser render agree (BR-HYD-10)
+ const pakket = useHydrated() ? searched : undefined;
const navigate = useNavigate();
const { head, formTitle, detailsTitle, image, portrait } = contactContent;
const { email, socials, contactForm } = siteContent;
diff --git a/web/src/routes/hydration.test.tsx b/web/src/routes/hydration.test.tsx
new file mode 100644
index 0000000..1acc6c0
--- /dev/null
+++ b/web/src/routes/hydration.test.tsx
@@ -0,0 +1,73 @@
+import { screen, waitFor, within } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { FakeIntersectionObserver } from '@/test/fakeIntersectionObserver';
+import { hydrateApp } from '@/test/hydrate';
+
+// A direct load of a page with a search: the HTML was prerendered without it,
+// so the first browser render must ignore it and the page applies it right
+// after hydrating (BR-HYD-10 to 12). React reports a mismatch through
+// onRecoverableError, which hydrate() collects.
+beforeEach(() => {
+ vi.stubGlobal('IntersectionObserver', FakeIntersectionObserver);
+ Element.prototype.scrollTo = () => {};
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ FakeIntersectionObserver.reset();
+ // @ts-expect-error -- jsdom has no Element.scrollTo of its own
+ delete Element.prototype.scrollTo;
+});
+
+describe('portfolio ?shoot= on a direct load', () => {
+ it('hydrates without a mismatch and then applies the filter', async () => {
+ const { errors } = await hydrateApp(
+ '/portfolio',
+ '/portfolio?shoot=gezin',
+ );
+ await waitFor(() =>
+ expect(
+ screen.getByRole('button', { name: 'Gezin', pressed: true }),
+ ).toBeInTheDocument(),
+ );
+ expect(
+ within(screen.getByTestId('portfolio-grid')).getAllByRole('link'),
+ ).toHaveLength(2);
+ expect(errors).toEqual([]);
+ });
+
+ it('hydrates a plain /portfolio with the whole list', async () => {
+ const { errors } = await hydrateApp('/portfolio', '/portfolio');
+ expect(
+ await screen.findByRole('button', { name: 'Alles', pressed: true }),
+ ).toBeInTheDocument();
+ expect(errors).toEqual([]);
+ });
+});
+
+describe('contact ?pakket= on a direct load', () => {
+ it('hydrates without a mismatch and then preselects the package', async () => {
+ const { errors } = await hydrateApp(
+ '/contact',
+ '/contact?pakket=newborn',
+ );
+ expect(
+ await screen.findByTestId('contact-form-shoot', undefined, {
+ timeout: 10_000,
+ }),
+ ).toHaveValue('newborn');
+ expect(errors).toEqual([]);
+ });
+});
+
+describe('homepage ?pakket= on a direct load', () => {
+ it('hydrates without a mismatch and then preselects the package', async () => {
+ const { errors } = await hydrateApp('/', '/?pakket=newborn');
+ expect(
+ await screen.findByTestId('contact-form-shoot', undefined, {
+ timeout: 10_000,
+ }),
+ ).toHaveValue('newborn');
+ expect(errors).toEqual([]);
+ });
+});
diff --git a/web/src/routes/index.tsx b/web/src/routes/index.tsx
index 2037e96..2b41faf 100644
--- a/web/src/routes/index.tsx
+++ b/web/src/routes/index.tsx
@@ -13,6 +13,7 @@ import packages from '../content/packages';
import testimonials from '../content/testimonials';
import siteContent from '../content/siteContent';
import { visibleSocials } from '../lib/visibleSocials';
+import useHydrated from '../hooks/useHydrated';
import { pageHead } from '../seo';
// ?pakket= from a "Boek" link on a price card. Only text is kept; whether it
@@ -28,7 +29,10 @@ export const Route = createFileRoute('/')({
// The homepage: the hero, then the sections in the order of LAYOUT.md
function Index() {
- const { pakket } = Route.useSearch();
+ const { pakket: searched } = Route.useSearch();
+ // The search only counts after hydration, so the prerendered HTML and the
+ // first browser render agree (BR-HYD-10)
+ const pakket = useHydrated() ? searched : undefined;
// Without a valid https link the tiles would lead nowhere: no section
const instagram = visibleSocials(siteContent.socials).find(
(social) => social.platform === 'instagram',
diff --git a/web/src/routes/portfolio.tsx b/web/src/routes/portfolio.tsx
index 6fdd546..ae1e0c8 100644
--- a/web/src/routes/portfolio.tsx
+++ b/web/src/routes/portfolio.tsx
@@ -9,6 +9,7 @@ import siteContent from '../content/siteContent';
import type { ShootTypeId } from '../content/types';
import { isShootTypeId } from '../lib/portfolioFilters';
import { visibleSocials } from '../lib/visibleSocials';
+import useHydrated from '../hooks/useHydrated';
import { galleryImages, pageHead, structuredDataScript, webPage } from '../seo';
// ?shoot= from a filter or a "Bekijk meer โฆfoto's" link: only a known shoot
@@ -42,7 +43,10 @@ export const Route = createFileRoute('/portfolio')({
// The portfolio (LAYOUT.md: Intro โ Portfolio โ Instagram): the photos with
// filters and lightbox, then the same Instagram block as on the homepage
function Portfolio() {
- const { shoot } = Route.useSearch();
+ const { shoot: searched } = Route.useSearch();
+ // The filter only applies after hydration, so the prerendered HTML and the
+ // first browser render agree (BR-HYD-10)
+ const shoot = useHydrated() ? searched : undefined;
const navigate = useNavigate({ from: Route.fullPath });
const { intro, photos } = portfolioContent;
// Without a valid https link the tiles would lead nowhere: no section
diff --git a/web/src/test/hydrate.tsx b/web/src/test/hydrate.tsx
new file mode 100644
index 0000000..635110c
--- /dev/null
+++ b/web/src/test/hydrate.tsx
@@ -0,0 +1,130 @@
+import type { ReactElement, ReactNode } from 'react';
+import { ChakraProvider } from '@chakra-ui/react';
+import {
+ createMemoryHistory,
+ createRoute,
+ createRootRoute,
+ createRouter,
+ HeadContent,
+ RouterContextProvider,
+ RouterProvider,
+ rootRouteId,
+} from '@tanstack/react-router';
+import { act } from '@testing-library/react';
+import { hydrateRoot } from 'react-dom/client';
+import { renderToString } from 'react-dom/server';
+import { afterEach } from 'vitest';
+import { routerOptions } from '../router';
+import system from '../theme';
+
+// Roots still mounted at the end of a test: Testing Library does not know them
+const mounted = new Set<() => void>();
+afterEach(() => {
+ for (const unmount of [...mounted]) unmount();
+});
+
+// Plays what the browser does with a prerendered page: the server markup goes
+// into a container and React hydrates it. `errors` collects what React
+// reports as a mismatch (it recovers by client rendering and calls
+// onRecoverableError), so tests can state that there was none (BR-HYD-20).
+// The first render of the hydrating pass uses the server snapshots; the
+// effects and store updates that follow run inside act.
+export function hydrate(ui: ReactElement, markup = renderToString(ui)) {
+ const container = document.createElement('div');
+ container.innerHTML = markup;
+ document.body.append(container);
+ const errors: unknown[] = [];
+ let root!: ReturnType;
+ act(() => {
+ root = hydrateRoot(container, ui, {
+ onRecoverableError: (error) => errors.push(error),
+ });
+ });
+ const unmount = () => {
+ mounted.delete(unmount);
+ act(() => root.unmount());
+ container.remove();
+ };
+ mounted.add(unmount);
+ return { container, errors, unmount };
+}
+
+export { renderToString };
+
+// A server router at the path of the prerendered file, a browser router at
+// the URL the visitor opened: `/404` for the 404 page, the page itself with
+// the query stripped for the others. Same test shell as renderApp.
+const TestShell = ({ children }: { children: ReactNode }) => (
+ <>
+
+ {children}
+ >
+);
+
+async function appRouterAt(path: string) {
+ const router = createRouter({
+ ...routerOptions(),
+ history: createMemoryHistory({ initialEntries: [path] }),
+ });
+ const rootOptions = router.routesById[rootRouteId].options as {
+ shellComponent?: typeof TestShell;
+ };
+ rootOptions.shellComponent = TestShell;
+ await router.load();
+ return (
+
+
+
+ );
+}
+
+// renderToString cannot wait for a lazy component: it emits the fallback and a
+// client-render marker. The real prerender waits, so render again until every
+// lazy chunk (the form, the dev-only devtools) has loaded.
+async function serverMarkup(ui: ReactElement) {
+ let markup = renderToString(ui);
+ for (
+ let attempt = 0;
+ markup.includes('') && attempt < 100;
+ attempt++
+ ) {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ markup = renderToString(ui);
+ }
+ return markup;
+}
+
+export async function hydrateApp(serverPath: string, clientPath: string) {
+ const [server, client] = await Promise.all([
+ appRouterAt(serverPath),
+ appRouterAt(clientPath),
+ ]);
+ return hydrate(client, await serverMarkup(server));
+}
+
+// A component alone, inside the Chakra theme and a router that matches every
+// path (like renderWithProviders), for components that only need Link
+async function withProviders(ui: ReactElement, path: string) {
+ const rootRoute = createRootRoute();
+ const splat = createRoute({ getParentRoute: () => rootRoute, path: '$' });
+ const router = createRouter({
+ routeTree: rootRoute.addChildren([splat]),
+ history: createMemoryHistory({ initialEntries: [path] }),
+ });
+ await router.load();
+ return (
+
+ {ui}
+
+ );
+}
+
+// The HTML the prerender would write for this component
+export async function serverHtml(ui: ReactElement, path = '/') {
+ return serverMarkup(await withProviders(ui, path));
+}
+
+// Hydrates that HTML, as the browser does
+export async function hydratePage(ui: ReactElement, path = '/') {
+ return hydrate(await withProviders(ui, path), await serverHtml(ui, path));
+}
--
2.39.5
From 0b964b546639baea4e2f8930bb46aa07c7e79228 Mon Sep 17 00:00:00 2001
From: Sluijsens
Date: Sat, 31 Oct 2026 18:20:22 +0100
Subject: [PATCH 05/49] Adds a preview server that follows the real server
rules
Lighthouse and the browser tests need a real 404 status, the .html mapping and
the production headers, which vite preview does not give. It is not wired into
the scripts yet.
Co-Authored-By: Claude Opus 5.5
---
.../start-migration-code-generation-plan.md | 37 +-
.../start-migration/code/verification-log.md | 4 +-
web/config/previewServer.test.ts | 522 ++++++++++++++++++
web/config/previewServer.ts | 233 ++++++++
web/src/test/requestArbitraries.ts | 86 +++
5 files changed, 863 insertions(+), 19 deletions(-)
create mode 100644 web/config/previewServer.test.ts
create mode 100644 web/config/previewServer.ts
create mode 100644 web/src/test/requestArbitraries.ts
diff --git a/aidlc-docs/features/prerendering/construction/plans/start-migration-code-generation-plan.md b/aidlc-docs/features/prerendering/construction/plans/start-migration-code-generation-plan.md
index 320c39f..fd000b2 100644
--- a/aidlc-docs/features/prerendering/construction/plans/start-migration-code-generation-plan.md
+++ b/aidlc-docs/features/prerendering/construction/plans/start-migration-code-generation-plan.md
@@ -224,21 +224,21 @@ The unknowns that can invalidate the design come first. Steps 3 to 6 prove Start
Files are new `config/*` files and `src/test/htmlArbitraries.ts`. Config files are Dutch-commented like their neighbours. They run under Node type stripping: relative imports with `.ts`, no aliases.
-### Step 7: `config/pageFiles.ts` [ ]
+### Step 7: `config/pageFiles.ts` [x]
- Executor: Sonnet.
- Implements: BR-BLD-02, 03; domain-entities `config/pageFiles.ts`.
- Do: create the pure module with `NOT_FOUND_PATH = '/404'`, `NOT_FOUND_FILE = '404.html'`, `pageFile(path: string): string` (`/` gives `index.html`; otherwise the path without its leading slash plus `.html`) and `pagePath(file: string): string | undefined` (inverse; `undefined` for `404.html` and anything that is not a `.html` page file). Comment on why one mapping serves `vite.config.ts`, the runner and the preview server.
- Done when: `pnpm exec tsc --noEmit` clean. (Switching `vite.config.ts` to import it happens in Step 24, to keep B2 off B1's files.)
-### Step 8: `config/inlineScripts.ts` [ ]
+### Step 8: `config/inlineScripts.ts` [x]
- Executor: Sonnet.
- Implements: BR-SCR-01 to 11, 22 (nothing to build for 22); FR-PR-19, 20; D2, D3.
- Do: create the module with the exports of component-methods.md (`MovedScript`, `ExternalizeResult`, `externalizeInlineScripts`, `findExecutableInlineScripts`) and no dependency except `node:crypto` for SHA-256. Implement one internal scanner (BR-SCR-02) that yields script elements with their range, verbatim attribute text and body; the classification of flowchart 1.1 (BR-SCR-04: `src` attribute in any form, empty body, type list, `module`); the unsupported-form checks that throw (BR-SCR-05: `async`/`defer` on a classic script, `` and the form HTML sits in a hidden `S:0` div at the end of the body. It becomes visible only when the completion script runs. That script was inline before the move and is now an external classic script, so the form appears one request later than in the raw Start output, and not at all without JavaScript. Relevant for V8 and for the measurement (CLS and LCP of `/contact`).
+
+## Lighthouse on the new preview server (Step 24)
+
+Command: `pnpm exec lhci collect --config=lighthouserc.cjs --numberOfRuns=1 --url=` on a fresh `dist/client`; `lhci` starts `pnpm preview --port 4173 --strictPort` itself and stops it again. Port 4173 was free before the run. Only `collect` runs, so assertions and targets are not checked here.
+
+- `/over-mij`: exit 0, no runtime error. Performance 0.77, accessibility 1, best practices 1, SEO 1. LCP 6.2 s (score 0.11). Target for a photo page is 0.85 (see `lighthouserc.cjs`, to be checked in Step 34 under the measurement conditions).
+- `/bestaat-niet` (before the change): exit 1, `Runtime error encountered: Lighthouse was unable to reliably load the page you requested. Make sure you are testing the correct URL and that the server is properly responding to all requests. (Status code: 404)`. Cause: the preview server answers 404 for the path. The fix is in the step: `notFoundPath` is now `/404.html`.
+- `/404.html` (after the change): exit 0, no runtime error. Performance 0.80, accessibility 1, best practices 0.96, SEO 0.58. Failing audits: `errors-in-console` (score 0): React error #418 (hydration mismatch) in `index-*.js` on this page; `is-crawlable` (score 0, expected, the page is noindex); `meta-description` (score 0, expected, `404.html` has no description by design); LCP score 0.22 (5.3 s). The #418 belongs to V12 (404 hydration); Step 27 must check it again. The `assertMatrix` entry for `notFoundPath` requires best practices 1, so this URL fails that assertion until V12 is fixed; this step only checks that `collect` works.
+- `notFoundPath` change: `lighthouserc.cjs` line 22 is now `'/404.html'`. The guard test `loopt gelijk met de URLs van Lighthouse CI` in `src/app.test.tsx` now also checks it.
diff --git a/web/eslint.config.js b/web/eslint.config.js
index 9c337da..297a592 100644
--- a/web/eslint.config.js
+++ b/web/eslint.config.js
@@ -31,6 +31,12 @@ export default tseslint.config(
globals: globals.browser,
},
},
+ {
+ files: ['config/**/*.ts', 'e2e/**/*.ts', 'vitest.e2e.config.ts'],
+ languageOptions: {
+ globals: globals.node,
+ },
+ },
{
files: ['*.{js,cjs}'],
extends: [js.configs.recommended],
diff --git a/web/lighthouserc.cjs b/web/lighthouserc.cjs
index bba7cfb..020fd6b 100644
--- a/web/lighthouserc.cjs
+++ b/web/lighthouserc.cjs
@@ -19,7 +19,7 @@ const indexedPaths = [
'/contact',
];
const noindexPaths = ['/privacyverklaring'];
-const notFoundPath = '/bestaat-niet';
+const notFoundPath = '/404.html';
// Homepage mobiel voorlopig 0,8: de foto's zijn nog niet responsive en de
// titel verschijnt pas na de JavaScript. Komt terug op 0,9 met responsive
diff --git a/web/package.json b/web/package.json
index 2c80d32..7e098c9 100644
--- a/web/package.json
+++ b/web/package.json
@@ -6,8 +6,9 @@
"packageManager": "pnpm@12.11.2",
"scripts": {
"dev": "vite",
- "build": "tsc && vite build",
- "preview": "vite preview",
+ "build": "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",
"typegen": "chakra typegen ./src/theme.ts",
"typegen:watch": "chakra typegen ./src/theme.ts --watch",
@@ -19,7 +20,7 @@
"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",
- "check": "pnpm lint && pnpm format:check && pnpm test && pnpm build && pnpm audit:deps && pnpm audit:dev && pnpm lighthouse"
+ "check": "pnpm lint && pnpm format:check && pnpm test && pnpm build && pnpm e2e && pnpm audit:deps && pnpm audit:dev && pnpm lighthouse"
},
"devDependencies": {
"@chakra-ui/cli": "^3.37.0",
diff --git a/web/src/app.test.tsx b/web/src/app.test.tsx
index 716dd9e..0cae5b4 100644
--- a/web/src/app.test.tsx
+++ b/web/src/app.test.tsx
@@ -642,5 +642,8 @@ describe('pagina-register', () => {
.map(([path]) => path);
expect(lighthouseConfig.indexedPaths).toEqual(indexed);
expect(lighthouseConfig.noindexPaths).toEqual(noindex);
+ // Lighthouse weigert een 404-pagina; de preview-server geeft het
+ // bestand 404.html als bestandsverzoek met status 200 (BR-SRV-04)
+ expect(lighthouseConfig.notFoundPath).toBe('/404.html');
});
});
diff --git a/web/tsconfig.json b/web/tsconfig.json
index cad1b81..9d6f55f 100644
--- a/web/tsconfig.json
+++ b/web/tsconfig.json
@@ -24,5 +24,11 @@
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
- "include": ["src", "config", "vite.config.ts"]
+ "include": [
+ "src",
+ "config",
+ "e2e",
+ "vite.config.ts",
+ "vitest.e2e.config.ts"
+ ]
}
diff --git a/web/vite.config.ts b/web/vite.config.ts
index 8237b61..6d6de9e 100644
--- a/web/vite.config.ts
+++ b/web/vite.config.ts
@@ -1,15 +1,11 @@
-///
-import { defineConfig } from 'vite';
+import { configDefaults, defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
import { tanstackStart } from '@tanstack/react-start/plugin/vite';
+import { NOT_FOUND_FILE, NOT_FOUND_PATH } from './config/pageFiles.ts';
import { securityHeaders } from './config/securityHeaders.ts';
import sitemapPlugin from './config/sitemapPlugin.ts';
import sitePages from './src/sitePages.ts';
-// Tijdelijk hier; Stap 7 maakt config/pageFiles.ts, Stap 24 schakelt over
-const NOT_FOUND_PATH = '/404';
-const NOT_FOUND_FILE = '404.html';
-
// 100% dekking voor de pure functies (NFR-M-02); de rest wordt alleen gerapporteerd
const fullCoverage = {
statements: 100,
@@ -74,6 +70,7 @@ export default defineConfig(({ mode }) => ({
globalSetup: ['./config/testSeed.ts'],
setupFiles: ['./src/test/setup.ts'],
css: false,
+ exclude: [...configDefaults.exclude, 'e2e/**'],
coverage: {
provider: 'v8',
include: ['src/**/*.{ts,tsx}', 'config/**/*.ts'],
--
2.39.5
From 0c5d8b8f40bde0a07a7ce40fb3ddcd2e6118d09a Mon Sep 17 00:00:00 2001
From: Sluijsens
Date: Sat, 31 Oct 2026 18:30:30 +0100
Subject: [PATCH 07/49] Compresses responses in the preview server
The baseline ran on vite preview, which compresses, so measurements could not
be compared without this. Also records that the real servers need compression.
Co-Authored-By: Claude Opus 5.5
---
aidlc-docs/features/prerendering/audit.md | 12 ++
.../functional-design/business-rules.md | 2 +-
.../inception/plans/execution-plan.md | 2 +-
.../inception/requirements/requirements.md | 2 +
web/config/previewServer.test.ts | 160 +++++++++++++++++-
web/config/previewServer.ts | 57 ++++++-
6 files changed, 220 insertions(+), 15 deletions(-)
diff --git a/aidlc-docs/features/prerendering/audit.md b/aidlc-docs/features/prerendering/audit.md
index c9c2ab6..21b8ccb 100644
--- a/aidlc-docs/features/prerendering/audit.md
+++ b/aidlc-docs/features/prerendering/audit.md
@@ -215,3 +215,15 @@
**Context**: Code Generation Part 2, unit 1. Permission ends when this feature ends.
---
+
+## Code Generation - Lighthouse Comparison Finding
+
+**Timestamp**: 2026-10-31T14:15:01Z
+
+**User Input**: "(none: finding by the main session)"
+
+**AI Response**: "Step 24 measured /over-mij at 0.77 with LCP 6.2 s against the baseline 0.86 and 3.5 s. Root cause in the Lighthouse reports: the new preview server does not compress, while vite preview at the baseline did (script transfer 667 kB versus 202 kB; document 94 kB uncompressed, about 16 kB gzipped). FCP was already better at 1.66 s versus 2.60 s. Extended BR-SRV-08 with gzip. Separately, curl showed test.andreaslop.nl returns HTML and JavaScript without Content-Encoding and serverConfig.ts has no compression rules, so FR-PR-23 was added to unit 3. Lighthouse also reported React error #418 on /404.html; its root cause goes to Steps 26 and 27."
+
+**Context**: Code Generation unit 1, after Step 24.
+
+---
diff --git a/aidlc-docs/features/prerendering/construction/start-migration/functional-design/business-rules.md b/aidlc-docs/features/prerendering/construction/start-migration/functional-design/business-rules.md
index 17d933c..1a35ab3 100644
--- a/aidlc-docs/features/prerendering/construction/start-migration/functional-design/business-rules.md
+++ b/aidlc-docs/features/prerendering/construction/start-migration/functional-design/business-rules.md
@@ -211,7 +211,7 @@ Only what Lighthouse and the browser tests need. Trailing slash and `/404` are f
| BR-SRV-05 | Anything else gives `404.html` with status 404. | FR-PR-14 |
| BR-SRV-06 | The path is percent-decoded once. A path that fails to decode, contains a NUL or a backslash, or has a `..` segment gives `404.html` with 404. The returned `file` never contains `..` and is never absolute, so it cannot leave `clientDir` (SECURITY-11 misuse case). | NFR-PR-SEC-01 |
| BR-SRV-07 | Marked "final rule in unit 3 Infrastructure Design": a path with a trailing slash (interim: `404.html` with 404, no redirect in unit 1, so `{ redirect }` is not produced); the path `/404` (interim: `404.html` with status 404, not 200); `/index` and `/index.html`. | FR-PR-16 |
-| BR-SRV-08 | `startPreviewServer(clientDir, port)` answers `GET` and `HEAD`; other methods get 405. Every response, also 404, carries `securityHeaders('production')`. HTML responses send `Cache-Control: no-cache`. The content type comes from the file extension (html, js, css, svg, png, jpg, webp, woff2, ico, xml, txt, json). It binds to `127.0.0.1`. `pnpm preview` runs it with default port 4173, accepts the `--port` and `--strictPort` arguments that `lighthouserc.cjs` passes (or that command changes with it), and prints a line matching its `startServerReadyPattern`. | NFR-PR-SEC-01; D10 |
+| BR-SRV-08 | `startPreviewServer(clientDir, port)` answers `GET` and `HEAD`; other methods get 405. Every response, also 404, carries `securityHeaders('production')`. HTML responses send `Cache-Control: no-cache`. Text responses (HTML, JavaScript, CSS, SVG, JSON, XML, TXT) are gzip-compressed when the request accepts gzip, with `Vary: Accept-Encoding`, because the baseline ran on `vite preview`, which compresses; without this the measurements cannot be compared (found in Step 24: script transfer 667 kB versus 202 kB). The content type comes from the file extension (html, js, css, svg, png, jpg, webp, woff2, ico, xml, txt, json). It binds to `127.0.0.1`. `pnpm preview` runs it with default port 4173, accepts the `--port` and `--strictPort` arguments that `lighthouserc.cjs` passes (or that command changes with it), and prints a line matching its `startServerReadyPattern`. | NFR-PR-SEC-01; D10 |
### BR-TST: Tests
diff --git a/aidlc-docs/features/prerendering/inception/plans/execution-plan.md b/aidlc-docs/features/prerendering/inception/plans/execution-plan.md
index 0662d1a..74eadef 100644
--- a/aidlc-docs/features/prerendering/inception/plans/execution-plan.md
+++ b/aidlc-docs/features/prerendering/inception/plans/execution-plan.md
@@ -152,7 +152,7 @@ Text alternative: after Workflow Planning come Application Design, Functional De
|---|---|---|---|
| 1. Start migration and script step | Start setup, entry and root document, head tags, post-build script step and guard, hydration of all pages, Sentry and Umami, tests, CI output path and preview | FR-PR-01 to 08, 19, 20, 22; catch-all route of FR-PR-14 and 15; NFR-PR-P-03, P-04, S-02, SEC-01 to 04, Q-01 to 05 | None |
| 2. Fade-in, no JavaScript, first photo | `Reveal`, `DeferredImage`, mobile menu without JavaScript, carousels and form fallback, photo preload | FR-PR-09 to 13, 21 | Unit 1 |
-| 3. Hosting and targets | URLs without a redirect, real 404, nginx and IIS configuration, upload order, Lighthouse targets | FR-PR-14 to 18; NFR-PR-P-01, P-02, S-01 | Units 1 and 2 |
+| 3. Hosting and targets | URLs without a redirect, real 404, nginx and IIS configuration, upload order, Lighthouse targets | FR-PR-14 to 18, 23; NFR-PR-P-01, P-02, S-01 | Units 1 and 2 |
**Decision gate after unit 1 (NFR-PR-P-03)**: bundle size and Lighthouse scores are measured against master and shown to the owner. If they got worse, the owner decides whether to continue with Start before units 2 and 3 start.
diff --git a/aidlc-docs/features/prerendering/inception/requirements/requirements.md b/aidlc-docs/features/prerendering/inception/requirements/requirements.md
index 5041ac6..229e292 100644
--- a/aidlc-docs/features/prerendering/inception/requirements/requirements.md
+++ b/aidlc-docs/features/prerendering/inception/requirements/requirements.md
@@ -91,6 +91,8 @@ Text alternative: Start renders each page to HTML, a post-build step moves inlin
- **FR-PR-17**: Only the client output is deployed to test and production. The Node server output from the build is never uploaded.
- **FR-PR-18**: During a production upload, a visitor never receives HTML that refers to a file not yet present. The existing order (assets first, then HTML, then cleanup) must cover all HTML files instead of only `index.html`. HTML stays uncached and hashed assets stay long-cached.
+- **FR-PR-23**: nginx and IIS serve text responses (HTML, JavaScript, CSS, SVG, JSON, XML) compressed. Measured on 2026-10-31: `test.andreaslop.nl` returned HTML and JavaScript without `Content-Encoding` and the generated server configuration has no compression rules; the cause on the test host (nginx or its reverse proxy) is settled in Infrastructure Design. Added by the main session as a consequence of the goal; the owner can overrule it.
+
### Inline scripts
- **FR-PR-19**: A post-build step moves every executable inline script in the generated HTML to a file in `/assets`, preserving execution order. JSON-LD data blocks stay inline, provided a browser test confirms the CSP does not block them.
diff --git a/web/config/previewServer.test.ts b/web/config/previewServer.test.ts
index 25c00f4..fc8402b 100644
--- a/web/config/previewServer.test.ts
+++ b/web/config/previewServer.test.ts
@@ -5,6 +5,7 @@ import { createServer } from 'node:net';
import { tmpdir } from 'node:os';
import { dirname, join, posix, win32 } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { gunzipSync } from 'node:zlib';
import fc from 'fast-check';
import { afterEach, describe, expect, it } from 'vitest';
import {
@@ -16,6 +17,7 @@ import {
} from '../src/test/requestArbitraries';
import { securityHeaders } from './securityHeaders';
import {
+ acceptsGzip,
contentTypeOf,
resolveRequest,
startPreviewServer,
@@ -263,27 +265,42 @@ describe('contentTypeOf', () => {
});
});
+// Groot genoeg voor meerdere stukken in de stroom, en ook niet-ASCII
+const GROOT_SCRIPT = 'const tekst = "hรฉllo wรถrld โ";\n'.repeat(5000);
+// Geen geldige UTF-8: de bytes moeten ongewijzigd aankomen
+const BINARY = Buffer.from(Array.from({ length: 2000 }, (_, i) => i % 256));
+const GZIP = { 'Accept-Encoding': 'gzip, deflate, br' };
+
interface Answer {
status: number;
headers: Record;
body: string;
+ // De ontvangen bytes, voor gzip en binaire bestanden
+ raw: Buffer;
}
// node:http in plaats van fetch: die laat het pad ongemoeid, ook '..'
-const ask = (port: number, path: string, method = 'GET'): Promise =>
+const ask = (
+ port: number,
+ path: string,
+ method = 'GET',
+ headers: Record = {},
+): Promise =>
new Promise((resolve, reject) => {
const req = request(
- { host: '127.0.0.1', port, path, method },
+ { host: '127.0.0.1', port, path, method, headers },
(response) => {
const chunks: Buffer[] = [];
response.on('data', (chunk: Buffer) => chunks.push(chunk));
- response.on('end', () =>
+ response.on('end', () => {
+ const raw = Buffer.concat(chunks);
resolve({
status: response.statusCode ?? 0,
headers: response.headers,
- body: Buffer.concat(chunks).toString('utf8'),
- }),
- );
+ body: raw.toString('utf8'),
+ raw,
+ });
+ });
},
);
req.on('error', reject);
@@ -313,6 +330,9 @@ function siteDir(): string {
writeFileSync(join(clientDir, 'over-mij.html'), '
');
+ });
+
+ it('stuurt bij HEAD de gzip-headers maar geen inhoud', async () => {
+ const port = await serve(siteDir());
+ const answer = await ask(port, '/assets/groot.js', 'HEAD', GZIP);
+ expect(answer.status).toBe(200);
+ expect(answer.raw.length).toBe(0);
+ expect(answer.headers['content-encoding']).toBe('gzip');
+ expect(answer.headers['vary']).toBe('Accept-Encoding');
+ expect(answer.headers['content-length']).toBeUndefined();
+ });
+
+ it('houdt de securityheaders ook op gecomprimeerde antwoorden', async () => {
+ const port = await serve(siteDir());
+ const { headers } = await ask(port, '/over-mij', 'GET', GZIP);
+ for (const [name, value] of Object.entries(
+ securityHeaders('production'),
+ )) {
+ expect(headers[name.toLowerCase()], name).toBe(value);
+ }
+ });
+});
+
describe('previewServer als opdrachtregel', () => {
const script = join(
dirname(fileURLToPath(import.meta.url)),
diff --git a/web/config/previewServer.ts b/web/config/previewServer.ts
index cfc3402..fb37de4 100644
--- a/web/config/previewServer.ts
+++ b/web/config/previewServer.ts
@@ -14,6 +14,7 @@ import {
} from 'node:http';
import { extname, join, resolve, sep, win32 } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { createGzip } from 'node:zlib';
import { NOT_FOUND_FILE, pageFile } from './pageFiles.ts';
import { securityHeaders } from './securityHeaders.ts';
@@ -92,6 +93,41 @@ const CONTENT_TYPES: Record = {
export const contentTypeOf = (file: string): string =>
CONTENT_TYPES[extname(file).toLowerCase()] ?? 'application/octet-stream';
+// Tekst wordt gecomprimeerd, afbeeldingen en lettertypen niet (die zijn het al).
+// Waarom: de nulmeting draaide op `vite preview`, dat comprimeert; zonder dit
+// zijn de Lighthouse-metingen niet te vergelijken (scripts: 667 kB tegen
+// 202 kB, gevonden in stap 24). Productie comprimeert op de host (BR-SRV-08).
+const COMPRESSIBLE = new Set([
+ '.html',
+ '.js',
+ '.css',
+ '.svg',
+ '.json',
+ '.xml',
+ '.txt',
+]);
+
+export const isCompressible = (file: string): boolean =>
+ COMPRESSIBLE.has(extname(file).toLowerCase());
+
+// Staat gzip in Accept-Encoding? 'gzip;q=0' weigert het, '*' staat het toe,
+// tenzij gzip zelf genoemd is
+export function acceptsGzip(header: string | undefined): boolean {
+ if (!header) return false;
+ let gzip: number | undefined;
+ let star: number | undefined;
+ for (const part of header.split(',')) {
+ const [name, ...params] = part.trim().toLowerCase().split(';');
+ const q = params
+ .map((param) => /^\s*q\s*=\s*([0-9.]+)\s*$/.exec(param))
+ .find(Boolean);
+ const weight = q ? Number(q[1]) : 1;
+ if (name === 'gzip') gzip = weight;
+ else if (name === '*') star = weight;
+ }
+ return (gzip ?? star ?? 0) > 0;
+}
+
// Alleen het pad: query en hash horen niet bij het bestand. Bewust niet via
// `new URL`, want die haalt '..' al weg en dan ziet resolveRequest het niet.
const pathOf = (target: string) => target.split(/[?#]/, 1)[0];
@@ -151,15 +187,22 @@ export function startPreviewServer(
}
const headers: Record = {
'Content-Type': contentTypeOf(file),
- 'Content-Length': statSync(target).size,
};
if (file.endsWith('.html')) headers['Cache-Control'] = 'no-cache';
- send(
- response,
- status,
- headers,
- request.method === 'HEAD' ? null : createReadStream(target),
- );
+ // Gzip als stroom: de lengte is vooraf niet bekend, dus dan geen
+ // Content-Length (chunked); ook niet bij HEAD, dat geen inhoud stuurt
+ const compressible = isCompressible(file);
+ const gzip =
+ compressible && acceptsGzip(request.headers['accept-encoding']);
+ if (compressible) headers['Vary'] = 'Accept-Encoding';
+ if (gzip) headers['Content-Encoding'] = 'gzip';
+ else headers['Content-Length'] = statSync(target).size;
+ let body: NodeJS.ReadableStream | null = null;
+ if (request.method !== 'HEAD') {
+ body = createReadStream(target);
+ if (gzip) body = body.pipe(createGzip());
+ }
+ send(response, status, headers, body);
};
return new Promise((resolvePromise, reject) => {
--
2.39.5
From 8bf00005316406fc32780d2003fdb14564874dcc Mon Sep 17 00:00:00 2001
From: Sluijsens
Date: Sat, 31 Oct 2026 19:03:07 +0100
Subject: [PATCH 08/49] Adds browser tests and fixes hydration of the 404 page
The prerendered 404 page is served for other URLs, so its dehydrated match id
differs and the router renders the catch-all's pending component first. Without
one that render was empty, which gave React error 418 and duplicate head tags.
The tests run the built output in a real browser under the production CSP.
Co-Authored-By: Claude Opus 5.5
---
.../start-migration-code-generation-plan.md | 6 +-
.../start-migration/code/verification-log.md | 40 ++-
web/e2e/hydration.e2e.ts | 328 ++++++++++++++++++
web/e2e/interaction.e2e.ts | 262 ++++++++++++++
web/e2e/rawHtml.e2e.ts | 157 +++++++++
web/e2e/smoke.e2e.ts | 30 ++
web/e2e/support/browser.ts | 136 ++++++++
web/e2e/support/globalSetup.ts | 12 +
web/e2e/support/server.ts | 24 ++
web/src/prerender.test.tsx | 70 ++++
web/src/routes/$.tsx | 17 +-
web/src/routes/hydration.test.tsx | 32 +-
web/src/test/hydrate.tsx | 71 +++-
web/src/test/setup.ts | 60 ++--
web/vitest.e2e.config.ts | 19 +
15 files changed, 1216 insertions(+), 48 deletions(-)
create mode 100644 web/e2e/hydration.e2e.ts
create mode 100644 web/e2e/interaction.e2e.ts
create mode 100644 web/e2e/rawHtml.e2e.ts
create mode 100644 web/e2e/smoke.e2e.ts
create mode 100644 web/e2e/support/browser.ts
create mode 100644 web/e2e/support/globalSetup.ts
create mode 100644 web/e2e/support/server.ts
create mode 100644 web/src/prerender.test.tsx
create mode 100644 web/vitest.e2e.config.ts
diff --git a/aidlc-docs/features/prerendering/construction/plans/start-migration-code-generation-plan.md b/aidlc-docs/features/prerendering/construction/plans/start-migration-code-generation-plan.md
index 2bd458e..c37604b 100644
--- a/aidlc-docs/features/prerendering/construction/plans/start-migration-code-generation-plan.md
+++ b/aidlc-docs/features/prerendering/construction/plans/start-migration-code-generation-plan.md
@@ -402,7 +402,7 @@ Disjoint from B2 and B4. Runs only targeted `vitest run` commands. The editing o
- Done when: **CP3**: `pnpm build` succeeds, the runner prints its success line (this requires Steps 17 and 21 done, otherwise EMAIL_IN_OUTPUT fails the build, which is the check working). Port 4173 and CPU rules of Step 2 apply to item 5.
- Record: verification log notes under V5, V7, and the lighthouse finding.
-### Step 25: Prerender-safety test (BR-TST-07) [ ]
+### Step 25: Prerender-safety test (BR-TST-07) [x]
- Executor: Sonnet.
- Implements: BR-TST-07; FR-PR-05; NFR-PR-Q-03 (fast feedback).
@@ -410,7 +410,7 @@ Disjoint from B2 and B4. Runs only targeted `vitest run` commands. The editing o
- Do: for every key of `sitePages` plus an unknown path, create a router with memory history from `routerOptions()`, await `router.load()`, render with `react-dom/server` inside `ChakraProvider`, and expect no throw and a non-empty string containing the page's `
`. This catches `window`/`document` use in render paths. If it cannot be made to work with the shell, drop the shell from the test as in Step 5. Feasibility is the open point: if the Chakra provider or the router cannot render in a Node environment at all, record "not feasible, the build's own prerender is the guard" in the verification log and replace the test by a documented skip-free alternative (a test that scans nothing is not acceptable): in that case STOP and report instead of deleting the step. Add the assertion that the server HTML of `/contact` has no assembled address.
- Done when: `pnpm exec vitest run src/prerender.test.tsx` passes.
-### Step 26: e2e harness and smoke test [ ]
+### Step 26: e2e harness and smoke test [x]
- Executor: Sonnet.
- Implements: BR-TST-05 (harness); D11; NFR-PR-Q-03; V1 (browser side), V8 early.
@@ -422,7 +422,7 @@ Disjoint from B2 and B4. Runs only targeted `vitest run` commands. The editing o
- `smoke.e2e.ts`: `/` and `/contact` and `/onbekend`: page loads under the production CSP, the heading is visible, zero console errors/warnings and zero CSP violations. This is the first real-browser proof; if it fails with hydration or CSP errors, analyse; failures that need a design change: STOP.
- Done when: `pnpm build && pnpm e2e` passes locally (Chrome must be installed or `CHROME_PATH` set; if no browser is available on this machine, STOP and ask the main session instead of skipping).
-### Step 27: Full e2e tests (BR-TST-05, BR-TST-06; V8, V9, V10, V11, V12, V14, V15, V16, V17) [ ]
+### Step 27: Full e2e tests (BR-TST-05, BR-TST-06; V8, V9, V10, V11, V12, V14, V15, V16, V17) [x]
- Executor: Sonnet.
- Implements: BR-TST-05, 06; BR-HYD-17, 20, 21; BR-LZY-01, 05; BR-404-03, 04, 05, 07; BR-ENT-06; BR-MAIL-10; FR-PR-05 to 08, 14, 15, 22; NFR-PR-S-02, SEC-01, Q-03, Q-04; PBT: "No PBT properties identified" (browser flows).
diff --git a/aidlc-docs/features/prerendering/construction/start-migration/code/verification-log.md b/aidlc-docs/features/prerendering/construction/start-migration/code/verification-log.md
index 6100509..eca8c2b 100644
--- a/aidlc-docs/features/prerendering/construction/start-migration/code/verification-log.md
+++ b/aidlc-docs/features/prerendering/construction/start-migration/code/verification-log.md
@@ -32,18 +32,42 @@ Notes:
| V5 | `index.html` written, crawling off | 4 | `/` is written as `index.html` with `autoSubfolderIndex: false`; `/x` as `x.html`, `/soorten-fotoshoots/x` as `soorten-fotoshoots/x.html`. Option names (from the `start-plugin-core` schema): `prerender.crawlLinks: false` and `prerender.autoStaticPathsDiscovery: false` (the latter stops Start adding static routes by itself), page list from `Object.keys(sitePages)` plus `{ path: '/404', prerender: { outputPath: '/404.html' } }`. | Prerender log: "Prerendered 12 pages". `find dist/client -name '*.html'` gives exactly 404, index, over-mij, portfolio, privacyverklaring, contact, soorten-fotoshoots and five `soorten-fotoshoots/.html` (12 files, no others). Step 24: `pnpm build` (tsc, vite build, runner) exits 0 with the same 12 pages; `vite.config.ts` now takes `NOT_FOUND_PATH` and `NOT_FOUND_FILE` from `config/pageFiles.ts`. | OK |
| V6 | Code splitting; router plugin unused | 4 (30 later) | Start's plugin includes `tanstackRouterGenerator` and `tanStackRouterCodeSplitter` itself (client and server environments), so route code splitting is on without an option and `@tanstack/router-plugin` is not needed as a direct dependency. Removed with `pnpm remove @tanstack/router-plugin`; only Start's own copy (1.168.48) remains. | Client build has one chunk per route (`over-mij-*.js`, `contact-*.js`, `portfolio-*.js`, `newborn-*.js`, ..., `_-*.js` for the catch-all), plus `ContactForm`, `Lightbox`, `TestimonialCarousel` chunks. Step 30 re-checks. | OK |
| V7 | Sitemap in the client environment only | 4 | `this.environment.name === 'client'` identifies the client build in `generateBundle` (Vite 8.3.1, Start environments `client` and `ssr`). | `dist/client/sitemap.xml` exists once (10 ``, no `/privacyverklaring`, no `/404`); `find dist -name sitemap.xml` gives only that file; `public/` has no `sitemap.xml`. Step 24: the same build gives the runner line `Inline scripts verplaatst: 12 pagina's gecontroleerd, 16 scripts verplaatst, 28 bestanden geschreven` (no violations), and `dist` keeps the sitemap in the client build only. | OK |
-| V8 | Lazy `ContactForm` in HTML and hydration | 27 | open (first look: `contact.html` contains `data-testid="contact-form"` and its fields; `/contact` hydrates in Chrome without console output) | | open |
-| V9 | Testimonials in HTML, hidden slides | 21, 27 | Code part (step 18, 21): `renderToString` of `Testimonials` holds the quote of every visible review; the copies besides the longest sit in a `VisuallyHidden` wrapper with `aria-hidden` and `inert`; axe has no violations in jsdom with the placeholder showing. Layout and reading order in a browser: step 27. | `Testimonials.test.tsx` (4 new tests) | open |
+| V8 | Lazy `ContactForm` in HTML and hydration | 27 | What is true (differs from the plan text and BR-LZY-01 "the form fields are in the HTML inside the gate"): the prerender waits for the lazy chunk, so the form and its fields (`data-testid="contact-form"`, `contact-form-shoot`, ...) are in the bytes of `contact.html`, but as a streamed Suspense segment, not in place. In `` the gate holds `` plus the empty `FORM_PLACEHOLDER_HEIGHT` box; the form sits in `
` at the end of the body, and React's completion runtime (`$RC("B:0","S:0")`, moved to an external script by the runner) moves it into place. Without JavaScript the form is therefore in the HTML but not visible (`isVisible` false); FR-PR-13 allows that. With JavaScript, under the production CSP and the moved scripts, the form appears inside `main`, there is no `securitypolicyviolation` and no console message or hydration error. A late chunk is safe too (BR-LZY-05): with the `ContactForm-*.js` request held back 1500 ms, the page hydrates without any message and the form appears. | `e2e/hydration.e2e.ts` "contactformulier op /contact (V8)", 3 tests, pass; also the 390 and 1280 px page tests of `/contact`. | OK (BR-LZY-01 text to be corrected: fields are in the HTML only as the hidden streamed segment) |
+| V9 | Testimonials in HTML, hidden slides | 21, 27 | Code part (step 18, 21): `renderToString` of `Testimonials` holds the quote of every visible review; the copies besides the longest sit in a `VisuallyHidden` wrapper with `aria-hidden` and `inert`; axe has no violations in jsdom with the placeholder showing. Browser part (step 27): the raw HTML of `/` contains the quote and author of every visible review. Measured at 390 px with and without JavaScript: the longest review is 350 x 533 px in the flow, the other copy is 1 x 1 px, `aria-hidden` and `inert`; the testimonials section is 840 px high in both cases (no layout change at hydration while the carousel has not loaded). Reading order: the hidden copies are out of the accessibility tree, so each review is read once. | `Testimonials.test.tsx` (4 new tests); `e2e/rawHtml.e2e.ts` "reviews op de homepage"; `e2e/interaction.e2e.ts` "reviews voor het laden van de carrousel (V9)" | OK |
| V10 | Placeholder sizes, CLS below 0.01 | 17, 34 | First estimates (step 17), not measured: footer item `minH` 44px below `lg`, `1lh` from `lg` (one line of the list item); contact card item `minH` 44px; gate notice inline block `38ch` (lead " Mail me voor nu op " 20 + address 18 characters, from the parts without assembling) plus a hidden button with the recipe and label. To be measured in 27 and 34. | `Footer.tsx`, `ContactDetails.tsx`, `ContactFormGate.tsx` | open |
-| V11 | One title, one noindex meta | 4 (normal pages), 27 (`404.html`) | Normal pages in the prerendered HTML: one ``, one `description`, one `canonical`, no `data-fallback`, a robots meta only on `/privacyverklaring`. `404.html`: one `` ("Pagina niet gevonden \| Andrea Slop Fotografie") and one ``, no description or canonical. React writes `` with a capital S (valid, attribute names are case-insensitive). | `scripts.mjs` counts per file. After hydration in Chrome: `/`, `/over-mij`, `/contact` still 1 title. Caution for Step 27: `/soorten-fotoshoots/onbekend` showed 2 titles and 2 robots metas after React error #418 (the two extra 404 buttons render before hydration; Step 16 fixes that); `/onbekend` is clean. | OK (normal pages); `404.html` source OK, final check in 27 |
-| V12 | 404 hydration with real shell | 27 | open (first look, before Step 16: `/onbekend` hydrates clean; `/soorten-fotoshoots/onbekend` gives #418, which Step 16 `hydrated && isShootSectionPath` should remove) | | open |
+| V11 | One title, one noindex meta | 4 (normal pages), 27 (`404.html`) | Normal pages in the prerendered HTML: one ``, one `description`, one `canonical`, no `data-fallback`, a robots meta only on `/privacyverklaring`. `404.html`: one `` ("Pagina niet gevonden \| Andrea Slop Fotografie") and one ``, no description or canonical. React writes `` with a capital S (valid, attribute names are case-insensitive). | `scripts.mjs` counts per file. After hydration in Chrome: `/`, `/over-mij`, `/contact` still 1 title. Caution for Step 27: `/soorten-fotoshoots/onbekend` showed 2 titles and 2 robots metas after React error #418 (the two extra 404 buttons render before hydration; Step 16 fixes that); `/onbekend` is clean. | OK (final check in Step 27, see the V11 paragraph below the table) |
+| V12 | 404 hydration with real shell | 27 | Found and fixed. With the real shell (navigation, footer, e-mail placeholders) the 404 HTML for `/404` hydrated at another URL gave React #418 in a race, reproducible below 1024 px width and under CPU or network delay (Lighthouse). Root cause and fix: "404 hydration error #418" below the table (`pendingComponent` of the catch-all route equals its component). After the fix `/404.html`, `/404`, `/onbekend`, `/soorten-fotoshoots/onbekend` give no console message, no CSP violation, one title and one robots meta at 390 and 1280 px, and also with the route chunk delayed by 800 ms; `/soorten-fotoshoots/onbekend` shows one button without JavaScript and two extra after hydration. | `e2e/hydration.e2e.ts` (48 tests); `src/routes/hydration.test.tsx` (4 new tests with `hydrateAppAsStart`). Without the fix 5 e2e tests and 4 unit tests fail. | OK |
| V13 | Timestamps and build paths | 4, 13 | Repeated on the final output of the runner (HTML plus the 16 moved script files plus all JS/CSS/XML/TXT/JSON): no build timestamp (`YYYY-MM-DDTHH:MM`) in any text file, no `.map` file, no repository root path (forward slashes, backslashes or doubled backslashes) in any text file. File names are content hashes, so they cannot carry a timestamp. | Scan in the scratch run (`repoPathFiles: 0`, `timestampFiles: 0`, `maps: 0`); the runner's own BUILD_PATH_LEAK check reported nothing. | OK |
-| V14 | Focus on first load, tidy navigation | 27 | open | | open |
-| V15 | Emotion/Chakra flicker | 4 (styles in HTML), 27 (screenshots) | Styles are in the HTML: ``. Rendered by the root shell after `HeadContent`. Renders the same on both sides; the browser ignores the children (BR-IMG-03). |
+| `src/components/NavigationBar/NoScriptNav.tsx` | `NoScriptMenuOpen()`: `