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`. `<html lang="nl">`, 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 `<style>` is allowed by `style-src 'unsafe-inline'`); the first paint shows no unstyled content. | NFR-PR-Q-04 | +| BR-BLD-08 | The Start plugin is not part of the Vitest configuration. `@tanstack/router-plugin` is replaced by Start's own generator; `routeTree.gen.ts` stays generated, committed and excluded from coverage. Route code splitting stays on. | D12; NFR-PR-P-03 | +| BR-BLD-09 | `sitemap.xml` is emitted by `sitemapPlugin` in the client build only, so that it ends up in `dist/client` exactly once. The runner checks that the file exists and equals `sitemapXml(pageList(sitePages), siteUrl)` (SITEMAP_MISSING, SITEMAP_DIFFERS). | FR-PR-04 | +| BR-BLD-10 | The CI job uploads `web/dist/client/` as the build artifact so that later jobs receive `index.html` at the artifact root as today. Upload order and server rules are unit 3. | FR-PR-17; unit boundaries | +| BR-BLD-11 | New packages are in `pnpm-lock.yaml` and pass `pnpm audit:deps`. The `seroval` and `seroval-plugins` overrides in `pnpm-workspace.yaml` stay. Packages no longer used (for instance `@tanstack/router-plugin` if Start replaces it) are removed. | NFR-PR-SEC-02 | +| BR-BLD-12 | Header comments in `inlineScripts.ts`, `externalizeInlineScripts.ts` and `previewServer.ts` explain why the step exists (strict `script-src 'self'`, Start emits inline scripts). The lines of this feature in `_shared/reverse-engineering/` are updated (entry, build, output, test setup). | NFR-PR-Q-05 | + +### BR-ENT: Entry, router and document + +| Id | Rule | Source | +|---|---|---| +| BR-ENT-01 | `getRouter()` in `src/router.tsx` returns a new router per call with the options of `main.tsx` today: `routeTree`, `scrollRestoration: true`, `defaultErrorComponent: ErrorPage`. The options come from one shared function that `renderApp` also uses. | FR-PR-07; D12 | +| BR-ENT-02 | The root route renders the document through `shellComponent`: `<html lang="nl">`, `<head>` with `HeadContent`, `<body>` with `ChakraProvider value={system}` around the children and `Scripts` last. The site stays light only. | D6; main.tsx comment | +| BR-ENT-03 | `src/client.tsx` calls `startSentry()` first and hydrates second, inside `StrictMode` as `main.tsx` does today. The server never imports it. | FR-PR-08; D13 | +| BR-ENT-04 | Root `notFoundComponent` and `errorComponent` stay. `ErrorPage` shows no error text (BR-ERR-02/03 of the shell feature stay). | FR-PR-07; NFR-PR-SEC-03 | +| BR-ENT-05 | A prerender error fails the build. No page is ever written from an error render. | SECURITY-15 | +| BR-ENT-06 | Client navigation, scroll restoration, focus move on route change (`useRouteFocus`, not on first load and not on query or hash change) and `/?pakket=...#contact` anchors behave as today; the e2e tests cover each. | FR-PR-07 | + +### BR-HYD: Hydration + +| Id | Rule | Source | +|---|---|---| +| BR-HYD-01 | Principle: the first browser render produces the same markup as the prerendered HTML. Anything that depends on `window`, `document`, the URL search, hash or pathname, media queries, time, storage, observers or random values is applied after hydration. `suppressHydrationWarning` and `typeof window` branches in render are not used. | FR-PR-05; D6 | +| BR-HYD-02 | `useHydrated()` is `useSyncExternalStore(subscribeNoop, () => true, () => false)`. It returns `false` during prerender and during the hydrating render, `true` in the next render, and `true` from the first render of any component that mounts later (client navigation, tests with `createRoot`). | D6 | +| BR-HYD-03 | Browser capabilities read by our own hooks go through `useSyncExternalStore` with a server snapshot equal to what the HTML shows. This keeps behaviour for components that mount after hydration (no extra render, existing tests unchanged) and needs no `setState` in an effect. | D6 | +| BR-HYD-04 | `usePageLoaded`: store snapshot `document.readyState === 'complete'`, subscribed to the window `load` event, server snapshot `false`. | FR-PR-05 | +| BR-HYD-05 | `useInView`: the contract "without `IntersectionObserver` the element counts as in view" stays. `unsupported` is a store value (`typeof IntersectionObserver === 'undefined'`, server snapshot `false`). `inView = skip \|\| intersected \|\| unsupported`. First render therefore returns `skip` on both sides; the observer is created in the effect as today. | FR-PR-05 | +| BR-HYD-06 | `useScrolledPast` needs no change: it reads `window` only in its effect and starts at `false`. | verified | +| BR-HYD-07 | Chakra `useMediaQuery` and `useBreakpointValue` are called with the default `ssr` (true) everywhere. With `ssr: false` Chakra reads `window.matchMedia` in the `useState` initialiser, which throws during prerender and returns the real value in the first browser render. With the default, the first render returns `fallback` (none given, so `false`) for each query on both sides and an effect then sets the real values. Applies to `useReveal`, `useHeroSlider`, `ContactSection`, `TestimonialCarousel` and `NavigationBar`. No `{ ssr: false }` remains in `src`. | FR-PR-05 | +| BR-HYD-08 | First-render values: `useMediaQuery(['(prefers-reduced-motion: reduce)'])` gives `false`. `NavigationBar` `useBreakpointValue({ base: false, lg: true })` gives `false` (its existing `viewport` dispatch in an effect applies the real value; the mobile and desktop layouts are CSS only). `IntroGallery` `useBreakpointValue({ base: true, sm: false })` gives `true` (the `base` value), so the list carries `tabIndex={0}` in the HTML and loses it after hydration from `sm` up. | FR-PR-05 | +| BR-HYD-09 | `useHeroSlider`: `hidden` is a store value (`document.hidden`, event `visibilitychange`, server snapshot `false`). `document.hidden` is no longer read in a `useState` initialiser. | FR-PR-05 | +| BR-HYD-10 | `routes/index.tsx`, `routes/contact.tsx` and `routes/portfolio.tsx`: the search value passed to the page is `hydrated ? search.pakket : undefined` (portfolio: `search.shoot`). `validateSearch` is unchanged. Prerender and first browser render therefore both use "no search". | FR-PR-06; D6 | +| BR-HYD-11 | After the search value takes effect the existing behaviour is unchanged. Contact page: the tidy effect (`navigate({ to: '/contact', search: {}, replace: true })`) runs when `pakket` becomes defined, so one render later than today on a direct load and at once on client navigation (`hydrated` is already `true`). Home: the `ContactSection` effect behaves the same, with the smooth scroll to `#contact`. Portfolio: `onShootChange` navigation (`replace`, `resetScroll: false`) is only reachable after hydration. | FR-PR-06, 07 | +| BR-HYD-12 | On a direct load of `/portfolio?shoot=gezin` the HTML and first paint show all photos with filter "Alles"; the filter applies right after hydration (accepted consequence in the application design). `PortfolioGallery` closes the lightbox when the list changes (its `listFor` adjustment) and needs no change. | FR-PR-06 | +| BR-HYD-13 | `NotFound` shows the two shoot-section buttons only when `hydrated && isShootSectionPath(pathname)`. See BR-404. | FR-PR-15 | +| BR-HYD-14 | `Footer` year: the first render uses `BUILD_YEAR`, a constant that `vite.config.ts` defines once per build (`import.meta.env.VITE_BUILD_YEAR`, the year of the build machine at build start) so that server and client bundles agree. After hydration the line uses `new Date().getFullYear()`. A page built in December therefore stays valid after new year without a rebuild. In tests (`createRoot`) the real year shows at once. | FR-PR-05 | +| BR-HYD-15 | `UmamiAnalytics` reads its default hostname inside its effect, not in a default parameter evaluated during render. It renders `null`. | FR-PR-08 | +| BR-HYD-16 | `ContactForm` `shownAt = useState(() => Date.now())` is not rendered, and React state is not carried from server to client. The timer starts when the component first renders in the browser, which is when the form can first be used. A prerendered time can therefore never shorten the minimum fill time (`MIN_FILL_MS`). No change. | FR-PR-05; BR-SPAM-01 | +| BR-HYD-17 | Prices come from `formatPrice` (`Intl.NumberFormat('nl-NL')`, whitespace replaced by a non-breaking space). Node and browser must produce identical text; the e2e hydration test on `/` and the shoot pages fails on a difference. | FR-PR-05 | +| BR-HYD-18 | No render path uses `Math.random`, `Date.now`, `new Date`, counters or `crypto` for ids or text (verified: only BR-HYD-14 and BR-HYD-16). `useId` is not called in `src`; Chakra and Ark call it internally and are stable as long as both sides render the same tree, which BR-HYD-01 to 17 guarantee. | FR-PR-05 | +| BR-HYD-19 | Effects that touch `window` or `document` (`BackToTop`, `MobileNav`, `NavSubmenu`, `useDismiss`, `useRouteFocus`, `Hero`, `Lightbox`, `ContactForm`) are safe and stay. `Lightbox` mounts only after a request, so its `Portal` is not part of the HTML. | verified | +| BR-HYD-20 | A hydration error is a defect. The e2e tests fail on any console error or warning (React error #418, #423, #425 and the like) on every page and variant listed in BR-TST-05. | FR-PR-05; NFR-PR-Q-03 | +| BR-HYD-21 | Router `Link` computes its active state from the browser location in its first render. On `/?pakket=gezin` the book link of that package card (`PriceCard`: `to="/" search={{ pakket }}`) is active in the browser but not in the HTML, which differs only in attributes (`aria-current`, `data-status`, class). React's production build does not report attribute differences and the tidy navigation of `ContactSection` removes the search at once, so this is accepted; the link keeps its `href` with the search (it must work without JavaScript). The e2e tests run against the production build. If a React or Router upgrade starts reporting it, the card link must render without depending on the location. | FR-PR-05, 06 | + +### BR-MAIL: The e-mail address + +Owner decision: the address stays out of the HTML and the serialized data and appears after hydration. + +| Id | Rule | Source | +|---|---|---| +| BR-MAIL-01 | The assembled address (`user@domain`) and any `mailto:` link to it exist only in the browser after hydration. No component outputs it in the first render. Components get it through `useEmailAddress(email)`, which returns `{ available, address }`: `available` is `isEmailAddressValid(email)` (same on both sides, no assembly); `address` is `emailAddress(email)` when `hydrated && available`, else `null`. | FR-PR-22 | +| BR-MAIL-02 | Three states per slot. `!available`: nothing is rendered, as today (BR-EMAIL-02). `available && address === null` (before hydration): an empty placeholder that has the size of the real element, is `aria-hidden="true"`, has no text, no `href` and no `mailto`, and carries `data-email-pending`. `address !== null`: the real element. | FR-PR-22; NFR-PR-Q-04 | +| BR-MAIL-03 | `Footer`: the Contact column (title and list) is rendered before hydration whenever `available`, with one placeholder list item sized like `FooterLink` (`minH` 44 px below `lg`, one text line from `lg`). After hydration the item holds the link. Without the column the footer would grow at screen widths below `lg`, where the column wraps under the others. | FR-PR-22 | +| BR-MAIL-04 | `ContactDetails` (contact page, twice): with `available`, the e-mail item is the first list item before hydration as a placeholder of `minH` 44 px, so the social items below it do not move. The card is only omitted when there is no channel at all (`available` false and no social). | FR-PR-22 | +| BR-MAIL-05 | `ContactFormGate`: the notice sentence is "Het contactformulier komt binnenkort." before hydration. The part " Mail me voor nu op" with the address link and the button "Stuur een e-mail" appear after hydration. Before it, the notice reserves their space: the button is an `aria-hidden`, `visibility: hidden` placeholder with the button's own recipe and label, and the inline part is an `aria-hidden`, `visibility: hidden` inline block `n` characters wide (`n` = length of the address, computed from the parts without assembling it). The bottom margin depends on `available`, not on the address. | FR-PR-22 | +| BR-MAIL-06 | `ContactForm` shows the address only in the failed state after a user action, so it is never in the first render. It also reads `useEmailAddress` so the address is not assembled during prerender at all. | FR-PR-22 | +| BR-MAIL-07 | `contactChannels(email, socials, assemble)` gets a third parameter. With `assemble` false and valid parts the first channel is `{ kind: 'email-pending' }` (no `href`, no `label`); with `assemble` true it is the existing email channel; with invalid parts there is none. `ContactDetails` passes `hydrated`. Social channels do not depend on it. | FR-PR-22 | +| BR-MAIL-08 | `lib/emailAddress.ts` gets `isEmailAddressValid(parts)`; `emailAddress` reuses it, so both agree. `lib/` keeps its 100% thresholds: every new or changed function and branch in `lib/` has tests. | NFR-PR-Q-01 | +| BR-MAIL-09 | Without JavaScript the address never appears (FR-PR-11 exception). Unit 1 leaves the placeholders in a harmless state: nothing readable, nothing clickable. Unit 2 hides the bare "Contact" footer title without JavaScript (for instance by a `<noscript>` style on `[data-email-pending]` parents). | FR-PR-11, 22 | +| BR-MAIL-10 | Build check (runner, code EMAIL_IN_OUTPUT): the assembled address, built from `siteContent.email` by `emailAddress`, must not occur in any text file in `dist/client` (HTML, JavaScript, CSS, XML, TXT, JSON), compared case-insensitively in these forms: plain, `%40`, `@`, `\x40`, `@`, `@`, `@`. This is stricter than FR-PR-22 (HTML only): the moved scripts hold the serialized data, and the bundle must stay free of it as today. If the parts are invalid there is no address and the check passes. | FR-PR-22; NFR-PR-SEC-04 | +| BR-MAIL-11 | JSON-LD never contains the address (`seo.ts` comments already say so); the scan of BR-MAIL-10 covers it. | NFR-PR-SEC-04 | + +### BR-404: Not found + +| Id | Rule | Source | +|---|---|---| +| BR-404-01 | `src/routes/$.tsx` is a catch-all route whose component is `NotFound`. It renders normally; it never throws `notFound()` and never sets a status other than OK, because Start fails the build on a non-OK prerender. | FR-PR-14; D5 | +| BR-404-02 | Start prerenders it from path `/404` to `404.html`. `/404` is not in `sitePages` and not in the sitemap. | FR-PR-14; BR-BLD-02 | +| BR-404-03 | `404.html` contains exactly one `<title>` ("Pagina niet gevonden \| Andrea Slop Fotografie") and one `<meta name="robots" content="noindex">`. `NotFound` keeps rendering them itself (React 19 hoists them into `<head>`); the root `head()` has no title. | FR-PR-14 | +| BR-404-04 | The page is rendered in the normal shell (navigation and footer) as today. Before hydration it shows one button, "Terug naar home". The two extra buttons under `/soorten-fotoshoots/` appear after hydration. | FR-PR-15; BR-HYD-13 | +| BR-404-05 | The first browser render on an unknown URL has the router pathname of the real URL, while the prerendered HTML was made for `/404`. Only `NotFound` renders from the pathname. The navigation compares exact, normalised strings with registered paths (`isItemCurrent`, `isSectionCurrent`, `pathname === '/'`), which are false for both. The router's `Link` is different: the desktop `NavLink`s and the `MobileNav` links use the default fuzzy matching, so on an unknown URL such as `/over-mij/x` the client would mark "Over mij" as current (`aria-current`, `data-status`, class) while the HTML has none. Therefore every navigation link (`NavigationBar`, `MobileNav`) gets `activeOptions={{ exact: true, includeSearch: false }}`, like `NavSubmenu` and `MobileNavGroup` already have. For real pages nothing changes, as no page has sub-paths except the shoot pages, which the submenu already handles exactly. No other component may render from the pathname on the catch-all page. | FR-PR-15 | +| BR-404-06 | Client-side navigation to an unknown path renders the same catch-all route (no server round trip). | FR-PR-07 | +| BR-404-07 | Known limit, for unit 3: a URL that the web server does not map but the client router does match (different letter case such as `/Over-Mij`, or a trailing slash) gets `404.html` with a real page rendered in the browser. React recovers by client rendering and reports a hydration error. Unit 3 decides the URL rules (trailing slash, case) so that server and router agree. | FR-PR-14, 16 | + +### BR-LZY: Lazy code and what the HTML contains + +| Id | Rule | Source | +|---|---|---| +| BR-LZY-01 | `ContactPanel` / `ContactForm` on `/contact` (`load="eager"`): the form is in the first render on both sides, so the HTML contains the form fields inside the gate. On `/` (`load="lazy"`) the first render shows the placeholder box (`inView` is `false`); the form is not in the HTML and loads when near or when `?pakket=` applies. | FR-PR-01, 05 | +| BR-LZY-02 | `Testimonials`: all visible testimonial texts and names are in the HTML for SEO. The carousel itself loads only after hydration and when near, as today. `CarouselPlaceholder` therefore renders every visible testimonial as a `TestimonialSlide`: the longest in the normal flow (it sets the height, as today), the others visually hidden with `aria-hidden="true"` and `inert` so assistive technology reads each review once, in the carousel. A single review has no placeholder and is in the HTML already. Alternative if the owner prefers one copy of the text: render the carousel in the first render (costs the lazy chunk, see BR-MEA). | FR-PR-01; NFR-PR-S-02 | +| BR-LZY-03 | `PortfolioGallery` / `Lightbox`: `lightboxRequested` starts `false`, so the HTML has no lightbox. No change. | FR-PR-05 | +| BR-LZY-04 | `__root.tsx` `RouterDevtools`: `import.meta.env.DEV` is `false` in the build, so it is `() => null` in both bundles and nothing reaches the HTML. In `pnpm dev` the lazy devtools under `Suspense` must not break server rendering. | FR-PR-05 | +| BR-LZY-05 | A lazy component whose chunk is missing when React hydrates keeps the server HTML and hydrates later; it must not cause a mismatch. This is checked in the e2e test for `/contact` (BR-TST-05). | FR-PR-05 | + +### BR-MON: Sentry and Umami + +| Id | Rule | Source | +|---|---|---| +| BR-MON-01 | `startSentry()` runs only in `client.tsx`, before hydration. Shared modules have no import-time side effects (`monitoring/sentry.ts` has none; `reportError` is a no-op in state `off`). | FR-PR-08; D13 | +| BR-MON-02 | Sentry starts only on the test and production hostnames (`monitoringFor`, unchanged). The build machine and the preview server on `localhost` start nothing. | FR-PR-08 | +| BR-MON-03 | `UmamiAnalytics` adds its script in an effect, only on those hostnames, renders no markup and adds no script to the HTML. See BR-HYD-15. | FR-PR-08 | +| BR-MON-04 | `import.meta.env.VITE_RELEASE` is set for the whole `vite build` (client bundle). The server bundle never initialises Sentry. | FR-PR-08 | + +### BR-SCR: Script step + +Pure functions in `config/inlineScripts.ts`, runner in `config/externalizeInlineScripts.ts`. + +| Id | Rule | Source | +|---|---|---| +| BR-SCR-01 | `externalizeInlineScripts(html)` and `findExecutableInlineScripts(html)` use one scanner and one classification (flowchart 1.1), so the guard cannot disagree with the rewrite. No HTML parser dependency. | FR-PR-19; D2 | +| BR-SCR-02 | Scanner. It reads the text left to right and recognises: comments (from `<!--` to the first `-->`, or to the end if unterminated); `<!...>` and `<?...>` up to `>`; end tags up to `>`; start tags (name case-insensitive, attributes read with quotes so a `>` inside a quoted value does not end the tag). After the start tag of `style`, `textarea`, `title`, `noscript`, `xmp`, `iframe`, `noembed` or `noframes` the text up to the matching end tag (name followed by whitespace, `/` or `>`; or the end of the text) is skipped. A `<` not followed by a letter, `/`, `!` or `?` is text. Text in comments, style bodies and attribute values therefore never matches. | FR-PR-19 | +| BR-SCR-03 | The body of a script element runs from the `>` of the start tag to the first `</script` followed by whitespace, `/` or `>` (case-insensitive); the end tag runs to its `>`. A script start tag without such an end tag is an error (UNTERMINATED_SCRIPT) in `externalizeInlineScripts`; `findExecutableInlineScripts` reports the rest of the text as its body. | FR-PR-19; D2 | +| BR-SCR-04 | Executable means all of: no `src` attribute (present in any form, also empty or without value); a body that is not empty after trimming whitespace; `type` absent, empty, or after trimming and lower-casing one of `application/javascript`, `application/ecmascript`, `application/x-ecmascript`, `application/x-javascript`, `text/javascript`, `text/javascript1.0` to `text/javascript1.5`, `text/ecmascript`, `text/jscript`, `text/livescript`, `text/x-ecmascript`, `text/x-javascript`, or `module`. Every other type (`application/ld+json`, `application/json`, `importmap`, `speculationrules`, unknown) is a data block and stays. The `language` attribute is ignored. | FR-PR-19 | +| BR-SCR-05 | Unsupported executable forms throw (UNSUPPORTED_SCRIPT), so a Start change is noticed rather than silently changing behaviour: (a) a classic script with `async` or `defer` (an external file would run in another order); (b) a body containing `<!--` (the browser's script-data escape states make the end of the script ambiguous); (c) a `module` body with a relative import specifier (`from './...'`, `import('../...')`), which would resolve against `/assets/` instead of the page. | FR-PR-19, 20 | +| BR-SCR-06 | An executable script is replaced by `<script` + its original attribute text verbatim + ` src="/assets/inline-<hash>.js"` + `></script>`. All its attributes stay (`type`, `data-*`, `id`, `class`, `nonce`, and so on); only `src` is added. The element keeps its position, so the execution order (also relative to external scripts) is preserved. Scripts stay where Start puts them, at the end of the body. | FR-PR-19; D4 | +| BR-SCR-07 | `<hash>` is the first 12 lowercase hex characters of the SHA-256 of the body, as UTF-8 bytes exactly as written in the document (no trimming, no newline or entity changes). The file content is that body in UTF-8, without BOM and without an added newline. | D3 | +| BR-SCR-08 | The same body gives the same file name. `moved` lists each file once, in order of first appearance; file names in one result are unique. | D3 | +| BR-SCR-09 | Everything outside the replaced script elements stays byte-identical, including comments, style bodies, data blocks, external scripts, whitespace and line endings. | FR-PR-19 | +| BR-SCR-10 | Idempotence: `externalizeInlineScripts(result.html).html` equals `result.html`, with an empty `moved`. | NFR-PR-Q-02 | +| BR-SCR-11 | `findExecutableInlineScripts(externalizeInlineScripts(html).html)` is empty. | FR-PR-20 | +| BR-SCR-12 | Runner order: (1) read every `.html` file under `clientDir` (recursive, sorted); (2) plan in memory with no writes; (3) if the plan has violations, print them all and exit 1 without writing anything; (4) otherwise write the script files first and then the changed HTML files. `planExternalization(files, context)` is pure and exported for tests; the runner only reads and writes. | FR-PR-20; SECURITY-15 | +| BR-SCR-13 | Runner violation NO_HTML: no `.html` file under `clientDir`. | FR-PR-20 | +| BR-SCR-14 | Runner violation PAGE_MISSING: a path in `sitePages` has no file `pageFile(path)`. All missing pages are listed. | FR-PR-03 | +| BR-SCR-15 | Runner violation NOT_FOUND_PAGE_MISSING: `404.html` is absent. | FR-PR-14 | +| BR-SCR-16 | Runner violation UNEXPECTED_HTML: an `.html` file that is neither a page of BR-SCR-14 nor `404.html`. | BR-BLD-04 | +| BR-SCR-17 | Runner violation NO_SCRIPTS_MOVED: a page or `404.html` whose final HTML references no `/assets/inline-<12 hex>.js` file. A file that was already processed counts, so running the runner twice is not an error. The minimum is one reference per page (the spike saw two: the bootstrap and the boundary script). | FR-PR-20 | +| BR-SCR-18 | Runner violation EXECUTABLE_REMAINS: after the rewrite `findExecutableInlineScripts` still returns a body. Defence in depth; BR-SCR-11 says it cannot happen. | FR-PR-20 | +| BR-SCR-19 | Runner violation COLLISION: `assets/inline-<hash>.js` exists with other content than the body. | D3 | +| BR-SCR-20 | Runner violations from the other rules: UNTERMINATED_SCRIPT and UNSUPPORTED_SCRIPT (BR-SCR-03, 05), EMAIL_IN_OUTPUT (BR-MAIL-10), SITEMAP_MISSING and SITEMAP_DIFFERS (BR-BLD-09), SOURCE_MAP_PRESENT and BUILD_PATH_LEAK (BR-SEC). | see rules | +| BR-SCR-21 | Messages have the form `<file>: <CODE>: <detail>`. They name a file and a position, never print script bodies, and never print the assembled address. Success prints one line: pages checked, scripts moved, files written. Exit code 0 on success, 1 on any violation. | NFR-PR-SEC-04 | +| BR-SCR-22 | Data blocks (JSON-LD from `StructuredData` and the route `head()` scripts) stay inline. The e2e test under the production CSP must show no violation for them; if one appears, FR-PR-19 is to be revisited, not worked around. | FR-PR-19 | +| BR-SCR-23 | No `preload` or other hint is added for the moved scripts in unit 1; where they load is measured first (BR-MEA-03). | NFR-PR-P-04; D4 | + +### BR-SEC: Output hygiene + +| Id | Rule | Source | +|---|---|---| +| BR-SEC-01 | `config/securityHeaders.ts` is not changed in unit 1; its test keeps passing. The e2e tests and the preview server use `securityHeaders('production')`. | NFR-PR-SEC-01 | +| BR-SEC-02 | No `.map` file in `dist/client` (SOURCE_MAP_PRESENT). | NFR-PR-SEC-03 | +| BR-SEC-03 | No text file in `dist/client` contains the absolute path of the repository root in either slash style (BUILD_PATH_LEAK). | NFR-PR-SEC-03 | +| BR-SEC-04 | Serialized data is public page data only. No loader, route context or server function is added in unit 1; the moved bootstrap scripts are scanned by BR-MAIL-10 and BR-SEC-03. | NFR-PR-SEC-04 | +| BR-SEC-05 | Error pages show no internal details (BR-ENT-04). A failing prerender shows Start's message in the CI log only. | NFR-PR-SEC-03 | +| BR-SEC-06 | `StructuredData` and `structuredDataScript` keep escaping `<`, `>` and `&` (`jsonLdScript`), so content can never close the script element. | SECURITY-04, 11 | + +### BR-SRV: Preview server (unit 1 part) + +Only what Lighthouse and the browser tests need. Trailing slash and `/404` are final in unit 3 Infrastructure Design. + +| Id | Rule | Source | +|---|---|---| +| BR-SRV-01 | `resolveRequest(path, fileExists)` takes the URL path without query or hash and returns `{ file, status }` (`file` relative to `clientDir`, forward slashes, no leading slash). `fileExists` takes the same relative form. | D10 | +| BR-SRV-02 | `/` gives `index.html`, status 200. | FR-PR-16 | +| BR-SRV-03 | `/x` (last segment without a dot) gives `pageFile('/x')` with status 200 when that file exists. | FR-PR-16 | +| BR-SRV-04 | A last segment with a dot is a file request: the file itself with 200 when it exists. | D10 | +| 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-TST: Tests + +| Id | Rule | Source | +|---|---|---| +| BR-TST-01 | `renderApp` builds its router from the shared options of BR-ENT-01, with a memory history, and renders `RouterProvider` inside `ChakraProvider` without `<html>`. The root route renders only its `component` in tests. Whether Router renders `shellComponent` itself is verified in code generation (see section 4). | D12 | +| BR-TST-02 | The existing test files keep running. Changes are only where behaviour changed: first-render values after `ssr` removal are `false` until effects have run (wrap in `act` or `waitFor`); the footer year, `usePageLoaded`, `useInView` and `useHeroSlider` tests keep passing because components mounted by `createRoot` see the real value at once (BR-HYD-03). | NFR-PR-Q-01 | +| BR-TST-03 | Vitest coverage thresholds stay as they are (100% for `src/lib/**`, `src/seo.ts`, `src/sitemap.ts`). `config/**` is reported, not thresholded, as today. | NFR-PR-Q-01 | +| BR-TST-04 | Pure logic gets example-based tests and fast-check properties (section 3 of the business logic model), with the existing seed handling (`testSeed.ts`). | NFR-PR-Q-02 | +| BR-TST-05 | `e2e/` runs `playwright-core` with the Chromium of the Lighthouse job against the preview server on the built `dist/client`, in CI. Pages: all eleven, `/404`, `/soorten-fotoshoots/onbekend`, `/onbekend`, and the variants `/?pakket=gezin#contact`, `/contact?pakket=gezin`, `/portfolio?shoot=gezin`. Each must show: no console error or warning, no `securitypolicyviolation`, and for the variants the search value applied after hydration. Interaction checks: the mobile menu opens and closes, one client-side navigation works, the e-mail link appears only after hydration, focus moves to `main` after a client navigation but not on first load. | NFR-PR-Q-03, SEC-01; FR-PR-05 to 08 | +| BR-TST-06 | A second set of checks needs no JavaScript: `fetch` of each page of `sitePages` and `404.html` returns, in the raw HTML, the `<title>` of `pageHead`, exactly one `<h1>`, at least 40 visible characters in `main` outside the `h1`, a link to every `mainNav` and `footerNav` target, the canonical URL, the JSON-LD blocks, and no assembled e-mail address. The 40 characters is a floor that code generation may tune. | NFR-PR-S-02; FR-PR-02, 22 | +| BR-TST-07 | A fast prerender-safety test with `@vitest-environment node` renders each route with `react-dom/server` and expects no throw, to catch `window` or `document` in a render path before a full build. The build's own prerender stays the authoritative check. Feasibility is verified in code generation. | FR-PR-05 | + +### BR-MEA: Measurement and decision gate + +| Id | Rule | Source | +|---|---|---| +| BR-MEA-01 | Before the first code change, on master c4c2f83: gzip size of the entry JavaScript and of all JavaScript on `/`, and mobile and desktop Lighthouse (performance, FCP, LCP, TBT, CLS) for every page of `sitePages`, median of three runs, with the same method and machine class as `pnpm lighthouse`. | NFR-PR-P-03 | +| BR-MEA-02 | The same after unit 1, on the same machine. Both sets are shown to the owner side by side. If any entry is worse, the owner decides whether to continue before units 2 and 3 start. | NFR-PR-P-03 | +| BR-MEA-03 | For NFR-PR-P-04 the report adds, per page, the number and gzip size of the moved script files and, for `/` and `/over-mij`, their request start and end relative to FCP and LCP. FCP or LCP later than the baseline goes to the same owner decision. | NFR-PR-P-04 | +| BR-MEA-04 | CLS on `/` and `/contact` must not rise noticeably through the e-mail placeholders of BR-MAIL: it stays below 0.01 on both, mobile and desktop (the baseline on master is 0.0011 and 0.0009 on mobile, not exactly 0). A higher value is fixed with a better reserved size, not accepted. | NFR-PR-Q-04 | +| BR-MEA-05 | Unit 1 leaves `Reveal` hidden in the HTML and has no photo preload, so its scores understate what units 2 and 3 can reach on pages whose largest paint sits inside `Reveal`. The report therefore adds a second measurement with `Reveal` temporarily visible by default, in an uncommitted local change, labelled as an indication. The owner decides with both in view. | NFR-PR-P-03 | + +## 3. What unit 1 leaves in a working state + +| Belongs to | What unit 1 must leave | +|---|---| +| Unit 2 `Reveal` / `useReveal` | Hydrates without mismatch. In the HTML, content is in its hidden state (`data-reveal="hidden"`, as `inView` is `false`) and becomes visible after hydration, as in the SPA today. Text is in the HTML and in the raw-HTML test regardless of opacity. Unit 2 flips the default to visible (FR-PR-09). | +| Unit 2 `DeferredImage` | Hydrates without mismatch: first render has no `src` on either side (`pageLoaded` and `inView` start `false`), photos load after hydration as today. The no-JavaScript image is unit 2. | +| Unit 2 `NoScriptNav` | Not started. The mobile menu works with JavaScript as today. | +| Unit 2 photo preload | Not started. `pageHead` stays as it is. | +| Unit 2 hero, carousel, form fallbacks | The HTML contains the first hero slide image (the hero's `loaded` list starts with the active slide, which renders in the first render); testimonials per BR-LZY-02; the form per BR-LZY-01. Autoplay is on in the first render and stops after hydration for visitors with reduced motion. | +| Unit 3 servers | `dist/client` is complete and correct for a server that maps `/x` to `x.html` and unknown URLs to `404.html` with 404; the preview server proves it. nginx, IIS, upload order and Lighthouse targets are untouched. | + +## 4. To verify in code generation + +Neither the code nor the spike settles these. + +| # | Point | Where it matters | +|---|---|---| +| V1 | How the custom `src/client.tsx` hydrates with Start (entry API and file naming), and that `startSentry()` before hydration works. | BR-ENT-03 | +| V2 | Whether `RouterProvider` in jsdom renders `shellComponent` (`<html>` cannot sit in the test container). If it does, `renderApp` creates the router from a variant of the root route without the shell. | BR-TST-01 | +| V3 | The exact set of inline scripts per real page: Start's bootstrap and boundary, and any from router scroll restoration or from React for lazy boundaries (`$RC`-type completion scripts). They are moved like any other; check there is no `<!--`, no `async`/`defer`, no `module` with relative imports (BR-SCR-05). | BR-SCR | +| V4 | Whether the first real page keeps the minimum of one moved script (BR-SCR-17) or the runner should demand the two seen in the spike. | BR-SCR-17 | +| V5 | That prerender of `/` really writes `index.html` with `autoSubfolderIndex: false`, and that link crawling is off or limited. | BR-BLD-02, 04 | +| V6 | Start's plugin options for route code splitting (`autoCodeSplitting` equivalent) and whether `@tanstack/router-plugin` becomes unused. | BR-BLD-08, 11 | +| V7 | Whether Vite's `this.environment.name` identifies the client build in `sitemapPlugin.generateBundle` (Vite 8), and that no `sitemap.xml` is left in `public/`. | BR-BLD-09 | +| V8 | Lazy components in the HTML: that prerender waits for `ContactForm` on `/contact` (form fields in the HTML) and that React hydrates the boundary without a mismatch when the chunk arrives later. What the spike did not test. | BR-LZY-01, 05 | +| V9 | Testimonials: that all review texts are in the HTML and that the visually hidden slides do not disturb layout, reading order or the axe test. | BR-LZY-02 | +| V10 | Placeholder sizes for the footer item, contact card item and the gate notice: measured per breakpoint until CLS stays below 0.01. | BR-MAIL-03 to 05, BR-MEA-04 | +| V11 | Exactly one `<title>` and one `noindex` robots meta in `404.html`, and no duplicates on the normal pages, with React 19 hoisting inside Start's `HeadContent`. | BR-404-03, BR-BLD-05 | +| V12 | No hydration error from the 404 page when its HTML (made for `/404`) is served for other URLs, with the real shell (navigation, footer) and not only the spike's simple pages. | BR-404-05 | +| V13 | Whether Start's dehydrated state or any inline script contains a build timestamp (affects only the hash names, not correctness) or any build path (BR-SEC-03). | BR-SEC | +| V14 | `useRouteFocus` does not move focus on the first load with Start's router, and the contact page's tidy navigation keeps its scroll-to-top behaviour now that it runs one render later on a direct load. | BR-ENT-06, BR-HYD-11 | +| V15 | Emotion/Chakra: no style flicker on real pages and no duplicate style insertion after hydration. | BR-BLD-07 | +| V16 | Node and browser `Intl.NumberFormat('nl-NL')` give the same price text. | BR-HYD-17 | +| V17 | No inline event-handler attributes (`on*=`) or `javascript:` URLs in Start's output (they are not scripts for the runner but the CSP blocks them). The e2e CSP check covers this. | BR-SEC-01 | +| V18 | The CI artifact upload of `web/dist/client/` keeps `index.html` at the artifact root for the existing deploy steps. | BR-BLD-10 | diff --git a/aidlc-docs/features/prerendering/construction/start-migration/functional-design/domain-entities.md b/aidlc-docs/features/prerendering/construction/start-migration/functional-design/domain-entities.md new file mode 100644 index 0000000..333a1f9 --- /dev/null +++ b/aidlc-docs/features/prerendering/construction/start-migration/functional-design/domain-entities.md @@ -0,0 +1,105 @@ +# Domain Entities - Unit 1: Start migration and script step + +The site has no runtime data model and unit 1 adds none. The entities are build-time data of the script step and the preview server, the e-mail slot, and the inventory of browser-dependent values. Existing entities (`SitePage`, `SiteContent`, `EmailAddress`) are unchanged. Rules: [business-rules.md](business-rules.md). + +## 1. Relationships + +```mermaid +graph TD + Reg["SitePage register sitePages"] + Exp["ExpectedFileSet"] + Html["HtmlFile"] + Scr["ScriptElement"] + Mov["MovedScript"] + Res["ExternalizeResult"] + Plan["OutputPlan"] + Vio["Violation"] + Mail["EmailAddress parts"] + Slot["EmailSlot"] + Req["RequestResolution"] + Reg -->|"yields"| Exp + Exp -->|"is compared with"| Html + Html -->|"contains zero or more"| Scr + Scr -->|"executable ones become"| Mov + Html -->|"is rewritten into"| Res + Res -->|"lists"| Mov + Plan -->|"holds writes and"| Vio + Html -->|"is input of"| Plan + Mail -->|"gives"| Slot + Mail -->|"scanned for in"| Plan + Exp -->|"is the file set of"| Req + classDef source fill:#fbd38d,stroke:#92400e,stroke-width:1px,color:#000; + classDef data fill:#63b3ed,stroke:#2b6cb0,stroke-width:1px,color:#000; + classDef result fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000; + classDef problem fill:#f6e05e,stroke:#c05621,stroke-width:1px,color:#000; + class Reg,Mail source; + class Exp,Html,Scr,Req,Slot data; + class Mov,Res,Plan result; + class Vio problem; +``` + +Text alternative: the page register yields the expected files, which are compared with the HTML files; scripts in an HTML file become moved scripts in a result, and the plan holds the writes and violations, including the e-mail scan; the e-mail parts give the render slot. + +## 2. Entities + +### Script step (pure, `config/`) + +| Entity | Fields | Notes | +|---|---|---| +| `ScriptElement` (internal) | `start`, `end` (byte range), `attributeText` (verbatim between the tag name and `>`), `body`, `kind` | `kind` is `external`, `empty`, `data` or `executable` (flowchart 1.1). Not exported. | +| `MovedScript` | `fileName: string`, `body: string` | `fileName` is `inline-<12 hex>.js`; the file lives at `/assets/<fileName>`. | +| `ExternalizeResult` | `html: string`, `moved: MovedScript[]` | `moved` has unique file names in order of first appearance. | +| `ExpectedFileSet` | `pages: Map<path, file>`, `notFound: '404.html'` | From `sitePages` keys through `pageFile`. `404.html` is not a `sitePages` path. | +| `Violation` | `file: string`, `code: ViolationCode`, `detail: string` | Codes in business-logic-model.md ยง 3.2. `detail` never holds a script body or the address. | +| `OutputPlan` | `writes: Map<relativePath, string>`, `violations: Violation[]` | Result of `planExternalization`. Violations empty means the writes may be applied. | +| `PlanContext` | `expected: ExpectedFileSet`, `address: string \| null`, `sitemap: string`, `rootPaths: string[]` | `address` is `emailAddress(siteContent.email)`; `rootPaths` are the repository root in both slash styles. | + +Constants: `ASSETS_DIR = 'assets'`, `HASH_LENGTH = 12`, `NOT_FOUND_FILE = '404.html'`, `NOT_FOUND_PATH = '/404'`, the JavaScript type list of BR-SCR-04, the raw-text element list of BR-SCR-02. + +`config/pageFiles.ts` (new, pure): `pageFile(path): string`, `pagePath(file): string | undefined` (inverse, `undefined` for `404.html` and unknown files). + +### E-mail slot + +| Entity | Fields | Notes | +|---|---|---| +| `EmailAddress` (existing) | `user`, `domain` | Unchanged. Parts only; never joined during prerender. | +| `EmailSlot` | `available: boolean`, `address: string \| null` | Result of `useEmailAddress`. `available` is `isEmailAddressValid(parts)`; `address` is non-null only when hydrated and available. | +| `ContactChannel` (existing, extended) | adds `{ kind: 'email-pending' }` | Produced by `contactChannels(email, socials, assemble)` when `assemble` is false and the parts are valid. No `href`, no `label`. | + +| `available` | `address` | State | Renders | +|---|---|---|---| +| false | null | absent | nothing | +| true | null | pending (prerender, hydrating render) | placeholder, `aria-hidden`, reserved size | +| true | string | ready | text and `mailto` link | + +### Preview server + +| Entity | Fields | Notes | +|---|---|---| +| `RequestResolution` | `{ file: string; status: 200 \| 404 }` (unit 1 never returns `{ redirect }`) | `file` relative to `clientDir`, forward slashes. | +| `PreviewHeaders` | `securityHeaders('production')` plus `Content-Type`, and `Cache-Control: no-cache` for HTML | Same set on every response. | + +## 3. Hydration inventory + +Every value found in `web/src` that differs between the prerender and the first browser render, with the contract that removes the difference. "Today" is the code at master c4c2f83. + +| # | Source (file) | Today | First render, server and browser | After hydration | Rule | +|---|---|---|---|---|---| +| 1 | `hooks/usePageLoaded.ts` | `useState(() => document.readyState === 'complete')`: throws on the server | `false` | readyState and `load` event | BR-HYD-04 | +| 2 | `hooks/useInView.ts` | `typeof IntersectionObserver` in render: `inView` true on the server, false in the browser | `inView = skip` | observed, or `true` without observer | BR-HYD-05 | +| 3 | `hooks/useReveal.ts`, `Hero/useHeroSlider.ts`, `home/ContactSection`, `home/Testimonials/TestimonialCarousel` | `useMediaQuery(..., { ssr: false })`: reads `window.matchMedia` in the initialiser, throws on the server, real value in the browser | `false` | real value from Chakra's effect | BR-HYD-07, 08 | +| 4 | `NavigationBar/NavigationBar.tsx` | `useBreakpointValue({ base: false, lg: true }, { ssr: false })`: same | `false` (value of `base`) | `viewport` dispatch with the real value; layout is CSS only | BR-HYD-07, 08 | +| 5 | `home/IntroGallery` | `useBreakpointValue({ base: true, sm: false })` with default `ssr`: already safe | `true` (value of `base`) | real value; `tabIndex` leaves from `sm` | BR-HYD-08 | +| 6 | `Hero/useHeroSlider.ts` | `useState(() => document.hidden)`: throws on the server, differs in a background tab | `false` | `document.hidden`, `visibilitychange` | BR-HYD-09 | +| 7 | `routes/index.tsx`, `routes/contact.tsx`, `routes/portfolio.tsx` | `Route.useSearch()` in the first render: error #418 (spike) | search not applied | search applied | BR-HYD-10 to 12 | +| 8 | `StatusPage/NotFound.tsx` | `isShootSectionPath(pathname)` in the first render | one home button | extra buttons under `/soorten-fotoshoots/` | BR-HYD-13, BR-404 | +| 9 | `Footer/Footer.tsx` | `new Date().getFullYear()` in render | `BUILD_YEAR` | current year | BR-HYD-14 | +| 10 | `Footer`, `ContactDetails` (through `contactChannels`), `ContactFormGate`, `ContactForm` | `emailAddress(...)` in render | placeholder or nothing | address and link | BR-MAIL-01 to 09 | +| 11 | `Analytics/UmamiAnalytics.tsx` | default parameter `window.location.hostname` evaluated in render: throws on the server | `hostname` read in the effect | script added on known hosts | BR-HYD-15, BR-MON-03 | +| 12 | `NavigationBar` `NavLink`s and `MobileNav` links (router `Link`) | default fuzzy active matching against the browser location: `aria-current` differs on an unknown URL such as `/over-mij/x` | exact matching, never current there | unchanged | BR-404-05 | +| 13 | `home/Pricing/PriceCard.tsx` (router `Link`) | link to `/?pakket=...` is active on `/?pakket=...` in the browser only (attributes) | differs in attributes only | tidy navigation clears it | BR-HYD-21 | +| 14 | `ContactForm.tsx` `shownAt` | `Date.now()` in an initialiser, not rendered | same | form timer starts in the browser | BR-HYD-16 | +| 15 | `lib/formatPrice.ts` | `Intl.NumberFormat('nl-NL')`: Node and browser ICU could differ | identical text expected | none | BR-HYD-17, V16 | +| 16 | `home/Testimonials`, `ContactPanel` (`lazy`) | placeholder until near the viewport | placeholder; all reviews in the HTML | component loads | BR-LZY-01, 02 | + +Checked and safe, no rule beyond BR-HYD-19: `hooks/useScrolledPast.tsx` (effect only, starts `false`), `BackToTop` (`window` only in the scroll handler and effect), `MobileNav`, `NavSubmenu`, `useDismiss`, `useRouteFocus`, `Hero` (`requestAnimationFrame` in an event handler), `Lightbox` (lazy, after a request), `PortfolioGrid` (`masonryRowSpan` is pure, no measuring), `routes/__root.tsx` devtools (`import.meta.env.DEV`, a build-time constant). Not present in `src`: `Math.random`, `crypto`, `localStorage`, `sessionStorage`, `useId`, `navigator`, `innerWidth` in render, `ResizeObserver`, `dangerouslySetInnerHTML` other than JSON-LD. diff --git a/aidlc-docs/features/prerendering/construction/start-migration/functional-design/frontend-components.md b/aidlc-docs/features/prerendering/construction/start-migration/functional-design/frontend-components.md new file mode 100644 index 0000000..0cf9c16 --- /dev/null +++ b/aidlc-docs/features/prerendering/construction/start-migration/functional-design/frontend-components.md @@ -0,0 +1,147 @@ +# Frontend Components - Unit 1: Start migration and script step + +All paths are under `web/`. Interfaces for new files follow [component-methods.md](../../../inception/application-design/component-methods.md); this document fixes the details and records the additions (marked **new**). Rules: [business-rules.md](business-rules.md). Logic: [business-logic-model.md](business-logic-model.md). First-render values: [domain-entities.md ยง 3](domain-entities.md). + +## 1. Component hierarchy + +```mermaid +graph TD + Vite["vite.config.ts with Start plugin"] --> Router["src/router.tsx getRouter"] + Client["src/client.tsx: Sentry, then hydrate"] --> Router + Router --> Root["routes/__root.tsx shellComponent"] + Root --> Html["html, HeadContent, ChakraProvider, Scripts"] + Html --> App["AppShell"] + App --> Nav["NavigationBar and MobileNav"] + App --> Out["Outlet: page routes and catch-all"] + App --> Foot["Footer"] + App --> Top["BackToTop"] + App --> Umami["UmamiAnalytics"] + Out --> Pages["index, contact, portfolio, other pages"] + Out --> NF["routes/$.tsx NotFound"] + Pages --> Panel["ContactPanel and ContactFormGate"] + Pages --> Details["ContactDetails"] + Pages --> Tests["Testimonials"] + Nav --> Hyd["useHydrated"] + Foot --> Mail["useEmailAddress"] + Details --> Mail + Panel --> Mail + NF --> Hyd + Pages --> Hyd + Mail --> Hyd + Cfg["config: pageFiles, inlineScripts, externalizeInlineScripts, previewServer"] -.-> Vite + classDef build fill:#63b3ed,stroke:#2b6cb0,stroke-width:1px,color:#000; + classDef app fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000; + classDef hook fill:#f6e05e,stroke:#c05621,stroke-width:1px,color:#000; + classDef infra fill:#fbd38d,stroke:#92400e,stroke-width:1px,color:#000; + class Vite,Router,Client,Root,Html build; + class App,Nav,Out,Foot,Top,Umami,Pages,NF,Panel,Details,Tests app; + class Hyd,Mail hook; + class Cfg infra; +``` + +Text alternative: the Start build and the browser entry both use getRouter; the root shell renders the document around AppShell, whose navigation, pages, footer and monitoring components use the hydration hooks (green = app components, yellow = hooks, blue = build and entry, orange = config tools). + +## 2. Changed components + +"Contract" is what the component renders in the first render, on the server and in the browser (BR-HYD-01). + +### Build, entry and document + +| Component | Status | Contract and behaviour | +|---|---|---| +| `vite.config.ts` | Changed | `tanstackStart` with prerender: pages from `sitePages` plus `/404` to `/404.html`, `autoSubfolderIndex: false`, no extra crawling. Start plugin only outside Vitest. `define` of `VITE_BUILD_YEAR`. `sitemapPlugin` emits in the client environment only. CSP headers for `server` and `preview` stay from `securityHeaders`. | +| `src/router.tsx` | **new** | `getRouter()` and a shared options function (routeTree, `scrollRestoration: true`, `defaultErrorComponent: ErrorPage`). | +| `src/routes/__root.tsx` | Changed | `shellComponent` renders `<html lang="nl">`, `HeadContent`, `ChakraProvider value={system}` around children, `Scripts` last. `head()` adds charset, viewport, `favicon.png` icon and `apple-touch-icon` besides `siteHead`. Fonts imported here. `component` stays `RootLayout` (without `HeadContent`, which moves to the shell). `notFoundComponent` and `errorComponent` stay. | +| `src/client.tsx` | **new** | `startSentry()`, then hydrate inside `StrictMode`. Replaces `main.tsx`; `index.html` is removed. | +| `src/routes/$.tsx` | **new** | Catch-all route, component `NotFound`. No `head()`. | +| `config/inlineScripts.ts` | **new** | `externalizeInlineScripts`, `findExecutableInlineScripts` (signatures as in component-methods.md). | +| `config/externalizeInlineScripts.ts` | **new** | `externalizeOutput(clientDir)`, plus exported `planExternalization(files, context)` (**new**, pure core). Runs as a script with Node type stripping like `writeServerConfig.ts`. | +| `config/pageFiles.ts` | **new** | `pageFile`, `pagePath`, `NOT_FOUND_FILE`, `NOT_FOUND_PATH`. | +| `config/previewServer.ts` | **new** | `resolveRequest`, `startPreviewServer`. `package.json` `preview` runs it. | +| `config/sitemapPlugin.ts` | Changed | Emits `sitemap.xml` only when `this.environment.name` is the client environment (to verify V7). | +| `src/test/renderApp.tsx` | Changed | Router from the shared options with memory history; no `<html>` shell (V2). | +| `e2e/` | **new** | Playwright tests of BR-TST-05 and BR-TST-06. | + +### Hooks + +| Hook | Status | Interface and contract | +|---|---|---| +| `hooks/useHydrated.ts` | **new** | `useHydrated(): boolean`. `useSyncExternalStore(subscribeNoop, () => true, () => false)`. Same behaviour as the `useHydrated` that `@tanstack/react-router` exports (marked internal there), so the project owns its copy. | +| `hooks/useEmailAddress.ts` | **new** | `useEmailAddress(email: EmailAddress): { available: boolean; address: string \| null }` (BR-MAIL-01). | +| `hooks/usePageLoaded.ts` | Changed | Store-based (BR-HYD-04). Returns `false` while hydrating. | +| `hooks/useInView.ts` | Changed | Same options and return `{ ref, inView }`. `inView = skip \|\| intersected \|\| unsupported` (BR-HYD-05). The "no observer counts as in view" contract is applied after the first render. | +| `hooks/useReveal.ts` | Changed | `useMediaQuery` without `ssr: false`; first render `reducedMotion` is `false`. Returns `{ ref, visible }` as before; the visible-by-default rule is unit 2. | +| `hooks/useScrolledPast.tsx` | Unchanged | Verified safe (BR-HYD-06). The application design lists it as changed; it needs no change. | +| `Hero/useHeroSlider.ts` | Changed | `hidden` from a store, `useMediaQuery` without `ssr: false`; first render `autoplay` is `count > 1`. | + +### Pages and components + +| Component | Status | Contract | +|---|---|---| +| `routes/index.tsx` | Changed | `pakket` passed to `ContactSection` is `hydrated ? search.pakket : undefined`. | +| `routes/contact.tsx` | Changed | Same for `ContactPanel`; the tidy effect depends on the gated value. | +| `routes/portfolio.tsx` | Changed | `shoot` passed to `PortfolioGallery` is `hydrated ? search.shoot : undefined`; navigation callback unchanged. | +| `NavigationBar` | Changed | `useBreakpointValue` without `ssr: false` (first render `false`); all `NavLink`s get `activeOptions={{ exact: true, includeSearch: false }}`. Layout stays CSS-driven, so no visible jump. | +| `MobileNav` | Changed | Top-level links get the same `activeOptions`. | +| `IntroGallery` | Unchanged | `useBreakpointValue` already uses the default; first render `scrollable` is `true` (BR-HYD-08). | +| `ContactSection` | Changed | `useMediaQuery` without `ssr: false`; effect unchanged. | +| `TestimonialCarousel` | Changed | `useMediaQuery` without `ssr: false`. Only renders after hydration. | +| `Testimonials` | Changed | `CarouselPlaceholder` renders every visible review (longest in flow, others `aria-hidden`, visually hidden, `inert`) so the texts are in the HTML (BR-LZY-02). | +| `NotFound` | Changed | `hydrated && isShootSectionPath(pathname)` picks the buttons. Renders its own `<title>` and `noindex` meta as today. | +| `Footer` | Changed | Year: `hydrated ? new Date().getFullYear() : BUILD_YEAR`. Contact column per `useEmailAddress`: absent, placeholder item, or link (BR-MAIL-03). | +| `ContactDetails` | Changed | `contactChannels(email, socials, hydrated)`; renders an empty `aria-hidden` item with `minH` 44 px for `email-pending` (BR-MAIL-04). Returns `null` only when there is no channel at all. | +| `ContactFormGate` | Changed | Notice per BR-MAIL-05: sentence only plus hidden placeholders before hydration; address text, link and button after. `mb` depends on `available`. | +| `ContactForm` | Changed | Reads `useEmailAddress`; the mail link in the failed state uses its `address`. `shownAt` unchanged (BR-HYD-16). | +| `ContactPanel` | Unchanged | Props and behaviour as today; lazy form per BR-LZY-01. | +| `PriceCard` | Unchanged | Accepted attribute difference (BR-HYD-21). | +| `UmamiAnalytics` | Changed | `hostname` default read in the effect. | +| `AppShell`, `BackToTop`, `Hero`, `PortfolioGallery`, `Lightbox` | Unchanged | Verified safe (BR-HYD-19). `useRouteFocus` unchanged (V14). | +| `lib/emailAddress.ts` | Changed | Adds `isEmailAddressValid`; `emailAddress` reuses it. | +| `lib/contactChannels.ts` | Changed | Third parameter `assemble`; new kind `email-pending` (BR-MAIL-07). | + +## 3. Placeholder specification + +| Place | Before hydration (available) | After hydration | +|---|---|---| +| Footer Contact column | Title "Contact" and one empty `li`, `aria-hidden`, `data-email-pending`, `minH` 44 px below `lg` | `li` with the `FooterLink` mailto | +| Contact card (twice) | First `li` empty, `aria-hidden`, `data-email-pending`, `minH` 44 px | `li` with the mailto link and icon | +| Gate notice | Sentence only. Hidden inline block `n` characters wide where " Mail me voor nu op <address>" will come; hidden button placeholder with the button's recipe and label | Sentence extended, address link, "Stuur een e-mail" button | + +All placeholders carry no text a reader needs, no `href`, no address and no `mailto`. Measured sizes (V10) must give CLS below 0.01 (BR-MEA-04). + +## 4. Interaction flows that must keep working + +| Flow | Behaviour after the change | +|---|---| +| Direct load of `/?pakket=gezin#contact` | HTML paints; after hydration the panel takes the package, the form loads, the address bar is tidied to `/#contact`, smooth scroll and focus on the contact heading | +| Direct load of `/contact?pakket=gezin` | HTML paints; the package is preselected after hydration; the URL becomes `/contact` without a history entry | +| Direct load of `/portfolio?shoot=gezin` | All photos first, then the filtered list; filter clicks navigate with `replace` and keep the scroll position | +| Click "Boek" on a price card (client navigation) | Search applies in the first render of the next state; same as today | +| Mobile menu | Opens, closes with button and Escape, sets `body` overflow; closes at `lg` and on route change | +| Unknown URL | 404 page in the shell; extra buttons under `/soorten-fotoshoots/` after hydration | + +## 5. Accessibility and layout notes + +- Placeholders are `aria-hidden` and empty; they add no stops for keyboard or screen reader users. +- Visually hidden testimonial copies are `aria-hidden` and `inert`, so each review is read once, in the carousel. +- The footer "Contact" title stands alone without JavaScript until unit 2 decides (BR-MAIL-09). +- `IntroGallery`'s list has `tabIndex={0}` in the HTML at every width until hydration; it is removed from `sm` up afterwards (BR-HYD-08). +- Lighthouse accessibility, best practices and SEO targets stay 1.0 (NFR-PR-S-01); the check at the end of unit 1 is informative, the final targets are unit 3. + +## 6. Testable properties + +Component-level properties: none, see "No PBT properties identified" in [business-logic-model.md ยง 9](business-logic-model.md). The pure functions (`inlineScripts`, `pageFile`, `planExternalization`, `contactChannels`, `isEmailAddressValid`, `resolveRequest`) have properties P1 to P17 there. + +## 7. Example-based test list (code generation input) + +| Area | Test | +|---|---| +| Hooks | `useHydrated`, `usePageLoaded`, `useInView`, `useHeroSlider.hidden`: server snapshot value while hydrating (`hydrateRoot` into server-rendered markup), real value after | +| Routes | Contact, home and portfolio: no search in the first render, search applied after; tidy navigation still fires; filter navigation still works | +| Footer | Year equals build year while hydrating, current year after; Contact column states absent, pending, ready | +| Contact components | `ContactDetails`, `ContactFormGate`, `ContactForm`: no address in `renderToString` output; address after hydration | +| NotFound | One button while hydrating; two extra under `/soorten-fotoshoots/` after | +| Navigation | No link current on an unknown sub-path; current on real pages and with a search | +| Script step | Worked examples of business-logic-model.md ยง 3.1; each violation code; unsupported forms; unterminated script | +| Preview server | Status, headers, methods, content types for `/`, `/x`, `/file.ext`, unknown, traversal | +| Build and e2e | BR-TST-05 and BR-TST-06 | diff --git a/aidlc-docs/features/prerendering/inception/application-design/application-design.md b/aidlc-docs/features/prerendering/inception/application-design/application-design.md new file mode 100644 index 0000000..d3370c0 --- /dev/null +++ b/aidlc-docs/features/prerendering/inception/application-design/application-design.md @@ -0,0 +1,95 @@ +# Application Design: prerendering + +Details: [components.md](components.md), [component-methods.md](component-methods.md), [services.md](services.md), [component-dependency.md](component-dependency.md). + +## Spike Evidence + +Tested in a throwaway app outside the repository: `@tanstack/react-start` 1.169.4 and `@tanstack/react-router` 1.170.46 with Chakra, in Chrome, against a static test server with the production `script-src`. The app had three simple pages, so the real components are still untested. + +| Test | Result | +|---|---| +| Inline scripts under the production CSP | Blocked; page error; content disappears | +| Inline scripts moved to `/assets` | Hydrates; button and client-side link work; no CSP violations | +| `autoSubfolderIndex: false`, served as `/over-mij.html` for `/over-mij` | Status 200, no redirect, no errors | +| 404 page rendered from a route giving status 404 | Build fails: Start rejects a non-OK response | +| Separate `/404` route, served for unknown URLs | Status 404 and correct URL, but React hydration error #418 | +| Start's SPA shell as the 404 page | Rejected: `index.html` is not generated, and error #418 remains | +| Catch-all `$` route, prerendered to `404.html`, URL-dependent output after hydration | Status 404, correct URL, no hydration error | +| `/?pakket=gezin` reading the search value in the first render | Correct value, but hydration error #418 | +| Same, with the value applied after hydration | Correct value, no error | + +## Decisions + +| # | Decision | Reason | Rejected | +|---|---|---|---| +| D1 | Prerender with Start, `autoSubfolderIndex: false`, all pages listed from `sitePages.ts` | URLs stay without a slash; a page cannot be forgotten through crawling alone | Subfolder output: gives redirects to a trailing slash | +| D2 | A small Node step after `vite build` moves the scripts, without an HTML parser dependency | Runs on Start's final output; pure logic is testable; the browser also ends a script at the first `</script>` | Vite plugin hook: ordering against Start's prerender is less clear | +| D3 | Moved files are named after their content hash in `/assets` | Long caching is safe, and identical scripts share a file | Fixed names: unsafe with long caching | +| D4 | Keep the scripts at the end of the body, where Start puts them | Content renders before they are fetched, which limits the cost of the extra requests | Moving them to the head | +| D5 | 404 through a catch-all route rendering the existing `NotFound` | The only tested option without a hydration error | See the spike table | +| D6 | One rule for hydration: the first browser render equals the HTML; browser-only values apply afterwards through `useHydrated` or server-safe defaults | Prevents errors in Sentry, jumps and lost performance | Suppressing warnings: hides the problem | +| D7 | `Reveal` renders visible by default and hides only what is below the viewport after hydration | The build cannot know the screen size. Content in view never flashes, and content is visible without JavaScript | Hiding in HTML and revealing with JavaScript | +| D8 | `<noscript>` image next to `DeferredImage`'s image | Keeps deferred loading, which protects the largest paint, and gives visitors without JavaScript the photo | Loading all photos eagerly | +| D9 | Mobile menu without JavaScript through `<noscript>` with `:target` CSS | The JavaScript menu stays exactly as it is; `style-src` already allows this | `<details>`: would change the tested menu behaviour and ARIA for everyone | +| D10 | Own small preview server instead of `vite preview` | Lighthouse and browser tests must see the real rules (status 404, `.html` mapping) and headers, with no Node server in production | `vite preview`: SPA fallback, no real 404 | +| D11 | Browser tests with `playwright-core`, using the Chromium that the Lighthouse job already installs | Hydration and CSP only show in a real browser | jsdom: runs neither the CSP nor real hydration | +| D12 | The Start plugin stays out of Vitest, and `renderApp` renders without the document shell | The large existing test suite keeps testing components; `<html>` cannot render inside a test container | Rewriting the test setup | +| D13 | Sentry starts from a custom `src/client.tsx`, before hydration | Keeps catching errors from the start; it must not run during prerendering | Starting in an effect: misses early errors | + +## Consequences the Owner Should Know + +- **`/portfolio?shoot=gezin` and `/?pakket=gezin`**: the first paint shows the page without the filter or chosen package, and the filter or package applies right after hydration. On the portfolio, the visitor can briefly see all photos before the filter applies. This follows from one HTML file per page; the alternative would be separate pages per filter, which changes the URLs. +- **`/404` and `/404.html`**: these technically exist as files. Infrastructure Design makes sure they do not appear as normal pages, and the page stays `noindex` and out of the sitemap. +- **The 404 buttons under `/soorten-fotoshoots/`** appear right after hydration, and are missing without JavaScript. The page still has the normal menu links. +- **The IIS rules** can only be tested in production, as the test environment runs nginx. Infrastructure Design covers how to limit that risk, including whether the webhost allows the required setting. + +## Open Points for Construction + +| Point | Where settled | +|---|---| +| Custom client entry `src/client.tsx`: not tested in the spike, and how Start supports it is still to be confirmed | Unit 1 | +| JSON-LD through `StructuredData` under the CSP | Unit 1 browser test | +| `lazy()` contact form and code-split routes during prerendering | Unit 1 | +| Sitemap plugin with Start's separate client and server builds | Unit 1 | +| Main bundle and Lighthouse on the real app | Unit 1 decision gate | +| Flicker with Emotion styles on real pages | Unit 1 | +| Trailing slash and `/404` rules; webhost limits for 404 handling | Unit 3 Infrastructure Design | + +## Requirement Coverage + +| Requirements | Unit | Design | +|---|---|---| +| FR-PR-01 to 04, 19, 20 | 1 | D1 to D4 | +| FR-PR-05 to 08, 22 | 1 | D6, D13 | +| FR-PR-09, 10 | 2 | D7 | +| FR-PR-11 to 13 | 2 | D7 to D9 | +| FR-PR-14, 15 | 1 (route), 3 (servers) | D5, D10 | +| FR-PR-16 to 18 | 3 | D1, Infrastructure Design | +| FR-PR-21 | 2 | `preloadImage` | +| NFR-PR-P-01, P-02, S-01 | 3 | Final Lighthouse targets | +| NFR-PR-P-03, P-04 | 1 | Decision gate, D4 | +| NFR-PR-S-02, SEC-01, Q-03 | 1 | D10, D11 | +| NFR-PR-SEC-02 to 04, Q-01, Q-02, Q-04, Q-05 | 1, carried through 2 and 3 | D2, D12 | + +## Extension Compliance + +**Security Baseline** + +| Rule | Status | Note | +|---|---|---| +| SECURITY-03 | Compliant | Sentry stays the error logging; no new logging surface | +| SECURITY-04 | Compliant | Headers unchanged; `style-src 'unsafe-inline'` remains, already documented in `securityHeaders.ts` for Chakra and Emotion | +| SECURITY-09 | Compliant | Server build not deployed; generic error pages; directory handling covered in Infrastructure Design | +| SECURITY-10 | Compliant | New packages go through the lockfile and `audit:deps`; `seroval` patch kept. The repository generates no SBOM, as with earlier features | +| SECURITY-11 | Compliant | Misuse case: a path in the preview server escaping the client directory is a tested property. No public endpoints are added | +| SECURITY-13 | Compliant | No external scripts added; serialized data is public page data and read only from same-origin files | +| SECURITY-15 | Compliant | Build fails closed on script violations; the global error page stays | +| SECURITY-01, 02, 05, 06, 07, 08, 12, 14 | N/A | No data stores, intermediaries, APIs, access policies, network rules, accounts or security events in this feature | + +**Property-Based Testing** + +| Rule | Status | Note | +|---|---|---| +| PBT-01 | Compliant | Candidates in [services.md](services.md); confirmed per unit | +| PBT-09 | Compliant | fast-check is already a dependency and runs in Vitest | +| PBT-02 to 08, 10 | N/A at this stage | Enforced in Code Generation and Build and Test | diff --git a/aidlc-docs/features/prerendering/inception/application-design/component-dependency.md b/aidlc-docs/features/prerendering/inception/application-design/component-dependency.md new file mode 100644 index 0000000..a6c33b9 --- /dev/null +++ b/aidlc-docs/features/prerendering/inception/application-design/component-dependency.md @@ -0,0 +1,67 @@ +# Component Dependencies: prerendering + +```mermaid +graph TD + Vite["vite.config.ts"] + Router["src/router.tsx"] + Root["routes/__root.tsx"] + Client["src/client.tsx"] + Routes["Page routes and catch-all route"] + Hydrated["useHydrated and server-safe hooks"] + Display["Reveal, DeferredImage, NoScriptNav"] + Extract["config/externalizeInlineScripts.ts"] + Logic["config/inlineScripts.ts"] + Output["dist/client"] + Preview["config/previewServer.ts"] + Headers["config/securityHeaders.ts"] + ServerConfig["config/serverConfig.ts"] + E2E["e2e browser tests and Lighthouse"] + + Vite --> Router + Router --> Root + Client --> Router + Root --> Routes + Routes --> Hydrated + Routes --> Display + Display --> Hydrated + Vite --> Output + Extract --> Logic + Extract --> Output + Preview --> Output + Preview --> Headers + ServerConfig --> Headers + E2E --> Preview + + classDef build fill:#63b3ed,stroke:#2b6cb0,stroke-width:1px,color:#000; + classDef app fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000; + classDef infra fill:#fbd38d,stroke:#92400e,stroke-width:1px,color:#000; + classDef check fill:#f6e05e,stroke:#c05621,stroke-width:1px,color:#000; + class Vite,Extract,Logic,Output build; + class Router,Root,Client,Routes,Hydrated,Display app; + class Preview,Headers,ServerConfig infra; + class E2E check; +``` + +Text alternative: the Vite config drives the router, root route and pages, which use hydration-safe hooks and display components; the post-build step rewrites the client output; the preview server serves that output with the shared headers for the browser tests and Lighthouse. + +## Dependency matrix + +| Component | Depends on | Used by | Communication | +|---|---|---|---| +| `tanstackStart` plugin | `src/router.tsx`, route tree | Build | Build time | +| `__root.tsx` shell | `HeadContent`, `Scripts`, `ChakraProvider`, `theme.ts` | All pages | Render | +| `useHydrated` | React | `NotFound`, search-dependent routes, display components | Hook | +| `inlineScripts.ts` | None | Runner, tests | Pure function | +| `externalizeInlineScripts.ts` | `inlineScripts.ts`, file system | `pnpm build` | Build time | +| `previewServer.ts` | `securityHeaders.ts`, file system | Lighthouse, `e2e/` | HTTP | +| `serverConfig.ts` | `securityHeaders.ts` | `deploy/` | Generated files | + +## Unit boundaries + +| Unit | Owns | +|---|---| +| 1 | Build and entry, hydration safety, script step, preview server, browser tests, test setup, CI output path | +| 2 | `Reveal`, `DeferredImage`, `NoScriptNav`, no-JavaScript fallbacks, photo preload | +| 3 | `serverConfig.ts`, `deploy/`, CI upload order, Lighthouse targets | + +Units run in sequence, so shared files are not a merge concern. diff --git a/aidlc-docs/features/prerendering/inception/application-design/component-methods.md b/aidlc-docs/features/prerendering/inception/application-design/component-methods.md new file mode 100644 index 0000000..64b737b --- /dev/null +++ b/aidlc-docs/features/prerendering/inception/application-design/component-methods.md @@ -0,0 +1,73 @@ +# Component Methods: prerendering + +Signatures are the intended interfaces. Detailed rules follow in Functional Design. + +## `config/inlineScripts.ts` + +```ts +type MovedScript = { fileName: string; body: string }; +type ExternalizeResult = { html: string; moved: MovedScript[] }; + +// Replaces each executable inline script with a reference to a file named +// after its content hash; order and all other content stay as they are. +export function externalizeInlineScripts(html: string): ExternalizeResult; + +// Executable inline scripts still present; data blocks such as JSON-LD excluded. +export function findExecutableInlineScripts(html: string): string[]; +``` + +## `config/externalizeInlineScripts.ts` + +```ts +// Rewrites all HTML under clientDir and writes moved scripts to clientDir/assets. +// Exits non-zero when a page has no moved scripts or a violation remains. +export function externalizeOutput(clientDir: string): void; +``` + +## `config/previewServer.ts` + +```ts +// Maps a request path to a file following the nginx rules. +export function resolveRequest( + path: string, + fileExists: (file: string) => boolean, +): { file: string; status: 200 | 404 } | { redirect: string }; + +export function startPreviewServer(clientDir: string, port: number): Server; +``` + +## `src/router.tsx` + +```ts +export function getRouter(): AnyRouter; +``` + +## `src/hooks/useHydrated.ts` + +```ts +export default function useHydrated(): boolean; +``` + +## `src/components/Reveal` + +```ts +// Props are unchanged, so the 21 call sites stay as they are. +type RevealProps = BoxProps & { delay?: number }; +``` + +`useReveal<T>()` keeps returning `{ ref, visible }`. `visible` now starts as `true` and only becomes `false` when the element is below the viewport after hydration. + +## `src/components/DeferredImage` + +Props are unchanged. The rendered output gains a `<noscript>` image. + +## `src/seo.ts` + +```ts +// Adds the preload link for a page's first photo to its head. +export function preloadImage(src: string): HeadLink; +``` + +## Route `head()` + +Pages pass their first photo to `pageHead`, so the existing `pageHead(path)` helper stays the single source for head tags. The exact shape is settled in unit 2. diff --git a/aidlc-docs/features/prerendering/inception/application-design/components.md b/aidlc-docs/features/prerendering/inception/application-design/components.md new file mode 100644 index 0000000..40942ee --- /dev/null +++ b/aidlc-docs/features/prerendering/inception/application-design/components.md @@ -0,0 +1,49 @@ +# Components: prerendering + +All paths are under `web/`. "New" and "changed" refer to master at c4c2f83. + +## Build and entry (unit 1) + +| Component | Status | Responsibility | +|---|---|---| +| `vite.config.ts` | Changed | Adds the `tanstackStart` plugin with prerendering; the plugin is left out under Vitest | +| `src/router.tsx` | New | `getRouter()`: the router options now in `main.tsx` (scroll restoration, default error component) | +| `src/routes/__root.tsx` | Changed | Renders the document through `shellComponent` (`html`, `HeadContent`, providers, `Scripts`); imports the fonts | +| `src/client.tsx` | New | Browser entry: starts Sentry, then hydrates. Replaces `main.tsx` | +| `src/main.tsx`, `index.html` | Removed | Start generates the document; fallback tags are no longer needed | +| `config/inlineScripts.ts` | New | Pure logic: finds executable inline scripts in HTML and replaces them with file references | +| `config/externalizeInlineScripts.ts` | New | Post-build runner: applies the logic to all HTML in the output, writes the files, fails the build on a violation | +| `config/previewServer.ts` | New | Static server for Lighthouse and browser tests, following the nginx rules and using `securityHeaders` | +| `e2e/` | New | Browser tests against the built output: hydration, CSP, content without JavaScript | +| `src/test/renderApp.tsx` | Changed | Renders the app without the document shell in jsdom | + +## Hydration safety (unit 1) + +| Component | Status | Responsibility | +|---|---|---| +| `src/hooks/useHydrated.ts` | New | `false` during prerendering and the first browser render, then `true` | +| `routes/index.tsx`, `routes/contact.tsx`, `routes/portfolio.tsx` | Changed | Search values take effect after hydration, through `useHydrated` | +| `usePageLoaded`, `useInView` | Changed | Same first render on server and client | +| `NavigationBar`, `useReveal`, `useHeroSlider`, `TestimonialCarousel`, `ContactSection` | Changed | Breakpoint and media query values start from a server-safe value; `useHeroSlider` also reads `document.hidden` safely | +| `UmamiAnalytics` | Changed | Reads the hostname in its effect, not during render | +| `Footer`, `ContactDetails`, `lib/contactChannels.ts`, `ContactFormGate`, `ContactForm` | Changed | E-mail address only after hydration (FR-PR-22); `Footer` also renders the year safely | +| `src/routes/$.tsx` | New | Catch-all route rendering `NotFound`; source of `404.html` | +| `NotFound` | Changed | Shows the shoot section buttons after hydration | + +## Display (unit 2) + +| Component | Status | Responsibility | +|---|---|---| +| `Reveal`, `useReveal` | Changed | Visible in the HTML; only content below the viewport at load is hidden for its fade-in | +| `DeferredImage` | Changed | Real image for visitors without JavaScript; deferred loading with JavaScript stays | +| `NoScriptNav` | New | Rendered inside `<noscript>`: a menu link, a close link and the CSS that shows `#mobile-nav` through `:target` and expands the shoot submenu | +| `Hero`, `TestimonialCarousel`, `ContactSection` | Changed where needed | First slide, usable content and mailto route without JavaScript | +| `seo.ts` and route `head()` | Changed | Preload link for the first photo per page | + +## Hosting (unit 3) + +| Component | Status | Responsibility | +|---|---|---| +| `config/serverConfig.ts`, `deploy/` | Changed | URL rules and real 404 on nginx and IIS | +| `.gitea/workflows/continuous_integration.yaml` | Changed | Client output only; upload order for all HTML files. The output path itself changes in unit 1 | +| `lighthouserc.cjs`, `lighthouserc.desktop.cjs` | Changed | Preview server, final targets | diff --git a/aidlc-docs/features/prerendering/inception/application-design/services.md b/aidlc-docs/features/prerendering/inception/application-design/services.md new file mode 100644 index 0000000..104717d --- /dev/null +++ b/aidlc-docs/features/prerendering/inception/application-design/services.md @@ -0,0 +1,48 @@ +# Services: prerendering + +The site has no runtime services. The orchestration in this feature happens at build time and once in the browser. + +## Build pipeline + +`pnpm build` runs in this order: + +1. `tsc` +2. `vite build`: Start builds client and server, runs the server locally and prerenders each page to `dist/client` +3. `node config/externalizeInlineScripts.ts`: moves inline scripts and guards the result + +The server output in `dist/server` exists only during the build and is never deployed. + +## Page load in the browser + +```mermaid +sequenceDiagram + box rgba(246,224,94,0.4) Browser + participant V as Visitor + participant R as React + end + box rgba(99,179,237,0.4) Static host + participant H as nginx or IIS + end + V->>H: Request page + H-->>V: Complete HTML with styles + V->>H: Request first photo through preload + H-->>V: First photo + V->>H: Request scripts at end of body + H-->>V: Moved scripts and main bundle + R->>R: Hydrate with the same first render as the HTML + R->>R: Apply browser values such as search, breakpoints and fade-in +``` + +Text alternative: the host returns complete HTML, the first photo is preloaded, scripts load at the end of the body, React hydrates with the same first render as the HTML, and only then applies values that exist in the browser. + +## Pure functions and testable properties (PBT-01) + +Confirmed per unit in Functional Design and Infrastructure Design. + +| Function | Category | Property | +|---|---|---| +| `externalizeInlineScripts` | Invariant | Script order is preserved; all non-script content is unchanged | +| `externalizeInlineScripts` | Round-trip | Putting each moved body back at its reference restores the original HTML, apart from the tag's attributes | +| `externalizeInlineScripts` | Idempotence | Applying it twice gives the result of applying it once | +| `externalizeInlineScripts`, `findExecutableInlineScripts` | Invariant | Data blocks stay inline; no executable inline script remains in the result | +| `resolveRequest` | Invariant | Every path gives a file, a 404 or one redirect; a path never leaves the client directory | diff --git a/aidlc-docs/features/prerendering/inception/plans/application-design-plan.md b/aidlc-docs/features/prerendering/inception/plans/application-design-plan.md new file mode 100644 index 0000000..c3f506d --- /dev/null +++ b/aidlc-docs/features/prerendering/inception/plans/application-design-plan.md @@ -0,0 +1,23 @@ +# Application Design Plan: prerendering + +Depth: standard. No question file was created: each open choice was settled by testing it in a spike or is purely technical, and the owner's decisions are in requirements.md. The design states its decisions and the consequences the owner should know. Business rules follow in Functional Design (units 1 and 2) and Infrastructure Design (unit 3). + +## Plan + +- [x] Analyse context + - [x] Read requirements.md, execution-plan.md and the shared reverse-engineering artifacts + - [x] Read in code: `main.tsx`, `__root.tsx`, `vite.config.ts`, `index.html`, `serverConfig.ts`, `securityHeaders.ts`, `lighthouserc.cjs`, the CI workflow, `Reveal`, `useReveal`, `useInView`, `DeferredImage`, `NavigationBar`, `MobileNav`, `NotFound`, `renderApp` +- [x] Test the open technical choices in the spike + - [x] Hydration under the production `script-src`, with inline and with moved scripts + - [x] URLs without a trailing slash through `autoSubfolderIndex: false` + - [x] Three ways to build the 404 page + - [x] Search parameters during hydration +- [x] Generate `components.md` +- [x] Generate `component-methods.md` +- [x] Generate `services.md` +- [x] Generate `component-dependency.md` +- [x] Generate `application-design.md` +- [x] Validate design completeness and consistency + - [x] Every FR-PR and NFR-PR item has a home in a unit + - [x] Mermaid diagrams use `classDef` with `color:#000`, safe node ids and a text alternative + - [x] Security Baseline and PBT compliance summarised; no blocking findings diff --git a/aidlc-docs/features/prerendering/inception/plans/execution-plan.md b/aidlc-docs/features/prerendering/inception/plans/execution-plan.md new file mode 100644 index 0000000..0662d1a --- /dev/null +++ b/aidlc-docs/features/prerendering/inception/plans/execution-plan.md @@ -0,0 +1,171 @@ +# Execution Plan + +## Detailed Analysis Summary + +### Transformation Scope +- **Transformation Type**: Architectural, within one package (`web/`): from a client-rendered SPA to statically prerendered pages with hydration +- **Primary Changes**: TanStack Start replaces the plain Vite entry; a post-build step moves inline scripts to files; `Reveal` and other display components work from prerendered HTML; nginx, IIS and CI handle the new output +- **Related Components**: `vite.config.ts`, `main.tsx`, `index.html`, `routes/__root.tsx`, `AppShell`, `NavigationBar`/`MobileNav`, `Reveal`/`useReveal`, `DeferredImage`, `NotFound`, `seo.ts`, `config/serverConfig.ts`, `deploy/`, `lighthouserc*.cjs`, the CI workflow, the test setup + +### Change Impact Assessment +- **User-facing changes**: Yes. Faster first paint, a changed fade-in at the top of pages, a mobile menu that works without JavaScript, a real 404 +- **Structural changes**: Yes. New app entry and root document, new build output, a new post-build step +- **Data model changes**: No +- **API changes**: No +- **NFR impact**: Yes. Performance and SEO are the goal; the CSP must stay unchanged; the main bundle may grow + +### Component Relationships + +```mermaid +graph TD + Start["TanStack Start build"] + Entry["App entry and root document"] + Pages["Routes and shared components"] + Extract["Post-build script step"] + Config["serverConfig and deploy files"] + CI["CI workflow and Lighthouse"] + Hosts["nginx and IIS"] + Start --> Entry + Entry --> Pages + Start --> Extract + Extract --> CI + Config --> Hosts + CI --> Hosts + classDef core fill:#63b3ed,stroke:#2b6cb0,stroke-width:1px,color:#000; + classDef app fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000; + classDef infra fill:#fbd38d,stroke:#92400e,stroke-width:1px,color:#000; + class Start,Extract core; + class Entry,Pages app; + class Config,CI,Hosts infra; +``` + +Text alternative: the Start build drives the app entry and pages and feeds the post-build step; its output goes through CI to nginx and IIS, which are configured from serverConfig. + +| Component | Change type | Reason | Priority | +|---|---|---|---| +| Build, entry, root route | Major | Framework change | Critical | +| Post-build script step (new) | Major | Keep the CSP unchanged | Critical | +| `Reveal`, `DeferredImage`, `MobileNav`, breakpoint-dependent components | Minor to major | Prerendered HTML and working without JavaScript | Important | +| `serverConfig.ts`, `deploy/` | Minor | URLs and real 404 | Critical | +| CI workflow, Lighthouse configuration | Minor | New output path, targets | Critical | +| Test setup | Minor | Framework change | Important | + +### Risk Assessment +- **Risk Level**: High. System-wide change with unknowns; the spike covered two simple pages only +- **Rollback Complexity**: Moderate. All work is on one branch, and the deployed result is static, so an earlier release can be put back +- **Testing Complexity**: Complex. Hydration, CSP and no-JavaScript behaviour need a real browser against the built output on two server types + +## Workflow Visualization + +```mermaid +flowchart TD + Start(["User Request"]) + + subgraph INCEPTION["๐Ÿ”ต INCEPTION PHASE"] + WD["Workspace Detection<br/><b>COMPLETED</b>"] + RE["Reverse Engineering<br/><b>SKIP</b>"] + RA["Requirements Analysis<br/><b>COMPLETED</b>"] + US["User Stories<br/><b>SKIP</b>"] + WP["Workflow Planning<br/><b>IN PROGRESS</b>"] + AD["Application Design<br/><b>EXECUTE</b>"] + UG["Units Generation<br/><b>SKIP</b>"] + end + + subgraph CONSTRUCTION["๐ŸŸข CONSTRUCTION PHASE"] + FD["Functional Design<br/><b>EXECUTE, units 1 and 2</b>"] + NFRA["NFR Requirements<br/><b>SKIP</b>"] + NFRD["NFR Design<br/><b>SKIP</b>"] + ID["Infrastructure Design<br/><b>EXECUTE, unit 3</b>"] + CG["Code Generation<br/><b>EXECUTE</b>"] + BT["Build and Test<br/><b>EXECUTE</b>"] + end + + Start --> WD + WD --> RA + RA --> WP + WP --> AD + AD --> FD + FD --> ID + ID --> CG + CG --> BT + BT --> End(["Complete"]) + + style WD fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff + style RA fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff + style WP fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff + style CG fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff + style BT fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff + style AD fill:#FFA726,stroke:#E65100,stroke-width:3px,stroke-dasharray: 5 5,color:#000 + style FD fill:#FFA726,stroke:#E65100,stroke-width:3px,stroke-dasharray: 5 5,color:#000 + style ID fill:#FFA726,stroke:#E65100,stroke-width:3px,stroke-dasharray: 5 5,color:#000 + style RE fill:#BDBDBD,stroke:#424242,stroke-width:2px,stroke-dasharray: 5 5,color:#000 + style US fill:#BDBDBD,stroke:#424242,stroke-width:2px,stroke-dasharray: 5 5,color:#000 + style UG fill:#BDBDBD,stroke:#424242,stroke-width:2px,stroke-dasharray: 5 5,color:#000 + style NFRA fill:#BDBDBD,stroke:#424242,stroke-width:2px,stroke-dasharray: 5 5,color:#000 + style NFRD fill:#BDBDBD,stroke:#424242,stroke-width:2px,stroke-dasharray: 5 5,color:#000 + style INCEPTION fill:#BBDEFB,stroke:#1565C0,stroke-width:3px,color:#000 + style CONSTRUCTION fill:#C8E6C9,stroke:#2E7D32,stroke-width:3px,color:#000 + style Start fill:#CE93D8,stroke:#6A1B9A,stroke-width:3px,color:#000 + style End fill:#CE93D8,stroke:#6A1B9A,stroke-width:3px,color:#000 + + linkStyle default stroke:#333,stroke-width:2px +``` + +Text alternative: after Workflow Planning come Application Design, Functional Design (units 1 and 2), Infrastructure Design (unit 3), Code Generation and Build and Test; Reverse Engineering, User Stories, Units Generation and both NFR stages are skipped. + +## Phases to Execute + +### ๐Ÿ”ต INCEPTION PHASE +- [x] Workspace Detection (COMPLETED) +- [x] Reverse Engineering (SKIPPED) + - **Rationale**: Shared artifacts exist; team agreement is no full refresh per feature +- [x] Requirements Analysis (COMPLETED) +- [x] User Stories (SKIPPED) + - **Rationale**: One visitor type; the requirements are concrete and testable +- [x] Execution Plan (IN PROGRESS) +- [ ] Application Design - EXECUTE + - **Rationale**: New entry, root document and post-build step; component responsibilities and open technical choices need settling before code +- [ ] Units Planning / Units Generation - SKIP + - **Rationale**: The three units below follow from the dependencies and are fixed in this plan + +### ๐ŸŸข CONSTRUCTION PHASE +- [ ] Functional Design - EXECUTE for units 1 and 2, SKIP for unit 3 + - **Rationale**: Script extraction rules and fade-in, no-JavaScript and hydration behaviour need exact definitions and testable properties (PBT-01). Unit 3's logic is covered by Infrastructure Design; it records its properties there +- [ ] NFR Requirements - SKIP + - **Rationale**: The NFRs are in requirements.md and the stack is decided. PBT-09: fast-check is already a project dependency +- [ ] NFR Design - SKIP + - **Rationale**: NFR Requirements is skipped; script loading and measurement are settled in Application Design +- [ ] Infrastructure Design - EXECUTE for unit 3 + - **Rationale**: Server rules for URLs and 404 on nginx and IIS, deployed output and upload order change +- [ ] Code Generation - EXECUTE (ALWAYS) + - **Rationale**: Implementation planning and code generation needed +- [ ] Build and Test - EXECUTE (ALWAYS) + - **Rationale**: Build, test and verification needed, including the human task on the Pi + +### ๐ŸŸก OPERATIONS PHASE +- [ ] Deployment Setup, Monitoring Setup, Production Readiness Validation - SKIP + - **Rationale**: Operations Configuration = No. Necessary server and CI changes are part of unit 3 + +## Units of Work + +| Unit | Content | Requirements | Depends on | +|---|---|---|---| +| 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 | + +**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. + +## Package Change Sequence +Single package (`web/`). Units run in sequence; unit 3 sets the final Lighthouse targets, so it comes last. + +## Estimated Timeline +- **Total Stages Remaining**: 5 (Application Design, Functional Design, Infrastructure Design, Code Generation, Build and Test) +- **Estimated Duration**: No fixed estimate. Each push to the pull request starts a full CI run of about 20 minutes on the Pi + +## Success Criteria +- **Primary Goal**: All pages arrive as complete HTML, with better first paint and full crawlable content, under the unchanged CSP +- **Key Deliverables**: Start-based build, post-build script step with guard, adjusted components, updated server configuration and CI, new Lighthouse targets +- **Quality Gates**: `pnpm check` and CI pass; browser test of hydration under the production CSP; no-JavaScript content test; owner decisions recorded for any page below 0.9 +- **Integration Testing**: Built output tested on nginx (test environment) and against the IIS configuration +- **Operational Readiness**: Monitoring keeps working (FR-PR-08); no new monitoring is added diff --git a/aidlc-docs/features/prerendering/inception/requirements/requirement-clarification-questions.md b/aidlc-docs/features/prerendering/inception/requirements/requirement-clarification-questions.md new file mode 100644 index 0000000..df9cb6f --- /dev/null +++ b/aidlc-docs/features/prerendering/inception/requirements/requirement-clarification-questions.md @@ -0,0 +1,42 @@ +# Verduidelijkingsvragen: prerendering + +Twee van je antwoorden hebben nog een keuze nodig voordat ik de requirements kan schrijven. Je overige antwoorden zijn verwerkt. + +## Tegenstrijdigheid 1: TanStack Start en de CSP + +Je koos TanStack Start (vraag 2, B). Een vast uitgangspunt was dat de CSP ongewijzigd blijft. Die twee botsen, zoals een kleine proef-app laat zien: TanStack Start 1.169.4 met Chakra, getest in Chrome met onze `script-src`. + +**Wat de proef liet zien:** + +- **Statische HTML werkt:** Start maakt per pagina een HTML-bestand met de inhoud en de Chakra-stijlen, zonder Node-server. De bestanden komen in `dist/client` te staan, dus CI en deployment moeten mee veranderen. +- **Inline scripts:** elke pagina krijgt twee inline scripts. Het eerste bevat paginagegevens, waardoor de hash per pagina verschilt. +- **Met onze huidige CSP breekt de site:** de browser blokkeert de scripts, de app crasht en de inhoud verdwijnt van het scherm. +- **Scripts in eigen bestanden werken:** als een stap na de build die scripts naar eigen bestanden in `/assets` verplaatst, blijft de CSP gelijk. De knop en de link werkten dan, zonder CSP-meldingen. +- **Meer JavaScript:** de hoofdbundel van de proef is 165 kB gzip, bijna zonder eigen code. De huidige site, inclusief al zijn code, is ongeveer 149โ€“153 kB. Dit is een grove vergelijking, maar Start lijkt de bundel groter te maken, en dat werkt tegen het Lighthouse-doel van vraag 7. + +### Verduidelijkingsvraag 1 + +Hoe lossen we dit op? + +- A) Start gebruiken, met een stap na de build die de inline scripts naar eigen bestanden verplaatst. De CSP blijft gelijk. Nadeel: we leunen op hoe Start zijn scripts schrijft, dus een test moet dit bij elke upgrade bewaken, en elke pagina krijgt twee kleine extra verzoeken. Aanbevolen als je bij Start wilt blijven; dit is ook in de proef bewezen. +- B) Start gebruiken en de hashes van alle pagina's in de CSP zetten. Geen extra verzoeken, maar de CSP verandert bij elke inhoudswijziging, en de nginx-config op de Pi moet nu met de hand worden bijgewerkt. Dat is dus niet praktisch zonder ook die config te automatiseren. +- C) Toch de eigen Vite-build-stap (vraag 2, A). Geen inline scripts en waarschijnlijk minder JavaScript, maar geen standaardframework. Dit is ook de beste optie als de score het zwaarst weegt. +- D) `'unsafe-inline'` toestaan in `script-src`. Het is het eenvoudigst, maar verzwakt de bescherming tegen XSS en vraagt een gedocumenteerde uitzondering op SECURITY-04. Niet aanbevolen. +- X) Anders (beschrijf hieronder na de [Answer]:-tag) + +[Answer]: A + +## Onduidelijkheid 1: wat doet de build-trigger? + +Je koos ervoor nu al een manier in te bouwen om de build van buitenaf te starten (vraag 8, B). De CI-workflow heeft al een handmatige start (`workflow_dispatch`) met de keuzes `deploy_test` en `deploy_production`. Productie kan daarmee alleen vanaf een `release/*`-branch. Nog niet duidelijk is hoe ver een trigger mag gaan. + +### Verduidelijkingsvraag 2 + +Wat moet een trigger van buitenaf kunnen? + +- A) De bestaande `workflow_dispatch` hergebruiken en documenteren: een aanroep met een token met zo min mogelijk rechten bouwt en zet het resultaat op test. Productie blijft een handmatige stap. Aanbevolen: er komt niets nieuws bij om te beveiligen, en er gaat niets ongezien live. Of onze Gitea-versie deze aanroep ondersteunt, controleer ik nog. +- B) Zoals A, maar de trigger mag ook naar productie deployen, na de bestaande controles en Lighthouse. Een wijziging in het CMS staat dan automatisch live, maar het token wordt gevoeliger en de `release/*`-regel moet worden aangepast. +- C) Een eigen webhook-endpoint dat de build start. Dit vraagt een server die openbaar bereikbaar is, en die hebben we nu niet. +- X) Anders (beschrijf hieronder na de [Answer]:-tag) + +[Answer]: 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 diff --git a/aidlc-docs/features/prerendering/inception/requirements/requirement-verification-questions.md b/aidlc-docs/features/prerendering/inception/requirements/requirement-verification-questions.md new file mode 100644 index 0000000..682e25f --- /dev/null +++ b/aidlc-docs/features/prerendering/inception/requirements/requirement-verification-questions.md @@ -0,0 +1,129 @@ +# Vragen bij de requirements: prerendering + +Vul achter elke `[Answer]:` de letter van je keuze in. Past geen enkele optie, kies dan de laatste (Anders) en licht je keuze toe. Bij elke vraag staat welke optie ik aanbeveel en waarom. + +**Wat prerendering hier betekent:** nu krijgt een bezoeker een lege `index.html` en bouwt JavaScript daarna de pagina op. Met prerendering maakt de build voor elke pagina vast een HTML-bestand met de volledige inhoud. De browser en Google zien de tekst en foto's dan meteen, en daarna maakt React de pagina interactief ("hydration"). + +**Vaste uitgangspunten, hierover hoef je niets te beslissen:** + +- De URL's blijven gelijk, dus zonder `/` aan het eind (`/over-mij`). +- De hosting blijft statisch: nginx op test en IIS op productie, zonder Node-server. +- De strenge beveiligingsheaders (CSP) blijven zoals ze zijn. +- Links met een zoekparameter, zoals `/?pakket=...` en `/portfolio?shoot=...`, blijven werken. + +## Vraag 1 + +Welke pagina's krijgen een eigen vooraf gebouwd HTML-bestand? + +- A) Alle bestaande pagina's: de 10 geรฏndexeerde pagina's plus `/privacyverklaring` (aanbevolen: รฉรฉn werkwijze voor de hele site) +- B) Alleen de 10 geรฏndexeerde pagina's; `/privacyverklaring` blijft client-side +- C) Eerst alleen de homepage en de foto-pagina's die nu onder het Lighthouse-doel zitten +- X) Anders (beschrijf hieronder na de [Answer]:-tag) + +[Answer]: A + +## Vraag 2 + +Met welke techniek bouwen we de HTML? + +- A) Een eigen build-stap met Vite: React rendert elke route naar HTML en de bestaande app blijft verder hetzelfde. Dit is aanbevolen, want het is de kleinste wijziging, er zijn geen inline scripts nodig die de CSP blokkeert, en de pagina's halen nu nergens data op die mee moet. +- B) Overstappen op TanStack Start, het framework bij onze router, met statische prerendering. Dit is meer standaard, maar een grotere ombouw, en de inline scripts kunnen botsen met de CSP (nog te controleren). +- C) Na de build elke pagina in een headless browser openen en de HTML opslaan. De code blijft ongewijzigd, maar elke build heeft dan Chromium nodig en de opgeslagen stijlen en toestand zijn kwetsbaarder. +- X) Anders (beschrijf hieronder na de [Answer]:-tag) + +[Answer]: B + +## Vraag 3 + +Veel blokken faden nu in bij het scrollen (`Reveal`, 21 keer in 14 bestanden) en zijn tot dan onzichtbaar. In vooraf gebouwde HTML zouden ze onzichtbaar blijven totdat de JavaScript draait, en dat kost juist de snelheidswinst. Wat moet er gebeuren? + +- A) De animatie blijft, maar wat bij het laden al in beeld is, staat er direct zonder fade-in. Lager op de pagina blijft de fade-in werken. Aanbevolen: zo blijft het effect bestaan en verschijnt de eerste foto meteen. Dit vervangt je eerdere keuze om de fade-in op de eerste foto van de shootpagina's te laten staan. +- B) De fade-in overal behouden zoals nu, ook bovenaan. De grootste foto verschijnt dan nog steeds pas na de JavaScript, dus de winst op die pagina's blijft beperkt. +- C) De fade-in overal verwijderen +- X) Anders (beschrijf hieronder na de [Answer]:-tag) + +[Answer]: A + +## Vraag 4 + +Wat moet er werken bij een bezoeker of crawler zonder JavaScript? + +- A) Alle tekst, foto's en links zijn zichtbaar en werken. Menu's op mobiel, de slider, de lightbox en het formulier hebben JavaScript nodig. Aanbevolen: dit dekt SEO en link-previews zonder dat we onderdelen dubbel moeten bouwen. +- B) Zoals A, maar het mobiele menu werkt ook zonder JavaScript. Dat kost extra bouw- en testwerk. +- C) Geen eis: alleen de HTML voor crawlers telt, ook als er zonder JavaScript onderdelen verborgen blijven +- X) Anders (beschrijf hieronder na de [Answer]:-tag) + +[Answer]: B + +## Vraag 5 + +Een onbekende URL krijgt nu de app terug met HTTP-status 200, en de router toont daarna de 404-pagina. Google kan dat zien als een "soft 404". Wat wil je? + +- A) Een vooraf gebouwde 404-pagina met een echte HTTP-status 404, op nginx รฉn IIS (aanbevolen: goed voor SEO, en de serverconfig wordt toch al aangepast). De twee extra knoppen op de 404-pagina onder `/soorten-fotoshoots/` blijven: de pagina kan die pas in de browser tonen, omdat ze afhangen van de opgevraagde URL. +- B) Zo laten en dit later apart oppakken +- X) Anders (beschrijf hieronder na de [Answer]:-tag) + +[Answer]: A + +## Vraag 6 + +Horen responsive foto's (meerdere formaten per foto, zodat een telefoon kleinere bestanden laadt) bij deze feature? In `lighthouserc.cjs` staat dat minder bytes aan foto's de score op de gemeten foto-pagina's niet verbeterden, en de homepagefoto's zijn nog niet responsive. + +- A) Nee, alleen prerendering, plus een preload van de belangrijkste foto per pagina. Responsive foto's worden een aparte feature. Aanbevolen: het houdt deze feature klein en laat apart zien wat prerendering oplevert. +- B) Ja, responsive foto's horen er meteen bij +- X) Anders (beschrijf hieronder na de [Answer]:-tag) + +[Answer]: A + +## Vraag 7 + +De Lighthouse-doelen voor mobiel zijn tijdelijk verlaagd "tot prerendering" (homepage 0,8, foto-pagina's 0,85). Prerendering versnelt het eerste beeld, maar de hoeveelheid JavaScript blijft gelijk, dus 0,9 is niet gegarandeerd. Wat is het doel? + +- A) Mikken op 0,9 op alle pagina's. Haalt een pagina dat niet, dan laat ik je de meting zien en beslis jij per pagina. Aanbevolen: het doel blijft ambitieus en we verlagen niets ongemerkt. +- B) 0,9 is een harde eis: de feature is pas af als alle pagina's het halen, ook als daar extra werk aan de JavaScript-bundel voor nodig is +- C) Geen vast nieuw doel: de doelen verhogen tot wat de metingen laten zien +- X) Anders (beschrijf hieronder na de [Answer]:-tag) + +[Answer]: A + +## Vraag 8 + +De inhoud staat nu in de code, en later komt er een API/CMS. Met prerendering komt die inhoud vast in de HTML te staan. Hoe gaan we daar nu mee om? + +- A) De HTML wordt bij elke build gemaakt uit de huidige inhoud. Automatisch opnieuw bouwen bij een CMS-wijziging wordt onderdeel van de latere CMS-feature; ik leg dit als aandachtspunt vast. Aanbevolen: het CMS bestaat nog niet, dus we bouwen er nu niets voor. +- B) Nu al een manier inbouwen om de build van buitenaf te starten (voorbereiding op het CMS) +- X) Anders (beschrijf hieronder na de [Answer]:-tag) + +[Answer]: B + +## Vraag: Beveiligingsextensies + +Moeten de beveiligingsregels als harde vereisten worden afgedwongen voor deze feature? + +- A) Ja โ€” dwing alle BEVEILIGINGSREGELS af als blokkerende vereisten (aanbevolen voor productietoepassingen, en zo ook gekozen bij shoot-type-pages) +- B) Nee โ€” sla alle BEVEILIGINGSREGELS over (geschikt voor PoC's, prototypes en experimentele projecten) +- X) Anders (beschrijf hieronder na de [Answer]:-tag) + +[Answer]: A + +## Vraag: Property-Based Testing Extensie + +Moeten de property-based testing (PBT) regels worden afgedwongen voor deze feature? + +- A) Ja โ€” dwing alle PBT-regels af als blokkerende vereisten (aanbevolen voor projecten met bedrijfslogica, datatransformaties, serialisatie of stateful componenten; zo ook gekozen bij shoot-type-pages) +- B) Gedeeltelijk โ€” dwing PBT-regels alleen af voor pure functies en serialisatie round-trips (geschikt voor projecten met beperkte algoritmische complexiteit) +- C) Nee โ€” sla alle PBT-regels over (geschikt voor eenvoudige CRUD-applicaties, UI-only projecten of dunne integratielagen zonder significante bedrijfslogica) +- X) Anders (beschrijf hieronder na de [Answer]:-tag) + +[Answer]: A + +## Vraag: Operations-fase + +Moet deze feature na Construction door de Operations-fase (deployment en monitoring inrichten)? De aanpassingen aan de serverconfig en CI-workflow horen sowieso bij Construction. Alleen de nginx-config op de Pi moet daarna nog met de hand worden bijgewerkt. + +- A) Ja โ€” na Construction de Operations-fase uitvoeren (deployment en monitoring inrichten) +- B) Nee โ€” stoppen na Build and Test (aanbevolen: de bestaande deployment en monitoring blijven gelijk, en zo ook gekozen bij shoot-type-pages) +- C) Weet ik nog niet โ€” vraag het opnieuw na de Construction-fase +- X) Anders (beschrijf hieronder na de [Answer]:-tag) + +[Answer]: B diff --git a/aidlc-docs/features/prerendering/inception/requirements/requirements.md b/aidlc-docs/features/prerendering/inception/requirements/requirements.md new file mode 100644 index 0000000..5041ac6 --- /dev/null +++ b/aidlc-docs/features/prerendering/inception/requirements/requirements.md @@ -0,0 +1,148 @@ +# Requirements: prerendering + +## Intent Analysis + +- **User request**: "Ik wil een nieuwe feature toevoegen met aidlc. Namelijk de pre-rendering voor het verbeteren van performance en SEO." +- **Request type**: Enhancement with a framework migration (SPA with a plain Vite entry to TanStack Start with static prerendering) +- **Scope estimate**: System-wide within `web/`: app entry, root route, build, server configuration, CI, Lighthouse, and shared display components +- **Complexity estimate**: Complex (framework change, hydration behaviour, strict CSP, two web servers) +- **Depth**: Standard + +## Goal + +Every page is delivered as a complete HTML file, so visitors see content before the JavaScript runs and crawlers receive full text, links and metadata without executing JavaScript. The site stays statically hosted and its security headers stay as strict as they are now. + +## Decisions + +| Topic | Decision | Source | +|---|---|---| +| Pages | All 11 pages: 10 indexed plus `/privacyverklaring` | Q1 A | +| Technique | TanStack Start with static prerendering | Q2 B | +| CSP conflict | A post-build step moves Start's inline scripts to files in `/assets`; CSP unchanged | Clarification 1 A | +| Fade-in | Content in view at load appears at once; fade-in remains lower on the page. Replaces the owner's 2026-10-30 choice for the first story block | Q3 A | +| Without JavaScript | All text, photos and links work, and the mobile menu works | Q4 B | +| 404 | Prebuilt 404 page with a real HTTP 404 on nginx and IIS | Q5 A | +| Responsive photos | Out of scope; separate feature | Q6 A | +| Lighthouse | Aim for 0.9 everywhere; the owner decides per page on a miss | Q7 A | +| External build trigger | Not built. Page texts are largely fixed and the frontend is rebuilt through the normal flow. Revisit if the CMS makes such texts editable | Q8 B, narrowed by Clarification 2 | +| Extensions | Security Baseline and Property-Based Testing fully enforced | Opt-in | +| Operations phase | No | Opt-in | + +## Target Build Flow + +```mermaid +graph TD + Source["Routes and content"] --> Start["TanStack Start build with prerender"] + Start --> Html["HTML per page, including 404"] + Html --> Extract["Post-build step: inline scripts to /assets"] + Extract --> Guard["Build check: no executable inline script left"] + Guard --> Client["dist/client: deployable output"] + Start -.-> Server["dist/server: build only, never deployed"] + Client --> Nginx["nginx on test"] + Client --> Iis["IIS on production"] + 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 Source,Start,Html,Extract build; + class Guard check; + class Client,Nginx,Iis output; + class Server excluded; +``` + +Text alternative: Start renders each page to HTML, a post-build step moves inline scripts to files, a check guards the result, and only `dist/client` goes to nginx and IIS; `dist/server` is never deployed. + +## Functional Requirements + +### Prerendered pages + +- **FR-PR-01**: The build produces an HTML file for each of these pages, containing the page's full text, photo elements and links: `/`, `/over-mij`, `/portfolio`, `/soorten-fotoshoots`, the five `/soorten-fotoshoots/{newborn,zwangerschap,gezin,loveshoot,portret}` pages, `/contact` and `/privacyverklaring`. +- **FR-PR-02**: Each HTML file contains that page's own title, description, canonical URL, Open Graph tags and JSON-LD, without duplicate tags. The static fallback tags in `web/index.html` and their removal in `web/src/main.tsx` are no longer needed. +- **FR-PR-03**: A new route cannot be left out unnoticed: the build or a test fails when a page in `sitePages.ts` has no prerendered HTML file. +- **FR-PR-04**: `sitemap.xml` keeps its current content, and `/privacyverklaring` stays `noindex`. + +### Behaviour after loading + +- **FR-PR-05**: Every page becomes fully interactive after hydration, with no hydration errors in the browser console. Components whose output depends on the browser, such as media queries with `ssr: false` in `NavigationBar` and `useReveal`, must not cause a mismatch or a visible jump. +- **FR-PR-06**: Links with search parameters keep working: `/?pakket=...`, `/contact?pakket=...` and `/portfolio?shoot=...` show the same result as today, with the prerendered HTML as their first paint. +- **FR-PR-07**: Client-side navigation, scroll restoration, focus handling on route change, `/?pakket=...#contact` anchors and the error page behave as they do now. +- **FR-PR-08**: Sentry and Umami still start only in the browser and only on the test and production hostnames. + +### Fade-in + +- **FR-PR-09**: `Reveal` content is visible in the prerendered HTML. After loading, content already in view stays visible without animation; content below the viewport fades in on scroll as it does now. Because the build cannot know the visitor's screen size, this is decided in the browser, without first hiding content that is in view. +- **FR-PR-10**: With reduced motion, content is visible without animation, as it is now. + +### Without JavaScript + +- **FR-PR-11**: Without JavaScript, all text and photos are visible, including `Reveal` content and photos loaded through `DeferredImage`, and all links work. Exception: the e-mail address and its links appear only after hydration (FR-PR-22). +- **FR-PR-12**: Without JavaScript, the mobile menu opens and closes and every link in it can be reached, including the shoot submenu. Keyboard and screen reader behaviour with JavaScript stays as it is. +- **FR-PR-13**: The hero slider, testimonial carousel, lightbox and contact form may require JavaScript, but without it they show usable content: at least the first slide and the photos. +- **FR-PR-22**: The e-mail address stays out of the prerendered HTML and the serialized data, in readable and in mailto form, so the existing protection against harvesting remains. It appears after hydration. A build check fails if the assembled address occurs in any HTML file. Owner's decision (start-migration-fd-questions.md, A). + +### Not found + +- **FR-PR-14**: A prebuilt 404 page is served with HTTP status 404 for unknown URLs on nginx, IIS and the preview server used by Lighthouse. It is `noindex`. +- **FR-PR-15**: The existing 404 behaviour stays: under `/soorten-fotoshoots/` the two extra buttons appear (FR-ST-14), decided in the browser from the requested URL. + +### URLs and hosting + +- **FR-PR-16**: Page URLs stay without a trailing slash and are served directly with status 200, without a redirect. The nginx and IIS configuration stays generated from `web/config/serverConfig.ts`. +- **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. + +### 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. +- **FR-PR-20**: The build fails if an executable inline script remains in any HTML file, or if the step finds no scripts where it expects them, so a Start upgrade that changes the output format is noticed. + +### First photo + +- **FR-PR-21**: Each page whose largest visible element is a photo preloads that photo from the HTML. + +## Non-Functional Requirements + +### Performance + +- **NFR-PR-P-01**: The mobile Lighthouse performance target is 0.9 on all pages. The temporary exceptions in `web/lighthouserc.cjs` (home 0.8, photo pages 0.85) are removed for each page that reaches 0.9. For a page that misses it, the owner sees the measurement and decides; no target is lowered or left in place without that decision. +- **NFR-PR-P-02**: The desktop target stays 0.9. +- **NFR-PR-P-03**: The main bundle size and Lighthouse scores are measured before the change and after the first unit, and reported to the owner. If the framework change makes scores worse, the owner decides whether to continue before further work is built on it. +- **NFR-PR-P-04**: The moved scripts must not noticeably delay first paint. The effect is measured, and the design considers where they load. + +### SEO and accessibility + +- **NFR-PR-S-01**: Lighthouse accessibility, best practices and SEO stay at 1.0, as currently enforced. +- **NFR-PR-S-02**: Fetching any page without JavaScript returns its title, h1, main text and internal links in the HTML. An automated test checks this for all pages. + +### Security + +- **NFR-PR-SEC-01**: `script-src` and the rest of the production CSP stay unchanged. Pages run without CSP violations in a real browser under the production headers. +- **NFR-PR-SEC-02**: New dependencies are in the lockfile, pass `pnpm audit:deps`, and keep the existing `seroval` overrides in `pnpm-workspace.yaml`. Unused dependencies are removed. +- **NFR-PR-SEC-03**: Nothing from the server build, source maps of server code or build paths ends up in the deployed output. Error pages show no internal details. +- **NFR-PR-SEC-04**: Serialized data in the HTML contains only public page data. + +### Quality + +- **NFR-PR-Q-01**: `pnpm check` and CI pass, with the existing coverage thresholds. The existing test suite keeps running; test setup changes only where the framework change requires it. +- **NFR-PR-Q-02**: Pure logic in the post-build step is covered by example-based tests and fast-check property tests. Candidates are preserved script order, idempotence and unchanged data blocks; Functional Design confirms the list (PBT-01). +- **NFR-PR-Q-03**: A browser test verifies hydration and interaction under the production CSP against the built output, and runs in CI. +- **NFR-PR-Q-04**: The visual result matches the current site, with no flash of unstyled content. Chakra's styles are present in the HTML. +- **NFR-PR-Q-05**: Comments and documentation explain why the post-build step exists, and the shared reverse-engineering lines for this feature are updated. + +## Out of Scope + +- Responsive photos (separate feature) +- An external build trigger or webhook +- CMS or API integration +- The draft shoot page texts and photos (`features/shoot-type-pages/content-pending.md`); they are prerendered as they are at build time + +## Risks and Attention Points + +| Risk | Consequence | Handling | +|---|---|---| +| Start increases the JavaScript: the spike's main bundle was 165.0 kB gzip with almost no app code, versus about 149โ€“153 kB for the current site. A rough comparison | Less Lighthouse gain than hoped | NFR-PR-P-03: measure early; owner decides | +| The post-build step depends on Start's output format | An upgrade can break the site | FR-PR-20 and NFR-PR-Q-03 | +| Community reports of Emotion styling problems with Start's SSR; the spike showed styles in the HTML, but flicker on a real page is untested | Visible jump on load | NFR-PR-Q-04, checked in the first unit | +| The spike covered two simple pages, not this app's own components | Unknown hydration problems | First unit runs the real app | +| The nginx configuration on the Pi is updated by hand | Test shows old 404 or URL behaviour until updated | **HUMAN TASK**, documented in Build and Test | +| Later CMS content (galleries, packages) ends up in static HTML | Published changes stay invisible until a rebuild, unless fetched in the browser | Decide in the CMS feature; owner expects most page texts to stay fixed | -- 2.39.5 From c1e90f0768060920d705b05e9ae93b2151846d67 Mon Sep 17 00:00:00 2001 From: Sluijsens <bdslop@gmail.com> Date: Sat, 31 Oct 2026 17:58:54 +0100 Subject: [PATCH 02/49] Moves the app to TanStack Start with prerendering Every page is now built as HTML from sitePages.ts, with a catch-all route for 404.html. Hooks that read the browser during render are safe for prerendering. The script step that keeps the CSP intact follows, so this build still has inline scripts and is not deployable yet. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../features/prerendering/aidlc-state.md | 4 +- .../start-migration-code-generation-plan.md | 11 +- .../start-migration/code/proof-report.md | 33 ++ .../start-migration/code/verification-log.md | 51 +++ .../functional-design/business-rules.md | 2 +- web/.gitignore | 3 + web/config/sitemapPlugin.ts | 3 + web/index.html | 62 --- web/package.json | 5 +- web/pnpm-lock.yaml | 425 +++++++++++++++--- web/pnpm-workspace.yaml | 2 + web/src/app.test.tsx | 5 +- web/src/client.tsx | 18 + .../components/Analytics/UmamiAnalytics.tsx | 13 +- .../DeferredImage/DeferredImage.test.tsx | 6 +- web/src/components/Hero/useHeroSlider.ts | 29 +- .../NavigationBar/NavigationBar.tsx | 8 +- .../home/ContactSection/ContactSection.tsx | 5 +- .../home/Testimonials/TestimonialCarousel.tsx | 5 +- web/src/hooks/useHydrated.ts | 14 + web/src/hooks/useInView.ts | 22 +- web/src/hooks/usePageLoaded.test.tsx | 6 +- web/src/hooks/usePageLoaded.ts | 23 +- web/src/hooks/useReveal.test.tsx | 6 +- web/src/hooks/useReveal.ts | 5 +- web/src/main.tsx | 51 --- web/src/navigation.ts | 5 +- web/src/routeTree.gen.ts | 30 ++ web/src/router.tsx | 27 ++ web/src/routes/$.tsx | 9 + web/src/routes/__root.tsx | 48 +- web/src/test/renderApp.tsx | 28 +- web/vite.config.ts | 51 ++- 33 files changed, 746 insertions(+), 269 deletions(-) create mode 100644 aidlc-docs/features/prerendering/construction/start-migration/code/proof-report.md create mode 100644 aidlc-docs/features/prerendering/construction/start-migration/code/verification-log.md delete mode 100644 web/index.html create mode 100644 web/src/client.tsx create mode 100644 web/src/hooks/useHydrated.ts delete mode 100644 web/src/main.tsx create mode 100644 web/src/router.tsx create mode 100644 web/src/routes/$.tsx diff --git a/aidlc-docs/features/prerendering/aidlc-state.md b/aidlc-docs/features/prerendering/aidlc-state.md index 1d6ced4..06a40c8 100644 --- a/aidlc-docs/features/prerendering/aidlc-state.md +++ b/aidlc-docs/features/prerendering/aidlc-state.md @@ -5,8 +5,8 @@ - **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) +- **Current Stage**: CONSTRUCTION - Code Generation (unit 1): B0 done; batch B1 (early proof) done, committed; B2 and B3 running, then B4 +- **Branch**: feature/prerendering (from master c4c2f83); commits and pushes allowed for this feature (owner, 2026-10-31) - **Worktree**: K:\Development\SlpSoftware\Projects\AndreaSlopFotografie-prerendering ## Workspace State 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 e5b07d4..320c39f 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 @@ -162,7 +162,7 @@ PBT-02 (round-trip): P3, P10. PBT-03 (invariant): P1, P2, P5, P6, P8, P14, P16. The unknowns that can invalidate the design come first. Steps 3 to 6 prove Start, `getRouter`, `shellComponent`, `src/client.tsx` and the test harness on the real app before the mechanical conversions. If an unknown fails, apply the STOP rule: report to the main session; do not improvise. -### Step 3: Remove what makes prerendering throw [ ] +### Step 3: Remove what makes prerendering throw [x] - Executor: Sonnet. - Implements: BR-HYD-02, 03, 04, 05, 07, 08 (media and breakpoint part), 09, 15; BR-MON-03; FR-PR-05, 08. @@ -177,8 +177,9 @@ The unknowns that can invalidate the design come first. Steps 3 to 6 prove Start - `web/src/components/Analytics/UmamiAnalytics.tsx`: `hostname` prop optional without a default; the effect uses `hostname ?? window.location.hostname`. - Done when: no `ssr: false` remains in `web/src` (`grep -rn "ssr: false" web/src` empty), `pnpm exec tsc --noEmit` is clean, `pnpm lint` is clean, and **CP0**: `pnpm test` passes without test changes. If an old test fails because it relied on first-render media values, fix the test per BR-TST-02 (wrap in `act`/`waitFor`) and list the changed tests in the Record line. - Record: a line in `code/verification-log.md` is not needed yet; list changed old tests (if any) under the step in this plan. +- Record (2026-10-31): CP0 green, 113 files, 888 tests. Changed old tests: `usePageLoaded.test.tsx` and `DeferredImage.test.tsx` (the mocked `readyState` must become `complete` when the `load` event fires, as in a browser, because the hook now reads a store snapshot); `useReveal.test.tsx` (first render assumes no reduced motion, so an observer starts and is disconnected at once; test expects all observers disconnected instead of none created). -### Step 4: Start setup and first prerender of the real app (V1, V3, V5, V6, V7, V11, V13, V15, V17) [ ] +### Step 4: Start setup and first prerender of the real app (V1, V3, V5, V6, V7, V11, V13, V15, V17) [x] - Executor: Sonnet. - Implements: BR-BLD-02, 03, 05, 06, 07, 08, 09 (plugin part), 10 (n/a here), 11; BR-ENT-01 to 05; BR-404-01, 02; BR-MON-01; D1, D5, D13; FR-PR-01, 02, 03, 04, 08, 14 (route part); NFR-PR-Q-04, SEC-02. @@ -196,8 +197,9 @@ The unknowns that can invalidate the design come first. Steps 3 to 6 prove Start 11. Run `pnpm exec tsc --noEmit`, then `pnpm build`. Inspect `web/dist/client`: list all files; the HTML set must be exactly the 11 pages plus `404.html` (`index.html`, `over-mij.html`, `soorten-fotoshoots.html`, `soorten-fotoshoots/<5 shoots>.html`, `contact.html`, `privacyverklaring.html`, `portfolio.html`, `404.html`); `sitemap.xml` exists once in `dist/client`; for every HTML file list its inline `<script>` elements (position, attributes, first 80 characters of the body, body length) and whether any contains `<!--`, has `async`/`defer`, or is a module with relative imports (BR-SCR-05); check `/over-mij.html` for exactly one `<title>`, one `description`, one `canonical`, no `data-fallback`; grep the whole `dist/client` for the string `info@andreaslop.nl` (expected to appear until Step 17; note where) and for the repository path (V13). - Done when: **CP1 part 1**: `pnpm build` succeeds (prerender completed for all 12 files) and the verification log rows above are filled with evidence. A prerender error caused by something other than Step 3's list (for example a component that throws on the server) is fixed only if the fix is inside the rules of business-rules.md BR-HYD; otherwise STOP. - Record: `code/verification-log.md` rows V1, V3, V5, V6, V7, V11, V13, V15, V17; add the resolved package versions under the log's header. +- Record (2026-10-31): done, see the log (versions, zod override, router bump, `RoutePath` excludes `/$`, `@tanstack/router-plugin` removed). -### Step 5: Test harness for the new router (V2) [ ] +### Step 5: Test harness for the new router (V2) [x] - Executor: Sonnet. - Implements: BR-TST-01, 02; D12; NFR-PR-Q-01; V2. @@ -208,8 +210,9 @@ The unknowns that can invalidate the design come first. Steps 3 to 6 prove Start 4. Run `pnpm test`. - Done when: **CP1**: `pnpm build` green and `pnpm test` green (all pre-existing tests pass; list tests you had to change, with the reason, in the Record line). - Record: verification log V2 (what happened, which variant); changed tests. +- Record (2026-10-31): CP1 green (`pnpm build` 12 HTML files; `pnpm test` 113 files, 888 tests). V2: test shell variant in `renderApp`. Changed in this step: `app.test.tsx` register test ignores `/$`. `routeTree.gen.ts` diff: only the `/$` route and Start's `Register` declaration. -### Step 6: Proof report and decision to continue [ ] +### Step 6: Proof report and decision to continue [x] - Executor: Sonnet. - Do: write `aidlc-docs/features/prerendering/construction/start-migration/code/proof-report.md` (max one page): per V1, V2, V3, V5, V6, V7 the outcome in one or two sentences with evidence; the list of inline scripts per page as found; the resolved dependency versions; any deviation from the design (none expected). diff --git a/aidlc-docs/features/prerendering/construction/start-migration/code/proof-report.md b/aidlc-docs/features/prerendering/construction/start-migration/code/proof-report.md new file mode 100644 index 0000000..61d3440 --- /dev/null +++ b/aidlc-docs/features/prerendering/construction/start-migration/code/proof-report.md @@ -0,0 +1,33 @@ +# Proof report: Start on the real app (Steps 3 to 6) + +Date 2026-10-31. Details and evidence per point: [verification-log.md](verification-log.md). + +## Outcome + +`pnpm build` (tsc, Vite with Start, prerender) is green and writes 12 HTML files plus `sitemap.xml` into `dist/client`. `pnpm test` is green (113 files, 888 tests, same counts as the baseline). `pnpm lint`, `pnpm format:check` and `pnpm audit:deps` are green. V1, V2, V5, V6 and V7 are OK; there is no blocker for the parallel batches. + +## Per point + +- **V1 client entry**: Start uses `src/client.tsx` by file name; it calls `startSentry()` and then `hydrateRoot(document, <StrictMode><StartClient/></StrictMode>)`. Pages hydrate in Chrome without console errors (`/`, `/over-mij`, `/contact`, `/contact?pakket=gezin`). +- **V2 shell in jsdom**: Router does render `shellComponent`, but React 19 keeps `html`/`head`/`body` out of the container; it does set `lang` on the test document and double-wraps `ChakraProvider`. `renderApp` therefore gives its router a test shell (`HeadContent` + children). All old tests pass. +- **V3 inline scripts**: every page has the scroll-restoration script (613 chars), Start's bootstrap (`data-tsr-stream-part`, 916 to 1349 chars) and the boundary script (56 chars); `/contact` also has `<script id="_R_">requestAnimationFrame(...)` and the React completion runtime (845 chars). No `<!--`, no `async`/`defer` on inline scripts, no inline module scripts. JSON-LD blocks are data and stay. +- **V5 pages**: exactly the 11 pages plus `404.html`; `autoSubfolderIndex: false`, `crawlLinks: false`, `autoStaticPathsDiscovery: false`. +- **V6 splitting**: built into Start's plugin (one chunk per route); `@tanstack/router-plugin` removed as direct dependency. +- **V7 sitemap**: `this.environment.name === 'client'` works; one `sitemap.xml` in `dist/client`. + +## Resolved dependency versions + +`@tanstack/react-start` 1.169.4, `@tanstack/react-router` 1.170.46, `@tanstack/router-core` 1.171.39, `@tanstack/start-plugin-core` 1.171.55, `playwright-core` 1.55.0, vite 8.3.1, zod 4.6.7 (override). + +## Deviations from the design text (for the main session to confirm) + +1. `pnpm-workspace.yaml`: new scoped override `zod@4: ^4.6.6` because `pnpm audit:deps` reported a high advisory (zod < 4.6.6) in Start's dependency tree. Patch bump only. +2. `@tanstack/react-router` raised from `^1.170.39` to `1.170.46` (the plan's fallback) to avoid two router copies. +3. `src/navigation.ts`: `RoutePath` excludes `/$`, otherwise the page register would need an entry for the catch-all. +4. `renderApp` uses a test shell instead of dropping `shellComponent` (the shell is rendered by Router in jsdom without error, so the plan's "variant" is a variant of the shell, not of the route tree). +5. Old tests changed (BR-TST-02): `usePageLoaded.test.tsx` and `DeferredImage.test.tsx` (the mocked `readyState` stays `interactive` when the `load` event is dispatched; with a store-based hook the snapshot must change too, as it does in a real browser), `useReveal.test.tsx` (the first render now assumes no reduced motion, so an observer starts and is stopped again at once; the test now expects all observers disconnected instead of none created), `app.test.tsx` (register test ignores the catch-all `/$`). + +## Things seen that later steps must handle + +- Before Step 16, `/soorten-fotoshoots/onbekend` and `/portfolio?shoot=gezin` give React error #418 in Chrome (expected, those are Step 16 changes); the former also ends with two `<title>` and two robots metas after the client re-render. +- The e-mail address is in all 12 HTML files until Step 17. 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 new file mode 100644 index 0000000..061eaf6 --- /dev/null +++ b/aidlc-docs/features/prerendering/construction/start-migration/code/verification-log.md @@ -0,0 +1,51 @@ +# Verification log (V1 to V18) + +Unit 1 start-migration. Rows are filled in the step named in the plan (section 3.2). Status: OK, BLOCKED, DEVIATION, open. + +## Resolved versions (Step 4, 2026-10-31) + +| Package | Version | Note | +|---|---|---| +| `@tanstack/react-start` | 1.169.4 | added exact (pnpm wrote no caret) | +| `@tanstack/react-router` | 1.170.46 | was `^1.170.39` (resolved 1.170.39); raised to Start's own version, see note 1 | +| `@tanstack/router-core` | 1.171.39 | one copy for router and Start | +| `@tanstack/start-plugin-core` | 1.171.55 | transitive | +| `@tanstack/router-plugin` | 1.168.48 | transitive only (inside Start); the direct devDependency was removed | +| `playwright-core` | 1.55.0 | devDependency, exact | +| `zod` (4.x, transitive) | 4.6.7 | via override, see note 2 | +| `vite` | 8.3.1 | unchanged | + +Notes: + +1. With only `@tanstack/react-start` added, pnpm kept two router copies (`react-router` 1.170.39 for the app and 1.170.46 for Start). The plan's fallback (raise `@tanstack/react-router` to the spike's 1.170.46) removes the second copy. No peer conflict was reported. +2. `pnpm audit:deps` failed after adding Start: high advisory GHSA-mrhx-c7xc-m3w5 (zod < 4.6.6) through `@tanstack/start-plugin-core` and `router-generator`. Fixed by a patch bump only, with a scoped override in `web/pnpm-workspace.yaml` (`zod@4: ^4.6.6`, same pattern as the existing seroval overrides); zod 3 (Chakra CLI, Lighthouse) is not touched. Afterwards `pnpm audit:deps`: no known vulnerabilities. The main session should decide whether it accepts this extra override (BR-BLD-11 only names the seroval overrides as "stay"). +3. `seroval` and `seroval-plugins` overrides still apply (`pnpm why seroval`: 1.7.3, both router-core copies). + +## Table + +| V# | Point | Step | Outcome | Evidence | Status | +|---|---|---|---|---|---| +| V1 | Custom `src/client.tsx` hydrates with Start; `startSentry()` before hydration | 4 | Start picks `src/client.tsx` by name (default entry `client` in `srcDirectory`); it replaces the default entry, whose body is `startTransition(() => hydrateRoot(document, <StrictMode><StartClient /></StrictMode>))`. `startSentry()` runs at module level before that call. | Build output `dist/client/assets/index-*.js` contains `hydrateRoot` and the Sentry loader (`sentryClient-*.js` dynamic import). Chrome (playwright-core, system Chrome, static server, no CSP yet): `/`, `/over-mij`, `/contact`, `/contact?pakket=gezin` hydrate with no console error or warning. Not proven here: that Sentry initialises (only on the test and production hostnames, so a no-op on 127.0.0.1); unit tests of `monitoring/` cover that. | OK | +| V2 | `RouterProvider` in jsdom renders `shellComponent` | 5 | Yes, Router calls the root `shellComponent` (`Match.js`: `ShellComponent = route.isRoot && route.options.shellComponent`). React 19 treats `html`/`head`/`body` as singletons, so no `<html>` lands in the RTL container (container has 0 html/head/body), but it sets `lang="nl"` on `document.documentElement` and wraps `ChakraProvider` a second time. Variant used: `renderApp` replaces the root route's `shellComponent` by a test shell (`HeadContent` + children) on its router instance; production code untouched. | Probe test (removed) printed `shellComponent: function`, `html=0 head=0 body=0`, `document.documentElement lang=nl`. All 888 tests pass with the test shell (with the real shell, 45 of 46 in `app.test.tsx` passed; the one failure was the `/$` register test). | OK | +| V3 | Inline scripts per real page | 4 (first look), 13 (final) | Per page (12 files) the inline executable scripts are: (a) router scroll restoration, 613 chars, no attributes, same body everywhere; (b) Start bootstrap `data-tsr-stream-part=""`, 916 to 1349 chars, differs per page; (c) boundary `document.currentScript.remove();/*$tsr-stream-boundary*/`, 56 chars, same everywhere. `/contact` has two more (lazy form Suspense): `<script id="_R_">requestAnimationFrame(function(){$RT=performance.now()});</script>` (57 chars) and the React completion runtime `$RB=[];$RV=function(a){...` (845 chars). No `$RC` seen on other pages. External: `<script type="module" async src="/assets/index-*.js">` only (not touched by the runner). JSON-LD blocks (`application/ld+json`) are data and stay. BR-SCR-05: no inline body contains `<!--`, no classic inline script has `async`/`defer`, no inline `module` script exists. | `scratchpad/scripts.mjs` over `dist/client` (first look, to be repeated in Step 13 with the real runner). | OK (first look) | +| V4 | Minimum moved scripts | 13 | open (first look: every page has at least 3 inline executable scripts, so a minimum of one is far below what Start emits) | | open | +| 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/<shoot>.html` (12 files, no others). | 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 `<loc>`, no `/privacyverklaring`, no `/404`); `find dist -name sitemap.xml` gives only that file; `public/` has no `sitemap.xml`. | 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 | open | | open | +| V10 | Placeholder sizes, CLS below 0.01 | 17, 34 | open | | open | +| V11 | One title, one noindex meta | 4 (normal pages), 27 (`404.html`) | Normal pages in the prerendered HTML: one `<title>`, one `description`, one `canonical`, no `data-fallback`, a robots meta only on `/privacyverklaring`. `404.html`: one `<title>` ("Pagina niet gevonden \| Andrea Slop Fotografie") and one `<meta name="robots" content="noindex">`, no description or canonical. React writes `<meta charSet="utf-8">` 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 | +| V13 | Timestamps and build paths | 4, 13 | No build timestamp (`YYYY-MM-DDT..`) in any text file of `dist/client`, no `lastmod` in the sitemap. No repository path (`SlpSoftware`, `Projects/Andrea...`, `K:\`, worktree name) in any text file, no `.map` file. | `grep -rI` over `dist/client`. Re-check on the moved scripts in Step 13. | OK (first look) | +| 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: `<style data-emotion` x69 in `/over-mij`, x120 on `/`, plus the bundled stylesheet `<link rel="stylesheet" href="/assets/index-*.css">` (fonts and Chakra base). After hydration in Chrome `/over-mij` has 70 emotion style tags (one added by the client); no console warning. Visual check in Step 27. | `scripts.mjs`; Chrome probe. | OK (styles present); screenshots in 27 | +| V16 | `Intl` price text | 27 | open | | open | +| V17 | No `on*=` or `javascript:` | 13, 27 | None in the 12 HTML files (` on[a-z]+=` and `javascript:` both 0 matches). Step 13 repeats it on the runner output; Step 27 under the CSP. | `scripts.mjs` | OK (first look) | +| V18 | CI artifact layout | 28 | open | | open | + +## Other findings in Steps 3 to 5 + +- Email address: `info@andreaslop.nl` is in all 12 HTML files (footer link, contact details, gate notice) and nowhere in `dist/client/assets/*.js`, `robots.txt` or `sitemap.xml`. Expected until Step 17. +- The route tree gets a `/$` route, so `RoutePath = keyof FileRoutesByTo` would force a `/$` entry in `sitePages`. `src/navigation.ts` now uses `Exclude<keyof FileRoutesByTo, '/$'>`; the test "bevat precies de routes van de route tree" ignores `/$`. Not in the design text; needed for `tsc` (see proof-report). +- Start's `client.base` default is `/_build`, but it is not used in this build: assets stay under `/assets/` (needed for `/assets/inline-<hash>.js` of the runner). 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 02ec137..17d933c 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 @@ -68,7 +68,7 @@ Text alternative: every browser-dependent value starts from a default that equal | BR-BLD-08 | The Start plugin is not part of the Vitest configuration. `@tanstack/router-plugin` is replaced by Start's own generator; `routeTree.gen.ts` stays generated, committed and excluded from coverage. Route code splitting stays on. | D12; NFR-PR-P-03 | | BR-BLD-09 | `sitemap.xml` is emitted by `sitemapPlugin` in the client build only, so that it ends up in `dist/client` exactly once. The runner checks that the file exists and equals `sitemapXml(pageList(sitePages), siteUrl)` (SITEMAP_MISSING, SITEMAP_DIFFERS). | FR-PR-04 | | BR-BLD-10 | The CI job uploads `web/dist/client/` as the build artifact so that later jobs receive `index.html` at the artifact root as today. Upload order and server rules are unit 3. | FR-PR-17; unit boundaries | -| BR-BLD-11 | New packages are in `pnpm-lock.yaml` and pass `pnpm audit:deps`. The `seroval` and `seroval-plugins` overrides in `pnpm-workspace.yaml` stay. Packages no longer used (for instance `@tanstack/router-plugin` if Start replaces it) are removed. | NFR-PR-SEC-02 | +| BR-BLD-11 | New packages are in `pnpm-lock.yaml` and pass `pnpm audit:deps`. The `seroval` and `seroval-plugins` overrides in `pnpm-workspace.yaml` stay, and a scoped `zod@4` override patches an advisory in Start's dependency tree (GHSA-mrhx-c7xc-m3w5). `@tanstack/react-start` and `@tanstack/react-router` are pinned to exact versions, because the script step depends on Start's output format. Packages no longer used (for instance `@tanstack/router-plugin` if Start replaces it) are removed. | NFR-PR-SEC-02 | | BR-BLD-12 | Header comments in `inlineScripts.ts`, `externalizeInlineScripts.ts` and `previewServer.ts` explain why the step exists (strict `script-src 'self'`, Start emits inline scripts). The lines of this feature in `_shared/reverse-engineering/` are updated (entry, build, output, test setup). | NFR-PR-Q-05 | ### BR-ENT: Entry, router and document diff --git a/web/.gitignore b/web/.gitignore index 829d32d..a461765 100644 --- a/web/.gitignore +++ b/web/.gitignore @@ -27,3 +27,6 @@ dist-ssr coverage .lighthouseci lighthouse-reports + +# Gegenereerde cache van Start +.tanstack diff --git a/web/config/sitemapPlugin.ts b/web/config/sitemapPlugin.ts index 298d856..d1c5a11 100644 --- a/web/config/sitemapPlugin.ts +++ b/web/config/sitemapPlugin.ts @@ -5,11 +5,14 @@ import { sitemapXml } from '../src/sitemap.ts'; // Maakt bij elke build dist/sitemap.xml uit het pagina-register. Route-heads // lezen hetzelfde register, dus sitemap en noindex lopen nooit uit elkaar. +// Start bouwt een client- en een serveromgeving; alleen de client komt in +// dist/client terecht, dus alleen daar wordt het bestand gemaakt. export default function sitemapPlugin(): Plugin { return { name: 'slp-sitemap', apply: 'build', generateBundle() { + if (this.environment.name !== 'client') return; this.emitFile({ type: 'asset', fileName: 'sitemap.xml', diff --git a/web/index.html b/web/index.html deleted file mode 100644 index ff1cde1..0000000 --- a/web/index.html +++ /dev/null @@ -1,62 +0,0 @@ -<!doctype html> -<html lang="nl"> - <head> - <meta charset="UTF-8" /> - <link rel="icon" type="image/png" href="/favicon.png" /> - <link rel="apple-touch-icon" href="/favicon.png" /> - <meta name="viewport" content="width=device-width, initial-scale=1.0" /> - <!-- - Fallback voor crawlers en link-previews die geen JavaScript uitvoeren. - Zodra de app start, worden deze tags verwijderd (zie main.tsx) en zet - elke route zijn eigen titel en beschrijving (zie src/seo.ts). - --> - <title data-fallback> - Lifestyle fotograaf in Huizen | Andrea Slop Fotografie - - - - - - - - - - - - - - - - -
- - - diff --git a/web/package.json b/web/package.json index 687667f..2c80d32 100644 --- a/web/package.json +++ b/web/package.json @@ -28,7 +28,6 @@ "@iconify/react": "^6.0.2", "@lhci/cli": "^0.15.1", "@tanstack/react-router-devtools": "^1.167.2", - "@tanstack/router-plugin": "^1.168.40", "@testing-library/dom": "^10.4.2", "@testing-library/jest-dom": "^7.0.1", "@testing-library/react": "^16.3.3", @@ -44,6 +43,7 @@ "fast-check": "^4.10.2", "globals": "^17.13.0", "jsdom": "^30.1.3", + "playwright-core": "1.55.0", "prettier": "^3.9.9", "typescript": "~6.0.2", "typescript-eslint": "^8.71.2", @@ -56,7 +56,8 @@ "@fontsource/jost": "^5.3.0", "@fontsource/marcellus": "^5.3.0", "@sentry/react": "^11.8.0", - "@tanstack/react-router": "^1.170.39", + "@tanstack/react-router": "1.170.46", + "@tanstack/react-start": "1.169.4", "react": "^19.3.0", "react-dom": "^19.3.0" } diff --git a/web/pnpm-lock.yaml b/web/pnpm-lock.yaml index 66cc3a6..32c1156 100644 --- a/web/pnpm-lock.yaml +++ b/web/pnpm-lock.yaml @@ -166,6 +166,7 @@ overrides: source-map-js: ^1.2.2 seroval: ^1.6.8 seroval-plugins: ^1.6.8 + zod@4: ^4.6.6 importers: @@ -187,8 +188,11 @@ importers: specifier: ^11.8.0 version: 11.8.0(react@19.3.0) '@tanstack/react-router': - specifier: ^1.170.39 - version: 1.170.39(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + specifier: 1.170.46 + version: 1.170.46(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + '@tanstack/react-start': + specifier: 1.169.4 + version: 1.169.4(esbuild@0.28.2)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(rolldown@1.2.11)(supports-color@5.5.0)(vite@8.3.1(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)) react: specifier: ^19.3.0 version: 19.3.0 @@ -213,10 +217,7 @@ importers: version: 0.15.1(supports-color@5.5.0) '@tanstack/react-router-devtools': specifier: ^1.167.2 - version: 1.167.2(@tanstack/react-router@1.170.39(react-dom@19.3.0(react@19.3.0))(react@19.3.0))(@tanstack/router-core@1.171.32)(csstype@3.2.3)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) - '@tanstack/router-plugin': - specifier: ^1.168.40 - version: 1.168.40(@tanstack/react-router@1.170.39(react-dom@19.3.0(react@19.3.0))(react@19.3.0))(esbuild@0.28.2)(rolldown@1.2.11)(supports-color@5.5.0)(vite@8.3.1(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)) + version: 1.167.2(@tanstack/react-router@1.170.46(react-dom@19.3.0(react@19.3.0))(react@19.3.0))(@tanstack/router-core@1.171.39)(csstype@3.2.3)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) '@testing-library/dom': specifier: ^10.4.2 version: 10.4.2 @@ -262,6 +263,9 @@ importers: jsdom: specifier: ^30.1.3 version: 30.1.3 + playwright-core: + specifier: 1.55.0 + version: 1.55.0 prettier: specifier: ^3.9.9 version: 3.9.9 @@ -826,6 +830,22 @@ packages: resolution: {integrity: sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==} engines: {node: '>= 8'} + '@oozcitak/dom@2.0.2': + resolution: {integrity: sha512-GjpKhkSYC3Mj4+lfwEyI1dqnsKTgwGy48ytZEhm4A/xnH/8z9M3ZVXKr/YGQi3uCLs1AEBS+x5T2JPiueEDW8w==} + engines: {node: '>=20.0'} + + '@oozcitak/infra@2.0.2': + resolution: {integrity: sha512-2g+E7hoE2dgCz/APPOEK5s3rMhJvNxSMBrP+U+j1OWsIbtSpWxxlUjq1lU8RIsFJNYv7NMlnVsCuHcUzJW+8vA==} + engines: {node: '>=20.0'} + + '@oozcitak/url@3.0.0': + resolution: {integrity: sha512-ZKfET8Ak1wsLAiLWNfFkZc/BraDccuTJKR6svTYc7sVjbR+Iu0vtXdiDMY4o6jaFl5TW2TlS7jbLl4VovtAJWQ==} + engines: {node: '>=20.0'} + + '@oozcitak/util@10.0.0': + resolution: {integrity: sha512-hAX0pT/73190NLqBPPWSdBVGtbY6VOhWYK3qqHqtXQ1gK7kS2yz4+ivsN07hpJ6I3aeMtKP6J6npsEKOAzuTLA==} + engines: {node: '>=20.0'} + '@oxc-project/types@0.151.0': resolution: {integrity: sha512-J1yXrIlNDZVzE3ada310xeAw7nH8yCAyLPuUIsjKatFPmfn5bS1oW+cM+QsGOtVWd5nhSpbwZWx/rue+r5Z+PA==} @@ -1012,8 +1032,8 @@ packages: '@swc/helpers@0.5.23': resolution: {integrity: sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw==} - '@tanstack/history@1.162.4': - resolution: {integrity: sha512-utTS5L2OkeYUzXGohL1Z8sefu1GLNOJcxe8Hd6iIdc/Xo1K1nDB2JEp4iSFhvYh33xKC9V91TxrS8qfrpoKobQ==} + '@tanstack/history@1.162.5': + resolution: {integrity: sha512-w1+YvwmTkwt5n8yUqEH3IWZ9DsmorCZW/EQ3KYHnqEgIkOZpH54NvW6/Epq3Dzb8H0ifIeYX8PExvrNLIH5FIA==} engines: {node: '>=20.19'} '@tanstack/react-router-devtools@1.167.2': @@ -1028,21 +1048,69 @@ packages: '@tanstack/router-core': optional: true - '@tanstack/react-router@1.170.39': - resolution: {integrity: sha512-wLZi/hXW/kTeLlMIvI2VB8Oj38GLz8YkHmTM14lLScAzx79UZEwBHWMj6JZw/imuyuhrcmbe8KTFsFBHzJUftg==} + '@tanstack/react-router@1.170.46': + resolution: {integrity: sha512-ez1iNIhsPjGlaDHg3BXWs67EWVIYzB2tbopEHYDESdkO7owgkGb5de52+5Kv2v1fxdkggcNzo35bdk4arTVGQw==} engines: {node: '>=20.19'} peerDependencies: react: '>=18.0.0 || >=19.0.0' react-dom: '>=18.0.0 || >=19.0.0' - '@tanstack/react-store@0.11.1': - resolution: {integrity: sha512-HaIGKI3YLmjBYIvy5DFDY23oNaYZIsTZfngey07Uh5iLVJgM3bIGCnZeOFOqzjFld9JHWcaHJnasD/bKoGKwJQ==} + '@tanstack/react-start-client@1.168.44': + resolution: {integrity: sha512-WvrYhQ0EgwYpxnP9mFCCo+jctqXV3qq8GfIyiSGLiZzz4GDyw+GuQ2lyA3BTN64wbNNNVeMll+9PV5OlGYi2/w==} + engines: {node: '>=22.12.0'} + peerDependencies: + react: '>=18.0.0 || >=19.0.0' + react-dom: '>=18.0.0 || >=19.0.0' + + '@tanstack/react-start-rsc@0.1.65': + resolution: {integrity: sha512-5MmzmQoADjMA/d2XawkwKAkgBaQFrfifw/wn8qwCaLIntGYd2jkrCga/KdQW2xdjBu9IoP98WFhZilm7DfI/4g==} + engines: {node: '>=22.12.0'} + peerDependencies: + '@rspack/core': '>=2.0.0-0' + '@vitejs/plugin-rsc': '>=0.5.30' + react: '>=18.0.0 || >=19.0.0' + react-dom: '>=18.0.0 || >=19.0.0' + react-server-dom-rspack: '>=0.0.2' + peerDependenciesMeta: + '@rspack/core': + optional: true + '@vitejs/plugin-rsc': + optional: true + react-server-dom-rspack: + optional: true + + '@tanstack/react-start-server@1.167.52': + resolution: {integrity: sha512-131olF9oWx1CqZg8JYmIJbLNKqS/vN3UbYuc9a++pRtvfY67tpPmPzuYj4OXSxRAYalGW3f1yYlFozxqE1LE7w==} + engines: {node: '>=22.12.0'} + peerDependencies: + react: '>=18.0.0 || >=19.0.0' + react-dom: '>=18.0.0 || >=19.0.0' + + '@tanstack/react-start@1.169.4': + resolution: {integrity: sha512-+DmlNPeQ1rsvo025I79GrlNgDm+zVCVAGg9gMIGmAevK2TJRMpKahgEKZZ1j4VSxDxjfTpkfLyuXiUxxjMJCaw==} + engines: {node: '>=22.12.0'} + peerDependencies: + '@rsbuild/core': ^2.0.0 + '@vitejs/plugin-rsc': '*' + react: '>=18.0.0 || >=19.0.0' + react-dom: '>=18.0.0 || >=19.0.0' + vite: '>=8.0.0' + peerDependenciesMeta: + '@rsbuild/core': + optional: true + '@vitejs/plugin-rsc': + optional: true + vite: + optional: true + + '@tanstack/react-store@0.11.2': + resolution: {integrity: sha512-oj5O5DmiMWE+ih+SioX2ayC1kbK7d3fpLx0B75fPJr9nY3zU+hoW010yr64qXsY/9fyiLVE2bn5mGNV3owm8RQ==} peerDependencies: react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 - '@tanstack/router-core@1.171.32': - resolution: {integrity: sha512-X86Jqk3vB2KJcUfS6oLi7B7yxbaa59QEhZRPPP1fRx3k+Jw/Fu1UYVBcRtdwK/OccQnrlQdVoKvNO3QXmyEBOw==} + '@tanstack/router-core@1.171.39': + resolution: {integrity: sha512-qUhoJ0meuSUqGYQbHbcJYdASr06YtK+bulbj6vtrhKYFkLgkSsZ6tXmMyym7sFxiSJSPYgasgozrL01LyyR/6A==} engines: {node: '>=20.19'} '@tanstack/router-devtools-core@1.168.2': @@ -1055,16 +1123,16 @@ packages: csstype: optional: true - '@tanstack/router-generator@1.167.38': - resolution: {integrity: sha512-lkqgFleDgfkW+QONVMKBs+ZGDUF0v9R9FkplS/GZvKDFpfnu+tZxmGlV2pryU1TDxyuSyjh56AtIla3NMrlScw==} + '@tanstack/router-generator@1.167.46': + resolution: {integrity: sha512-JSailAThcqPvqBzE3+MhNh6zQyZM2IdmIsHOxZgAc061Lh++SZqamNm/Whe7QNXWK5sLP4E0J1F8AI0hP8wTSw==} engines: {node: '>=20.19'} - '@tanstack/router-plugin@1.168.40': - resolution: {integrity: sha512-ifiXjjR4uivxwRDhgYAcfyrcu+Mwx+vlG0QjjQ7N5C5sKmzpt5UtsL21TNVvZDSZl2Vae8DcL84Z02fOs8ZZMQ==} + '@tanstack/router-plugin@1.168.48': + resolution: {integrity: sha512-oLDEZO/vhvF5JLrQ6qMNYcCjMMhlHA0Byx6ZXl9AHJ6qVLRxUeCU41vlZQ4buisONY2p0Zl9O09/qwLiVrIBCQ==} engines: {node: '>=20.19'} peerDependencies: '@rsbuild/core': '>=1.0.2 || ^2.0.0' - '@tanstack/react-router': ^1.170.38 + '@tanstack/react-router': ^1.170.46 vite: '>=5.0.0 || >=6.0.0 || >=7.0.0 || >=8.0.0' vite-plugin-solid: ^2.11.10 || ^3.0.0-0 webpack: '>=5.92.0' @@ -1080,12 +1148,40 @@ packages: webpack: optional: true - '@tanstack/router-utils@1.162.3': - resolution: {integrity: sha512-Icb0xGuG1+54IV0WMLRcc3ErTx2HeJWyPG661FkQ8UT6guoBq1FJjFRqlG/JS0xi4mFFkBhvwO7tbLa32f3yxA==} + '@tanstack/router-utils@1.162.4': + resolution: {integrity: sha512-3TSH3rwAQTqQOtTBF8IXMFXmGNJWnjwIm+l87uguyC/of0pSRKcU9GJrozaf0fY9it8dLQvUZJA2MOlfqbW1sA==} engines: {node: '>=20.19'} - '@tanstack/store@0.11.1': - resolution: {integrity: sha512-mzTOBhypOuDJAy/D8n2MfUZ1HFkXnmSETviRyhqEC8LUE7/IZQExOTxMANj3KjTofYTkFNpBY67qaVrT41YccA==} + '@tanstack/start-client-core@1.170.39': + resolution: {integrity: sha512-G0VJbZFf9/dYomQjZkWapaTjkjEI4vbk1jnxhhVtQ3nTRb3sIRc196j+S+qZcySfEV5W9TJHu4KatjSzjZZQwQ==} + engines: {node: '>=22.12.0'} + + '@tanstack/start-fn-stubs@1.162.0': + resolution: {integrity: sha512-QWfUZ3Yo923tdQn38LyKMU8rcTw69zc+T4dAvgTWV4O56SqFRsGfS0lSWIMhJRwXIx/bvdi7nTUBDdZtTHtpTQ==} + engines: {node: '>=22.12.0'} + + '@tanstack/start-plugin-core@1.171.55': + resolution: {integrity: sha512-8FjTuuxIE8MNJoveXahZPBCfEpm8p9tMFyWTvbllfqlysdhry34rw/nCwULfcVwTG39ezXEu/RYE83NSV+miog==} + engines: {node: '>=22.12.0'} + peerDependencies: + '@rsbuild/core': ^2.0.0 + vite: '>=8.0.0' + peerDependenciesMeta: + '@rsbuild/core': + optional: true + vite: + optional: true + + '@tanstack/start-server-core@1.169.45': + resolution: {integrity: sha512-fKySLUGIy7aVYR6ZRgjC19TQdsZ+q/54M9hVfHrJQQVpM/T5qq5djZ3gsqhugmrWP+gyd9qpa9D6cxRtR6CJvg==} + engines: {node: '>=22.12.0'} + + '@tanstack/start-storage-context@1.167.41': + resolution: {integrity: sha512-MY+Z4cZBPbH7hjORcROMX7K3kV1X25ArFKmRbks+EukPP9UVwCXbZFVzYkTt1u0AHthvQTcpa4J9B9i0o6fEnA==} + engines: {node: '>=22.12.0'} + + '@tanstack/store@0.11.2': + resolution: {integrity: sha512-sJ4mjol8uQsHV0gOJzzjwXfh2Fwm+Sz0+8deqiTm4jGbMdjzNSW+xZCFm0kUa870uhd8yi+DpKnZb5Kc4apa0Q==} '@tanstack/virtual-file-routes@1.162.0': resolution: {integrity: sha512-uhOeFyxLcU41HzvrxsGpiWdcMbScY1EDgbZ5K7DVRMYInbLYWAC0EA/kx9wXAoSM8q82bUG2hRl8+EAjE6XAbA==} @@ -2008,8 +2104,8 @@ packages: devtools-protocol@0.0.1608973: resolution: {integrity: sha512-Tpm17fxYzt+J7VrGdc1k8YdRqS3YV7se/M6KeemEqvUbq/n7At1rWVuXMxQgpWkdwSdIEKYbU//Bve+Shm4YNQ==} - diff@8.0.4: - resolution: {integrity: sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw==} + diff@9.0.0: + resolution: {integrity: sha512-svtcdpS8CgJyqAjEQIXdb3OjhFVVYjzGAPO8WGCmRbrml64SPw/jJD4GoE98aR7r25A0XcgrK3F02yw9R/vhQw==} engines: {node: '>=0.3.1'} dom-accessibility-api@0.5.16: @@ -2202,6 +2298,9 @@ packages: resolution: {integrity: sha512-Bdcs4+3qlpVlx2NRn6fgX2Ue2/gGRaPeawebgclM0ERSCqDpA+owF1fdPwjJUTAJWMTuAaxjDf+hzb0/4eKvvw==} engines: {node: '>= 0.10.0'} + exsolve@1.2.0: + resolution: {integrity: sha512-h1pQPR9XoeSMdntRNCjyTznaume4UpfXrULBnlkZ2CUM/G5eSa+pBByGldO5uR8dxbPC+OuJXsPPNf+JZ81ADg==} + external-editor@3.1.0: resolution: {integrity: sha512-hMQ4CX1p1izmuLYyZqLMO/qGNw10wSv9QDCPfzXfyFrOaCSSoRfqE1Kf1s5an66J5JZC62NewG+mK49jOCtQew==} engines: {node: '>=4'} @@ -2255,6 +2354,9 @@ packages: picomatch: optional: true + fetchdts@0.2.0: + resolution: {integrity: sha512-PJb4ZTGT2/wK78RmVrxZITStWabhZlKBsL52VOgq+c7clEkdHdEB+0rtzrXCbZJqeYJj+IwNWYqB5/G6vouA6A==} + figures@2.0.0: resolution: {integrity: sha512-Oa2M9atig69ZkfwiApY8F2Yy+tzMbazyvqv21R0NsSC8floSOC09BbT1ITWAdoMGQvJ/aZnR1KMwdx9tvHnTNA==} engines: {node: '>=4'} @@ -3152,6 +3254,11 @@ packages: resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} engines: {node: '>=12'} + playwright-core@1.55.0: + resolution: {integrity: sha512-GvZs4vU3U5ro2nZpeiwyb0zuFaqb9sUiAJuyrWpcGouD8y9/HLgGbNRjIph7zU9D3hnPaisMl9zG9CgFi/biIg==} + engines: {node: '>=18'} + hasBin: true + possible-typed-array-names@1.1.0: resolution: {integrity: sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==} engines: {node: '>= 0.4'} @@ -3459,6 +3566,10 @@ packages: resolution: {integrity: sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==} engines: {node: '>=0.10.0'} + source-map@0.7.6: + resolution: {integrity: sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==} + engines: {node: '>= 12'} + speedline-core@1.4.3: resolution: {integrity: sha512-DI7/OuAUD+GMpR6dmu8lliO2Wg5zfeh+/xsdyJZCzd8o5JgFUjCeLsBDuZjIQJdwXS3J0L/uZYrELKYqx+PXog==} engines: {node: '>=8.0'} @@ -3466,6 +3577,11 @@ packages: sprintf-js@1.0.3: resolution: {integrity: sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==} + srvx@1.0.8: + resolution: {integrity: sha512-ngFS/J6St4PJfHRHGjr78xkPPtbyXtdMOLNE4x/XZunEK3OhV7aGUWMHf9WTUEy6wm1U0W4okkd82ZFFWRVQTw==} + engines: {node: '>=20.16.0'} + hasBin: true + statuses@2.0.2: resolution: {integrity: sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==} engines: {node: '>= 0.8'} @@ -3677,6 +3793,9 @@ packages: engines: {node: '>=14.17'} hasBin: true + ufo@1.6.4: + resolution: {integrity: sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA==} + unbox-primitive@1.1.0: resolution: {integrity: sha512-nWJ91DjeOkej/TA8pXQ3myruKpKEYgqvpw9lz4OPHj/NWFNluYrjbz9j01CJ8yKQd2g4jFoOkINCTW2I5LEEyw==} engines: {node: '>= 0.4'} @@ -3813,6 +3932,14 @@ packages: yaml: optional: true + vitefu@1.1.3: + resolution: {integrity: sha512-ub4okH7Z5KLjb6hDyjqrGXqWtWvoYdU3IGm/NorpgHncKoLTCfRIbvlhBm7r0YstIaQRYlp4yEbFqDcKSzXSSg==} + peerDependencies: + vite: ^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + vite: + optional: true + vitest@5.0.5: resolution: {integrity: sha512-cPODOMF8YnkiiYtDdHo6n4wWmBrOBBbOIYH2d33M4l3CdNn72h+qMmO6uXffUN6A5AZFXNND/d+krS9mgkXRfg==} engines: {node: ^22.12.0 || ^24.0.0 || >=26.0.0} @@ -3967,6 +4094,10 @@ packages: resolution: {integrity: sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==} engines: {node: '>=18'} + xmlbuilder2@4.0.3: + resolution: {integrity: sha512-bx8Q1STctnNaaDymWnkfQLKofs0mGNN7rLLapJlGuV3VlvegD7Ls4ggMjE3aUSWItCCzU0PEv45lI87iSigiCA==} + engines: {node: '>=20.0'} + xmlchars@2.2.0: resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==} @@ -4014,13 +4145,13 @@ packages: resolution: {integrity: sha512-Q6/nZLe6jxuU80qb/4uJ4t5v2VEZ44lzQjPDhYJNztRQ4wyWc6VF3D3Kb/fAuPetZQnhS3hnajCf9CsWesghLQ==} engines: {node: '>=18.0.0'} peerDependencies: - zod: ^3.25.0 || ^4.0.0 + zod: ^4.6.6 zod@3.25.76: resolution: {integrity: sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==} - zod@4.6.5: - resolution: {integrity: sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==} + zod@4.6.7: + resolution: {integrity: sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==} snapshots: @@ -4707,6 +4838,23 @@ snapshots: '@nodelib/fs.scandir': 2.1.5 fastq: 1.20.3 + '@oozcitak/dom@2.0.2': + dependencies: + '@oozcitak/infra': 2.0.2 + '@oozcitak/url': 3.0.0 + '@oozcitak/util': 10.0.0 + + '@oozcitak/infra@2.0.2': + dependencies: + '@oozcitak/util': 10.0.0 + + '@oozcitak/url@3.0.0': + dependencies: + '@oozcitak/infra': 2.0.2 + '@oozcitak/util': 10.0.0 + + '@oozcitak/util@10.0.0': {} + '@oxc-project/types@0.151.0': {} '@pandacss/is-valid-prop@1.11.1': {} @@ -4860,76 +5008,145 @@ snapshots: dependencies: tslib: 2.8.1 - '@tanstack/history@1.162.4': {} + '@tanstack/history@1.162.5': {} - '@tanstack/react-router-devtools@1.167.2(@tanstack/react-router@1.170.39(react-dom@19.3.0(react@19.3.0))(react@19.3.0))(@tanstack/router-core@1.171.32)(csstype@3.2.3)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)': + '@tanstack/react-router-devtools@1.167.2(@tanstack/react-router@1.170.46(react-dom@19.3.0(react@19.3.0))(react@19.3.0))(@tanstack/router-core@1.171.39)(csstype@3.2.3)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)': dependencies: - '@tanstack/react-router': 1.170.39(react-dom@19.3.0(react@19.3.0))(react@19.3.0) - '@tanstack/router-devtools-core': 1.168.2(@tanstack/router-core@1.171.32)(csstype@3.2.3) + '@tanstack/react-router': 1.170.46(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + '@tanstack/router-devtools-core': 1.168.2(@tanstack/router-core@1.171.39)(csstype@3.2.3) react: 19.3.0 react-dom: 19.3.0(react@19.3.0) optionalDependencies: - '@tanstack/router-core': 1.171.32 + '@tanstack/router-core': 1.171.39 transitivePeerDependencies: - csstype - '@tanstack/react-router@1.170.39(react-dom@19.3.0(react@19.3.0))(react@19.3.0)': + '@tanstack/react-router@1.170.46(react-dom@19.3.0(react@19.3.0))(react@19.3.0)': dependencies: - '@tanstack/history': 1.162.4 - '@tanstack/react-store': 0.11.1(react-dom@19.3.0(react@19.3.0))(react@19.3.0) - '@tanstack/router-core': 1.171.32 + '@tanstack/history': 1.162.5 + '@tanstack/react-store': 0.11.2(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + '@tanstack/router-core': 1.171.39 isbot: 5.2.2 react: 19.3.0 react-dom: 19.3.0(react@19.3.0) - '@tanstack/react-store@0.11.1(react-dom@19.3.0(react@19.3.0))(react@19.3.0)': + '@tanstack/react-start-client@1.168.44(react-dom@19.3.0(react@19.3.0))(react@19.3.0)': dependencies: - '@tanstack/store': 0.11.1 + '@tanstack/react-router': 1.170.46(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + '@tanstack/router-core': 1.171.39 + '@tanstack/start-client-core': 1.170.39 + react: 19.3.0 + react-dom: 19.3.0(react@19.3.0) + + '@tanstack/react-start-rsc@0.1.65(esbuild@0.28.2)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(rolldown@1.2.11)(supports-color@5.5.0)(vite@8.3.1(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0))': + dependencies: + '@tanstack/react-router': 1.170.46(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + '@tanstack/router-core': 1.171.39 + '@tanstack/router-utils': 1.162.4(supports-color@5.5.0) + '@tanstack/start-client-core': 1.170.39 + '@tanstack/start-fn-stubs': 1.162.0 + '@tanstack/start-plugin-core': 1.171.55(@tanstack/react-router@1.170.46(react-dom@19.3.0(react@19.3.0))(react@19.3.0))(esbuild@0.28.2)(rolldown@1.2.11)(supports-color@5.5.0)(vite@8.3.1(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)) + '@tanstack/start-storage-context': 1.167.41 + pathe: 2.0.3 + react: 19.3.0 + react-dom: 19.3.0(react@19.3.0) + transitivePeerDependencies: + - '@farmfe/core' + - '@rsbuild/core' + - bun-types-no-globals + - esbuild + - rolldown + - rollup + - supports-color + - unloader + - vite + - vite-plugin-solid + - webpack + + '@tanstack/react-start-server@1.167.52(react-dom@19.3.0(react@19.3.0))(react@19.3.0)': + dependencies: + '@tanstack/react-router': 1.170.46(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + '@tanstack/router-core': 1.171.39 + '@tanstack/start-server-core': 1.169.45 + react: 19.3.0 + react-dom: 19.3.0(react@19.3.0) + + '@tanstack/react-start@1.169.4(esbuild@0.28.2)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(rolldown@1.2.11)(supports-color@5.5.0)(vite@8.3.1(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0))': + dependencies: + '@tanstack/react-router': 1.170.46(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + '@tanstack/react-start-client': 1.168.44(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + '@tanstack/react-start-rsc': 0.1.65(esbuild@0.28.2)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(rolldown@1.2.11)(supports-color@5.5.0)(vite@8.3.1(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)) + '@tanstack/react-start-server': 1.167.52(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + '@tanstack/router-utils': 1.162.4(supports-color@5.5.0) + '@tanstack/start-client-core': 1.170.39 + '@tanstack/start-plugin-core': 1.171.55(@tanstack/react-router@1.170.46(react-dom@19.3.0(react@19.3.0))(react@19.3.0))(esbuild@0.28.2)(rolldown@1.2.11)(supports-color@5.5.0)(vite@8.3.1(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)) + '@tanstack/start-server-core': 1.169.45 + pathe: 2.0.3 + react: 19.3.0 + react-dom: 19.3.0(react@19.3.0) + optionalDependencies: + vite: 8.3.1(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0) + transitivePeerDependencies: + - '@farmfe/core' + - '@rspack/core' + - bun-types-no-globals + - esbuild + - react-server-dom-rspack + - rolldown + - rollup + - supports-color + - unloader + - vite-plugin-solid + - webpack + + '@tanstack/react-store@0.11.2(react-dom@19.3.0(react@19.3.0))(react@19.3.0)': + dependencies: + '@tanstack/store': 0.11.2 react: 19.3.0 react-dom: 19.3.0(react@19.3.0) use-sync-external-store: 1.7.0(react@19.3.0) - '@tanstack/router-core@1.171.32': + '@tanstack/router-core@1.171.39': dependencies: - '@tanstack/history': 1.162.4 + '@tanstack/history': 1.162.5 cookie-es: 3.1.1 seroval: 1.7.3 seroval-plugins: 1.7.3(seroval@1.7.3) - '@tanstack/router-devtools-core@1.168.2(@tanstack/router-core@1.171.32)(csstype@3.2.3)': + '@tanstack/router-devtools-core@1.168.2(@tanstack/router-core@1.171.39)(csstype@3.2.3)': dependencies: - '@tanstack/router-core': 1.171.32 + '@tanstack/router-core': 1.171.39 clsx: 2.1.1 goober: 2.1.19(csstype@3.2.3) optionalDependencies: csstype: 3.2.3 - '@tanstack/router-generator@1.167.38(supports-color@5.5.0)': + '@tanstack/router-generator@1.167.46(supports-color@5.5.0)': dependencies: '@babel/types': 7.29.8 - '@tanstack/router-core': 1.171.32 - '@tanstack/router-utils': 1.162.3(supports-color@5.5.0) + '@tanstack/router-core': 1.171.39 + '@tanstack/router-utils': 1.162.4(supports-color@5.5.0) '@tanstack/virtual-file-routes': 1.162.0 jiti: 2.7.0 magic-string: 0.30.21 prettier: 3.9.9 - zod: 4.6.5 + zod: 4.6.7 transitivePeerDependencies: - supports-color - '@tanstack/router-plugin@1.168.40(@tanstack/react-router@1.170.39(react-dom@19.3.0(react@19.3.0))(react@19.3.0))(esbuild@0.28.2)(rolldown@1.2.11)(supports-color@5.5.0)(vite@8.3.1(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0))': + '@tanstack/router-plugin@1.168.48(@tanstack/react-router@1.170.46(react-dom@19.3.0(react@19.3.0))(react@19.3.0))(esbuild@0.28.2)(rolldown@1.2.11)(supports-color@5.5.0)(vite@8.3.1(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0))': dependencies: '@babel/core': 7.29.7(supports-color@5.5.0) '@babel/template': 7.29.7 '@babel/types': 7.29.8 - '@tanstack/router-core': 1.171.32 - '@tanstack/router-generator': 1.167.38(supports-color@5.5.0) - '@tanstack/router-utils': 1.162.3(supports-color@5.5.0) + '@tanstack/router-core': 1.171.39 + '@tanstack/router-generator': 1.167.46(supports-color@5.5.0) + '@tanstack/router-utils': 1.162.4(supports-color@5.5.0) chokidar: 5.0.0 unplugin: 3.4.0(esbuild@0.28.2)(rolldown@1.2.11)(vite@8.3.1(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)) - zod: 4.6.5 + zod: 4.6.7 optionalDependencies: - '@tanstack/react-router': 1.170.39(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + '@tanstack/react-router': 1.170.46(react-dom@19.3.0(react@19.3.0))(react@19.3.0) vite: 8.3.1(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0) transitivePeerDependencies: - '@farmfe/core' @@ -4941,20 +5158,81 @@ snapshots: - supports-color - unloader - '@tanstack/router-utils@1.162.3(supports-color@5.5.0)': + '@tanstack/router-utils@1.162.4(supports-color@5.5.0)': dependencies: '@babel/generator': 7.29.8 '@babel/parser': 7.29.9 '@babel/types': 7.29.8 ansis: 4.4.0 babel-dead-code-elimination: 1.0.12(supports-color@5.5.0) - diff: 8.0.4 + diff: 9.0.0 pathe: 2.0.3 tinyglobby: 0.2.17 transitivePeerDependencies: - supports-color - '@tanstack/store@0.11.1': {} + '@tanstack/start-client-core@1.170.39': + dependencies: + '@tanstack/router-core': 1.171.39 + '@tanstack/start-fn-stubs': 1.162.0 + '@tanstack/start-storage-context': 1.167.41 + seroval: 1.7.3 + + '@tanstack/start-fn-stubs@1.162.0': {} + + '@tanstack/start-plugin-core@1.171.55(@tanstack/react-router@1.170.46(react-dom@19.3.0(react@19.3.0))(react@19.3.0))(esbuild@0.28.2)(rolldown@1.2.11)(supports-color@5.5.0)(vite@8.3.1(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0))': + dependencies: + '@babel/code-frame': 7.29.7 + '@babel/core': 7.29.7(supports-color@5.5.0) + '@babel/types': 7.29.8 + '@jridgewell/remapping': 2.3.5 + '@tanstack/router-core': 1.171.39 + '@tanstack/router-generator': 1.167.46(supports-color@5.5.0) + '@tanstack/router-plugin': 1.168.48(@tanstack/react-router@1.170.46(react-dom@19.3.0(react@19.3.0))(react@19.3.0))(esbuild@0.28.2)(rolldown@1.2.11)(supports-color@5.5.0)(vite@8.3.1(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)) + '@tanstack/router-utils': 1.162.4(supports-color@5.5.0) + '@tanstack/start-server-core': 1.169.45 + exsolve: 1.2.0 + lightningcss: 1.33.0 + pathe: 2.0.3 + picomatch: 4.0.7 + seroval: 1.7.3 + source-map: 0.7.6 + srvx: 1.0.8 + tinyglobby: 0.2.17 + ufo: 1.6.4 + vitefu: 1.1.3(vite@8.3.1(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)) + xmlbuilder2: 4.0.3 + zod: 4.6.7 + optionalDependencies: + vite: 8.3.1(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0) + transitivePeerDependencies: + - '@farmfe/core' + - '@rspack/core' + - '@tanstack/react-router' + - bun-types-no-globals + - esbuild + - rolldown + - rollup + - supports-color + - unloader + - vite-plugin-solid + - webpack + + '@tanstack/start-server-core@1.169.45': + dependencies: + '@tanstack/history': 1.162.5 + '@tanstack/router-core': 1.171.39 + '@tanstack/start-client-core': 1.170.39 + '@tanstack/start-storage-context': 1.167.41 + cookie-es: 3.1.1 + fetchdts: 0.2.0 + seroval: 1.7.3 + + '@tanstack/start-storage-context@1.167.41': + dependencies: + '@tanstack/router-core': 1.171.39 + + '@tanstack/store@0.11.2': {} '@tanstack/virtual-file-routes@1.162.0': {} @@ -6244,7 +6522,7 @@ snapshots: devtools-protocol@0.0.1608973: {} - diff@8.0.4: {} + diff@9.0.0: {} dom-accessibility-api@0.5.16: {} @@ -6451,8 +6729,8 @@ snapshots: '@babel/parser': 7.29.9 eslint: 9.39.5(jiti@2.7.0)(supports-color@5.5.0) hermes-parser: 0.25.1 - zod: 4.6.5 - zod-validation-error: 4.0.2(zod@4.6.5) + zod: 4.6.7 + zod-validation-error: 4.0.2(zod@4.6.7) transitivePeerDependencies: - supports-color @@ -6578,6 +6856,8 @@ snapshots: transitivePeerDependencies: - supports-color + exsolve@1.2.0: {} + external-editor@3.1.0: dependencies: chardet: 0.7.0 @@ -6636,6 +6916,8 @@ snapshots: optionalDependencies: picomatch: 4.0.7 + fetchdts@0.2.0: {} + figures@2.0.0: dependencies: escape-string-regexp: 1.0.5 @@ -7532,6 +7814,8 @@ snapshots: picomatch@4.0.7: {} + playwright-core@1.55.0: {} + possible-typed-array-names@1.1.0: {} postcss@8.5.28: @@ -7890,6 +8174,8 @@ snapshots: source-map@0.6.1: {} + source-map@0.7.6: {} + speedline-core@1.4.3: dependencies: '@types/node': 26.6.5 @@ -7898,6 +8184,8 @@ snapshots: sprintf-js@1.0.3: {} + srvx@1.0.8: {} + statuses@2.0.2: {} std-env@4.3.0: {} @@ -8148,6 +8436,8 @@ snapshots: typescript@6.0.3: {} + ufo@1.6.4: {} + unbox-primitive@1.1.0: dependencies: call-bound: 1.0.4 @@ -8214,6 +8504,10 @@ snapshots: fsevents: 2.3.3 jiti: 2.7.0 + vitefu@1.1.3(vite@8.3.1(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)): + optionalDependencies: + vite: 8.3.1(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0) + vitest@5.0.5(@types/node@26.6.5)(@vitest/coverage-v8@5.0.5)(jsdom@30.1.3)(vite@8.3.1(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)): dependencies: '@types/chai': 5.2.3 @@ -8348,6 +8642,13 @@ snapshots: xml-name-validator@5.0.0: {} + xmlbuilder2@4.0.3: + dependencies: + '@oozcitak/dom': 2.0.2 + '@oozcitak/infra': 2.0.2 + '@oozcitak/util': 10.0.0 + js-yaml: 4.3.2 + xmlchars@2.2.0: {} y18n@4.0.3: {} @@ -8401,10 +8702,10 @@ snapshots: yocto-queue@0.1.0: {} - zod-validation-error@4.0.2(zod@4.6.5): + zod-validation-error@4.0.2(zod@4.6.7): dependencies: - zod: 4.6.5 + zod: 4.6.7 zod@3.25.76: {} - zod@4.6.5: {} + zod@4.6.7: {} diff --git a/web/pnpm-workspace.yaml b/web/pnpm-workspace.yaml index c186f53..9ba0895 100644 --- a/web/pnpm-workspace.yaml +++ b/web/pnpm-workspace.yaml @@ -7,3 +7,5 @@ overrides: # Veiligheidspatch (GHSA-97r2-qh9m-474h, GHSA-wp97-x4hv-qvhp, GHSA-7rv5-mrxv-xcr9) voor seroval, via @tanstack/router-core seroval: ^1.6.8 seroval-plugins: ^1.6.8 + # Veiligheidspatch (GHSA-mrhx-c7xc-m3w5) voor zod 4, via @tanstack/start-plugin-core en router-generator + zod@4: ^4.6.6 diff --git a/web/src/app.test.tsx b/web/src/app.test.tsx index b2d5f7a..716dd9e 100644 --- a/web/src/app.test.tsx +++ b/web/src/app.test.tsx @@ -626,7 +626,10 @@ describe('pagina-register', () => { it('bevat precies de routes van de route tree', async () => { const { router } = await renderApp('/'); - const routePaths = Object.keys(router.routesByPath).sort(); + // De vangroute (404) is geen pagina en staat niet in het register + const routePaths = Object.keys(router.routesByPath) + .filter((path) => path !== '/$') + .sort(); expect(Object.keys(sitePages).sort()).toEqual(routePaths); }); diff --git a/web/src/client.tsx b/web/src/client.tsx new file mode 100644 index 0000000..20dc0d3 --- /dev/null +++ b/web/src/client.tsx @@ -0,0 +1,18 @@ +import { StrictMode, startTransition } from 'react'; +import { hydrateRoot } from 'react-dom/client'; +import { StartClient } from '@tanstack/react-start/client'; +import { startSentry } from './monitoring/sentry'; + +// Foutmeldingen naar Sentry, alleen op test en productie (M1). Dit bestand +// draait alleen in de browser, dus niet tijdens het prerenderen, en loopt voor +// op het hydrateren zodat ook vroege fouten gemeld worden. +startSentry(); + +startTransition(() => { + hydrateRoot( + document, + + + , + ); +}); diff --git a/web/src/components/Analytics/UmamiAnalytics.tsx b/web/src/components/Analytics/UmamiAnalytics.tsx index f132ac0..89ab144 100644 --- a/web/src/components/Analytics/UmamiAnalytics.tsx +++ b/web/src/components/Analytics/UmamiAnalytics.tsx @@ -6,13 +6,12 @@ const SCRIPT_ELEMENT_ID = 'umami-analytics-script'; // Bezoekersstatistieken zonder cookies (M6). Alleen op een bekende host, met // de website van die omgeving; data-domains telt nergens anders mee en // data-do-not-track respecteert de Do Not Track-instelling van de browser. -export default function UmamiAnalytics({ - hostname = window.location.hostname, -}: { - hostname?: string; -}) { +export default function UmamiAnalytics({ hostname }: { hostname?: string }) { useEffect(() => { - const monitoring = monitoringFor(hostname); + // Read here, not as a default parameter: there is no window while + // prerendering + const host = hostname ?? window.location.hostname; + const monitoring = monitoringFor(host); if (!monitoring || document.getElementById(SCRIPT_ELEMENT_ID)) return; const script = document.createElement('script'); @@ -20,7 +19,7 @@ export default function UmamiAnalytics({ script.src = `${umamiOrigin}/script.js`; script.defer = true; script.dataset.websiteId = monitoring.umamiWebsiteId; - script.dataset.domains = hostname; + script.dataset.domains = host; script.dataset.doNotTrack = 'true'; document.head.appendChild(script); diff --git a/web/src/components/DeferredImage/DeferredImage.test.tsx b/web/src/components/DeferredImage/DeferredImage.test.tsx index b99ba09..175146d 100644 --- a/web/src/components/DeferredImage/DeferredImage.test.tsx +++ b/web/src/components/DeferredImage/DeferredImage.test.tsx @@ -40,12 +40,16 @@ describe('DeferredImage', () => { }); it('waits for the page load event, even when already in view', async () => { - vi.spyOn(document, 'readyState', 'get').mockReturnValue('interactive'); + const readyState = vi + .spyOn(document, 'readyState', 'get') + .mockReturnValue('interactive'); await renderWithProviders(); const img = screen.getByRole('img', { name: 'Een foto' }); expect(img).not.toHaveAttribute('src'); act(() => { + // The browser is 'complete' by the time the load event fires + readyState.mockReturnValue('complete'); window.dispatchEvent(new Event('load')); }); expect(img).toHaveAttribute('src', '/foto.jpg'); diff --git a/web/src/components/Hero/useHeroSlider.ts b/web/src/components/Hero/useHeroSlider.ts index f3e3941..008d6d8 100644 --- a/web/src/components/Hero/useHeroSlider.ts +++ b/web/src/components/Hero/useHeroSlider.ts @@ -1,4 +1,4 @@ -import { useEffect, useState } from 'react'; +import { useState, useSyncExternalStore } from 'react'; import { useMediaQuery } from '@chakra-ui/react'; import useSwipe from '@/hooks/useSwipe'; import { wrapIndex } from '@/lib/wrapIndex'; @@ -12,6 +12,11 @@ import { wrapIndex } from '@/lib/wrapIndex'; // leest een nieuwe naam van de knop met focus niet altijd voor. export type HeroAnnouncement = 'slide' | 'paused' | 'playing' | null; +const subscribeVisibility = (onChange: () => void) => { + document.addEventListener('visibilitychange', onChange); + return () => document.removeEventListener('visibilitychange', onChange); +}; + export default function useHeroSlider(count: number) { const [index, setIndex] = useState(0); const [announcement, setAnnouncement] = useState(null); @@ -19,23 +24,13 @@ export default function useHeroSlider(count: number) { const [stopped, setStopped] = useState(false); const [hovered, setHovered] = useState(false); const [focused, setFocused] = useState(false); - const [hidden, setHidden] = useState(() => document.hidden); - const [reducedMotion] = useMediaQuery( - ['(prefers-reduced-motion: reduce)'], - { - ssr: false, - }, + // Server and hydrating render say "visible", like the HTML + const hidden = useSyncExternalStore( + subscribeVisibility, + () => document.hidden, + () => false, ); - - useEffect(() => { - const onVisibilityChange = () => setHidden(document.hidden); - document.addEventListener('visibilitychange', onVisibilityChange); - return () => - document.removeEventListener( - 'visibilitychange', - onVisibilityChange, - ); - }, []); + const [reducedMotion] = useMediaQuery(['(prefers-reduced-motion: reduce)']); // Als de API minder slides teruggeeft dan de huidige index, begin vooraan. const active = index < count ? index : 0; diff --git a/web/src/components/NavigationBar/NavigationBar.tsx b/web/src/components/NavigationBar/NavigationBar.tsx index b66778c..19a9e2a 100644 --- a/web/src/components/NavigationBar/NavigationBar.tsx +++ b/web/src/components/NavigationBar/NavigationBar.tsx @@ -32,11 +32,9 @@ export default function NavigationBar() { const submenuToggleRef = useRef(null); // Het mobiele menu bestaat alleen onder lg; wordt het scherm breder, dan - // sluit de reducer het. Eerste render kan undefined geven: telt als mobiel. - const isDesktop = useBreakpointValue( - { base: false, lg: true }, - { ssr: false }, - ); + // sluit de reducer het. De eerste render geeft de waarde van `base` (zo ook + // in de voorgerenderde HTML): telt als mobiel. + const isDesktop = useBreakpointValue({ base: false, lg: true }); useEffect(() => { dispatch({ type: 'viewport', isDesktop: !!isDesktop }); }, [isDesktop]); diff --git a/web/src/components/home/ContactSection/ContactSection.tsx b/web/src/components/home/ContactSection/ContactSection.tsx index aaae4c7..31662f9 100644 --- a/web/src/components/home/ContactSection/ContactSection.tsx +++ b/web/src/components/home/ContactSection/ContactSection.tsx @@ -41,10 +41,7 @@ export default function ContactSection({ // continue keyboard and screen reader users here. This navigation // replaces the "Boek" click's before the router has scrolled for it, so // it must ask the router to scroll to #contact itself. - const [reducedMotion] = useMediaQuery( - ['(prefers-reduced-motion: reduce)'], - { ssr: false }, - ); + const [reducedMotion] = useMediaQuery(['(prefers-reduced-motion: reduce)']); useEffect(() => { if (pakket === undefined) return; void navigate({ diff --git a/web/src/components/home/Testimonials/TestimonialCarousel.tsx b/web/src/components/home/Testimonials/TestimonialCarousel.tsx index a1af221..b145499 100644 --- a/web/src/components/home/Testimonials/TestimonialCarousel.tsx +++ b/web/src/components/home/Testimonials/TestimonialCarousel.tsx @@ -27,10 +27,7 @@ export default function TestimonialCarousel({ testimonials: Testimonial[]; }) { const count = testimonials.length; - const [reducedMotion] = useMediaQuery( - ['(prefers-reduced-motion: reduce)'], - { ssr: false }, - ); + const [reducedMotion] = useMediaQuery(['(prefers-reduced-motion: reduce)']); // Empty on load; filled only by a change, so nothing is read out then const [announcement, setAnnouncement] = useState(''); const carousel = useCarousel({ diff --git a/web/src/hooks/useHydrated.ts b/web/src/hooks/useHydrated.ts new file mode 100644 index 0000000..0e08ae8 --- /dev/null +++ b/web/src/hooks/useHydrated.ts @@ -0,0 +1,14 @@ +import { useSyncExternalStore } from 'react'; + +const subscribeNoop = () => () => {}; + +// False while prerendering and during the hydrating render, true afterwards +// (and at once for components that mount later). Same behaviour as the +// useHydrated that the router keeps internally. +export default function useHydrated() { + return useSyncExternalStore( + subscribeNoop, + () => true, + () => false, + ); +} diff --git a/web/src/hooks/useInView.ts b/web/src/hooks/useInView.ts index 3cec008..320a814 100644 --- a/web/src/hooks/useInView.ts +++ b/web/src/hooks/useInView.ts @@ -1,4 +1,6 @@ -import { useEffect, useRef, useState } from 'react'; +import { useEffect, useRef, useState, useSyncExternalStore } from 'react'; + +const noopSubscribe = () => () => {}; type UseInViewOptions = { threshold?: number; @@ -8,21 +10,25 @@ type UseInViewOptions = { }; // Tells whether an element has come into (or near) the viewport, once. -// Without IntersectionObserver the element counts as in view right away, so -// content is never left hidden or unloaded. +// Without IntersectionObserver the element counts as in view (from the first +// render after hydration), so content is never left hidden or unloaded. export default function useInView({ threshold = 0, rootMargin = '0px', skip = false, }: UseInViewOptions = {}) { const ref = useRef(null); - const supported = typeof IntersectionObserver !== 'undefined'; + // The server cannot know, so prerender and hydration both assume support + const unsupported = useSyncExternalStore( + noopSubscribe, + () => typeof IntersectionObserver === 'undefined', + () => false, + ); const [intersected, setIntersected] = useState(false); - const immediate = skip || !supported; useEffect(() => { const element = ref.current; - if (!element || immediate || intersected) return; + if (!element || skip || unsupported || intersected) return; const observer = new IntersectionObserver( (entries) => { @@ -36,7 +42,7 @@ export default function useInView({ observer.observe(element); return () => observer.disconnect(); - }, [immediate, intersected, threshold, rootMargin]); + }, [skip, unsupported, intersected, threshold, rootMargin]); - return { ref, inView: immediate || intersected }; + return { ref, inView: skip || intersected || unsupported }; } diff --git a/web/src/hooks/usePageLoaded.test.tsx b/web/src/hooks/usePageLoaded.test.tsx index 1a060ed..8c3d655 100644 --- a/web/src/hooks/usePageLoaded.test.tsx +++ b/web/src/hooks/usePageLoaded.test.tsx @@ -9,11 +9,15 @@ describe('usePageLoaded', () => { }); it('turns true on the load event', () => { - vi.spyOn(document, 'readyState', 'get').mockReturnValue('interactive'); + const readyState = vi + .spyOn(document, 'readyState', 'get') + .mockReturnValue('interactive'); const { result } = renderHook(() => usePageLoaded()); expect(result.current).toBe(false); act(() => { + // The browser is 'complete' by the time the load event fires + readyState.mockReturnValue('complete'); window.dispatchEvent(new Event('load')); }); expect(result.current).toBe(true); diff --git a/web/src/hooks/usePageLoaded.ts b/web/src/hooks/usePageLoaded.ts index ac88811..e994fb9 100644 --- a/web/src/hooks/usePageLoaded.ts +++ b/web/src/hooks/usePageLoaded.ts @@ -1,17 +1,16 @@ -import { useEffect, useState } from 'react'; +import { useSyncExternalStore } from 'react'; -// True once the window's load event has fired (or had already fired). +const subscribe = (onChange: () => void) => { + window.addEventListener('load', onChange, { once: true }); + return () => window.removeEventListener('load', onChange); +}; + +// True once the window's load event has fired (or had already fired). While +// prerendering and hydrating it is false, like the HTML. export default function usePageLoaded() { - const [loaded, setLoaded] = useState( + return useSyncExternalStore( + subscribe, () => document.readyState === 'complete', + () => false, ); - - useEffect(() => { - if (loaded) return; - const onLoad = () => setLoaded(true); - window.addEventListener('load', onLoad, { once: true }); - return () => window.removeEventListener('load', onLoad); - }, [loaded]); - - return loaded; } diff --git a/web/src/hooks/useReveal.test.tsx b/web/src/hooks/useReveal.test.tsx index 70631c7..1d1ccd7 100644 --- a/web/src/hooks/useReveal.test.tsx +++ b/web/src/hooks/useReveal.test.tsx @@ -52,7 +52,11 @@ describe('useReveal', () => { mockReducedMotion(); renderProbe(); expect(screen.getByTestId('probe')).toHaveTextContent('visible'); - expect(FakeObserver.instances).toHaveLength(0); + // The first render still assumes motion is fine (as the prerendered + // HTML does), so an observer may start; it is stopped again at once + expect( + FakeObserver.instances.every((observer) => observer.disconnected), + ).toBe(true); }); it('stays hidden until the element scrolls into view, then stops observing', () => { diff --git a/web/src/hooks/useReveal.ts b/web/src/hooks/useReveal.ts index d230463..4081110 100644 --- a/web/src/hooks/useReveal.ts +++ b/web/src/hooks/useReveal.ts @@ -6,10 +6,7 @@ import useInView from './useInView'; // right at the bottom edge. When the visitor prefers reduced motion the // element counts as visible right away. export default function useReveal() { - const [reducedMotion] = useMediaQuery( - ['(prefers-reduced-motion: reduce)'], - { ssr: false }, - ); + const [reducedMotion] = useMediaQuery(['(prefers-reduced-motion: reduce)']); const { ref, inView } = useInView({ threshold: 0.12, rootMargin: '0px 0px -60px 0px', diff --git a/web/src/main.tsx b/web/src/main.tsx deleted file mode 100644 index 9b53ab9..0000000 --- a/web/src/main.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import { StrictMode } from 'react'; -import ReactDOM from 'react-dom/client'; -import { RouterProvider, createRouter } from '@tanstack/react-router'; -import { routeTree } from './routeTree.gen'; -import { ChakraProvider } from '@chakra-ui/react'; -import system from './theme.ts'; -import ErrorPage from './components/StatusPage/ErrorPage'; -import { startSentry } from './monitoring/sentry'; - -import '@fontsource/jost/300.css'; -import '@fontsource/jost/400.css'; -import '@fontsource/jost/500.css'; -import '@fontsource/marcellus/400.css'; - -// Foutmeldingen naar Sentry, alleen op test en productie (M1) -startSentry(); - -// Create a new router instance -const router = createRouter({ - routeTree, - // Nieuwe pagina begint bovenaan; terug/vooruit herstelt de positie (FR-08) - scrollRestoration: true, - // Fout in een pagina: foutpagina binnen de shell (FR-10) - defaultErrorComponent: ErrorPage, -}); - -// Register the router instance for type safety -declare module '@tanstack/react-router' { - interface Register { - router: typeof router; - } -} - -// De statische head-tags uit index.html zijn alleen voor crawlers zonder -// JavaScript. Vanaf hier beheren de routes ze, dus voorkom dubbele tags. -document.querySelectorAll('head [data-fallback]').forEach((el) => el.remove()); - -// Render the app -const rootElement = document.getElementById('root')!; -if (!rootElement.innerHTML) { - const root = ReactDOM.createRoot(rootElement); - root.render( - - {/* De site is alleen licht; de _dark-waarden in het thema blijven - staan voor een eventuele donkere modus later */} - - - - , - ); -} diff --git a/web/src/navigation.ts b/web/src/navigation.ts index e019ba0..205e35f 100644 --- a/web/src/navigation.ts +++ b/web/src/navigation.ts @@ -3,8 +3,9 @@ import { shootNavItems } from './lib/shootNavItems.ts'; import type { FileRoutesByTo } from './routeTree.gen.ts'; // Menu's verwijzen naar routes, en routes zijn code: het CMS kan geen -// pagina's toevoegen. Een tikfout in `to` is daardoor een typefout. -export type RoutePath = keyof FileRoutesByTo; +// pagina's toevoegen. Een tikfout in `to` is daardoor een typefout. De +// vangroute voor onbekende URL's is geen pagina: niet in menu's en register. +export type RoutePath = Exclude; export interface NavItem { to: RoutePath; diff --git a/web/src/routeTree.gen.ts b/web/src/routeTree.gen.ts index 55c6803..633c683 100644 --- a/web/src/routeTree.gen.ts +++ b/web/src/routeTree.gen.ts @@ -10,6 +10,7 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' +import { Route as SplatRouteImport } from './routes/$' import { Route as ContactRouteImport } from './routes/contact' import { Route as OverMijRouteImport } from './routes/over-mij' import { Route as PortfolioRouteImport } from './routes/portfolio' @@ -26,6 +27,11 @@ const IndexRoute = IndexRouteImport.update({ path: '/', getParentRoute: () => rootRouteImport, } as any) +const SplatRoute = SplatRouteImport.update({ + id: '/$', + path: '/$', + getParentRoute: () => rootRouteImport, +} as any) const ContactRoute = ContactRouteImport.update({ id: '/contact', path: '/contact', @@ -83,6 +89,7 @@ const SoortenFotoshootsZwangerschapRoute = export interface FileRoutesByFullPath { '/': typeof IndexRoute + '/$': typeof SplatRoute '/contact': typeof ContactRoute '/over-mij': typeof OverMijRoute '/portfolio': typeof PortfolioRoute @@ -96,6 +103,7 @@ export interface FileRoutesByFullPath { } export interface FileRoutesByTo { '/': typeof IndexRoute + '/$': typeof SplatRoute '/contact': typeof ContactRoute '/over-mij': typeof OverMijRoute '/portfolio': typeof PortfolioRoute @@ -110,6 +118,7 @@ export interface FileRoutesByTo { export interface FileRoutesById { __root__: typeof rootRouteImport '/': typeof IndexRoute + '/$': typeof SplatRoute '/contact': typeof ContactRoute '/over-mij': typeof OverMijRoute '/portfolio': typeof PortfolioRoute @@ -125,6 +134,7 @@ export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath fullPaths: | '/' + | '/$' | '/contact' | '/over-mij' | '/portfolio' @@ -138,6 +148,7 @@ export interface FileRouteTypes { fileRoutesByTo: FileRoutesByTo to: | '/' + | '/$' | '/contact' | '/over-mij' | '/portfolio' @@ -151,6 +162,7 @@ export interface FileRouteTypes { id: | '__root__' | '/' + | '/$' | '/contact' | '/over-mij' | '/portfolio' @@ -165,6 +177,7 @@ export interface FileRouteTypes { } export interface RootRouteChildren { IndexRoute: typeof IndexRoute + SplatRoute: typeof SplatRoute ContactRoute: typeof ContactRoute OverMijRoute: typeof OverMijRoute PortfolioRoute: typeof PortfolioRoute @@ -186,6 +199,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/$': { + id: '/$' + path: '/$' + fullPath: '/$' + preLoaderRoute: typeof SplatRouteImport + parentRoute: typeof rootRouteImport + } '/contact': { id: '/contact' path: '/contact' @@ -261,6 +281,7 @@ declare module '@tanstack/react-router' { const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, + SplatRoute: SplatRoute, ContactRoute: ContactRoute, OverMijRoute: OverMijRoute, PortfolioRoute: PortfolioRoute, @@ -275,3 +296,12 @@ const rootRouteChildren: RootRouteChildren = { export const routeTree = rootRouteImport ._addFileChildren(rootRouteChildren) ._addFileTypes() + +import type { getRouter } from './router.tsx' +import type { createStart } from '@tanstack/react-start' +declare module '@tanstack/react-start' { + interface Register { + ssr: true + router: Awaited> + } +} diff --git a/web/src/router.tsx b/web/src/router.tsx new file mode 100644 index 0000000..7ae502e --- /dev/null +++ b/web/src/router.tsx @@ -0,0 +1,27 @@ +import { createRouter } from '@tanstack/react-router'; +import { routeTree } from './routeTree.gen'; +import ErrorPage from './components/StatusPage/ErrorPage'; + +// Eรฉn set opties voor de app en voor de tests (renderApp) +export function routerOptions() { + return { + routeTree, + // Nieuwe pagina begint bovenaan; terug/vooruit herstelt de positie (FR-08) + scrollRestoration: true, + // Fout in een pagina: foutpagina binnen de shell (FR-10) + defaultErrorComponent: ErrorPage, + }; +} + +// Start roept dit aan voor elke render: op de server per prerender-verzoek, +// in de browser รฉรฉn keer +export function getRouter() { + return createRouter(routerOptions()); +} + +// Register the router instance for type safety +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType; + } +} diff --git a/web/src/routes/$.tsx b/web/src/routes/$.tsx new file mode 100644 index 0000000..078e385 --- /dev/null +++ b/web/src/routes/$.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router'; +import NotFound from '../components/StatusPage/NotFound'; + +// Vangt elke onbekende URL op en wordt als 404.html voorgerenderd (BR-404-01). +// Geen head() en geen notFound(): Start laat de build falen bij een niet-OK +// antwoord, en NotFound zet zelf titel en noindex. +export const Route = createFileRoute('/$')({ + component: NotFound, +}); diff --git a/web/src/routes/__root.tsx b/web/src/routes/__root.tsx index d882348..7389a2e 100644 --- a/web/src/routes/__root.tsx +++ b/web/src/routes/__root.tsx @@ -1,10 +1,18 @@ import { lazy, Suspense } from 'react'; -import { createRootRoute, HeadContent } from '@tanstack/react-router'; +import type { ReactNode } from 'react'; +import { createRootRoute, HeadContent, Scripts } from '@tanstack/react-router'; +import { ChakraProvider } from '@chakra-ui/react'; import AppShell from '../components/AppShell'; import ErrorPage from '../components/StatusPage/ErrorPage'; import NotFound from '../components/StatusPage/NotFound'; import siteContent from '../content/siteContent'; import { siteHead } from '../seo'; +import system from '../theme'; + +import '@fontsource/jost/300.css'; +import '@fontsource/jost/400.css'; +import '@fontsource/jost/500.css'; +import '@fontsource/marcellus/400.css'; // Devtools alleen tijdens het ontwikkelen; ze komen niet in de productiebuild const RouterDevtools = import.meta.env.DEV @@ -15,10 +23,24 @@ const RouterDevtools = import.meta.env.DEV ) : () => null; +// Het hele document: Start rendert dit op de server en hydrateert het in de +// browser. Titel en meta-tags van de actieve route komen via HeadContent. +const RootDocument = ({ children }: { children: ReactNode }) => ( + + + + + + {/* De site is alleen licht; de _dark-waarden in het thema blijven + staan voor een eventuele donkere modus later */} + {children} + + + +); + const RootLayout = () => ( <> - {/* Titel en meta-tags van de actieve route; React zet ze in */} - @@ -27,7 +49,25 @@ const RootLayout = () => ( ); export const Route = createRootRoute({ - head: () => siteHead(siteContent), + head: () => { + const { meta, scripts } = siteHead(siteContent); + return { + meta: [ + { charSet: 'utf-8' }, + { + name: 'viewport', + content: 'width=device-width, initial-scale=1.0', + }, + ...meta, + ], + links: [ + { rel: 'icon', type: 'image/png', href: '/favicon.png' }, + { rel: 'apple-touch-icon', href: '/favicon.png' }, + ], + scripts, + }; + }, + shellComponent: RootDocument, component: RootLayout, // Onbekende URL: 404 binnen de shell (FR-09) notFoundComponent: NotFound, diff --git a/web/src/test/renderApp.tsx b/web/src/test/renderApp.tsx index 63eaef7..4942b39 100644 --- a/web/src/test/renderApp.tsx +++ b/web/src/test/renderApp.tsx @@ -2,22 +2,38 @@ import { ChakraProvider } from '@chakra-ui/react'; import { createMemoryHistory, createRouter, + HeadContent, RouterProvider, + rootRouteId, } from '@tanstack/react-router'; import { render, screen } from '@testing-library/react'; +import type { ReactNode } from 'react'; import { expect } from 'vitest'; -import ErrorPage from '../components/StatusPage/ErrorPage'; -import { routeTree } from '../routeTree.gen'; +import { routerOptions } from '../router'; import system from '../theme'; -// De echte app: route tree, router-opties en thema zoals in main.tsx +// De root route rendert in de browser het hele document (, ). Dat +// past niet in de testcontainer: React zou op het testdocument +// zetten en het thema twee keer wikkelen. Tests krijgen daarom een shell met +// alleen de head-tags; verder is het dezelfde route tree (V2, D12). +const TestShell = ({ children }: { children: ReactNode }) => ( + <> + + {children} + +); + +// De echte app: route tree en router-opties uit router.tsx, thema zoals in de +// shell van __root.tsx export async function renderApp(path: string) { const router = createRouter({ - routeTree, + ...routerOptions(), history: createMemoryHistory({ initialEntries: [path] }), - scrollRestoration: true, - defaultErrorComponent: ErrorPage, }); + const rootOptions = router.routesById[rootRouteId].options as { + shellComponent?: typeof TestShell; + }; + rootOptions.shellComponent = TestShell; await router.load(); const result = render( diff --git a/web/vite.config.ts b/web/vite.config.ts index fe7cca5..8237b61 100644 --- a/web/vite.config.ts +++ b/web/vite.config.ts @@ -1,9 +1,14 @@ /// import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; -import { tanstackRouter } from '@tanstack/router-plugin/vite'; +import { tanstackStart } from '@tanstack/react-start/plugin/vite'; 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 = { @@ -14,16 +19,46 @@ const fullCoverage = { }; // https://vitejs.dev/config/ -export default defineConfig({ +export default defineConfig(({ mode }) => ({ plugins: [ - // Please make sure that '@tanstack/router-plugin' is passed before '@vitejs/plugin-react' - tanstackRouter({ - target: 'react', - autoCodeSplitting: true, - }), + // De Start-plugin hoort niet in Vitest (D12): de tests renderen + // componenten zonder document-shell. Hij brengt zijn eigen + // routegenerator en code splitting mee, vervangt dus de router-plugin. + ...(mode === 'test' + ? [] + : [ + tanstackStart({ + // Elke pagina uit het register wordt een eigen + // HTML-bestand; de lijst wordt nooit twee keer getypt. + pages: [ + ...Object.keys(sitePages).map((path) => ({ path })), + // De catch-all route als 404.html (BR-404-02) + { + path: NOT_FOUND_PATH, + prerender: { outputPath: `/${NOT_FOUND_FILE}` }, + }, + ], + prerender: { + enabled: true, + // /over-mij wordt over-mij.html, zonder map en + // zonder redirect naar een slash (BR-BLD-03) + autoSubfolderIndex: false, + // Alleen de pagina's hierboven (BR-BLD-04) + crawlLinks: false, + autoStaticPathsDiscovery: false, + }, + }), + ]), react(), sitemapPlugin(), ], + // Eรฉn keer per build vastgelegd, zodat server- en clientbundel hetzelfde + // jaar tonen in de eerste render van de footer (BR-HYD-14) + define: { + 'import.meta.env.VITE_BUILD_YEAR': JSON.stringify( + String(new Date().getFullYear()), + ), + }, resolve: { tsconfigPaths: true, }, @@ -50,4 +85,4 @@ export default defineConfig({ }, }, }, -}); +})); -- 2.39.5 From 1574726c1dd40875a296a7abfebc2d7eff1c864a Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Sat, 31 Oct 2026 18:12:42 +0100 Subject: [PATCH 03/49] Adds the step that moves inline scripts to files TanStack Start writes inline scripts into each page, which the strict CSP blocks. This step moves them to hashed files and checks the output: every page is present, no executable inline script remains and the e-mail address appears nowhere. It is not part of the build yet. Co-Authored-By: Claude Opus 5.5 --- .../start-migration/code/verification-log.md | 22 +- web/config/externalizeInlineScripts.test.ts | 729 ++++++++++++++++++ web/config/externalizeInlineScripts.ts | 363 +++++++++ web/config/inlineScripts.test.ts | 507 ++++++++++++ web/config/inlineScripts.ts | 370 +++++++++ web/config/pageFiles.test.ts | 84 ++ web/config/pageFiles.ts | 26 + web/src/test/htmlArbitraries.ts | 312 ++++++++ 8 files changed, 2409 insertions(+), 4 deletions(-) create mode 100644 web/config/externalizeInlineScripts.test.ts create mode 100644 web/config/externalizeInlineScripts.ts create mode 100644 web/config/inlineScripts.test.ts create mode 100644 web/config/inlineScripts.ts create mode 100644 web/config/pageFiles.test.ts create mode 100644 web/config/pageFiles.ts create mode 100644 web/src/test/htmlArbitraries.ts 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 061eaf6..31019c9 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 @@ -27,8 +27,8 @@ Notes: |---|---|---|---|---|---| | V1 | Custom `src/client.tsx` hydrates with Start; `startSentry()` before hydration | 4 | Start picks `src/client.tsx` by name (default entry `client` in `srcDirectory`); it replaces the default entry, whose body is `startTransition(() => hydrateRoot(document, ))`. `startSentry()` runs at module level before that call. | Build output `dist/client/assets/index-*.js` contains `hydrateRoot` and the Sentry loader (`sentryClient-*.js` dynamic import). Chrome (playwright-core, system Chrome, static server, no CSP yet): `/`, `/over-mij`, `/contact`, `/contact?pakket=gezin` hydrate with no console error or warning. Not proven here: that Sentry initialises (only on the test and production hostnames, so a no-op on 127.0.0.1); unit tests of `monitoring/` cover that. | OK | | V2 | `RouterProvider` in jsdom renders `shellComponent` | 5 | Yes, Router calls the root `shellComponent` (`Match.js`: `ShellComponent = route.isRoot && route.options.shellComponent`). React 19 treats `html`/`head`/`body` as singletons, so no `` lands in the RTL container (container has 0 html/head/body), but it sets `lang="nl"` on `document.documentElement` and wraps `ChakraProvider` a second time. Variant used: `renderApp` replaces the root route's `shellComponent` by a test shell (`HeadContent` + children) on its router instance; production code untouched. | Probe test (removed) printed `shellComponent: function`, `html=0 head=0 body=0`, `document.documentElement lang=nl`. All 888 tests pass with the test shell (with the real shell, 45 of 46 in `app.test.tsx` passed; the one failure was the `/$` register test). | OK | -| V3 | Inline scripts per real page | 4 (first look), 13 (final) | Per page (12 files) the inline executable scripts are: (a) router scroll restoration, 613 chars, no attributes, same body everywhere; (b) Start bootstrap `data-tsr-stream-part=""`, 916 to 1349 chars, differs per page; (c) boundary `document.currentScript.remove();/*$tsr-stream-boundary*/`, 56 chars, same everywhere. `/contact` has two more (lazy form Suspense): `` (57 chars) and the React completion runtime `$RB=[];$RV=function(a){...` (845 chars). No `$RC` seen on other pages. External: ``; + +const validFiles = (): Map => + new Map([ + ['index.html', page('boot("index")')], + ['over-mij.html', page('boot("over-mij")')], + ['soorten-fotoshoots/newborn.html', page('boot("newborn")')], + ['404.html', page('boot("404")')], + ['sitemap.xml', SITEMAP], + ['assets/index-abc.js', 'console.log(1);'], + ['assets/index-abc.css', 'a{color:red}'], + ]); + +const found = (plan: { violations: { file: string; code: string }[] }) => + plan.violations.map((v) => `${v.file}: ${v.code}`).sort(); + +describe('planExternalization: pad zonder overtredingen', () => { + it('verplaatst de scripts van elke pagina, ook van 404.html', () => { + const plan = planExternalization(validFiles(), context()); + expect(plan.violations).toEqual([]); + const scripts = [...plan.writes.keys()].filter((f) => + f.startsWith('assets/inline-'), + ); + expect(scripts).toHaveLength(4); + for (const file of [ + 'index.html', + 'over-mij.html', + 'soorten-fotoshoots/newborn.html', + '404.html', + ]) { + expect(plan.writes.get(file)).toMatch( + /src="\/assets\/inline-[0-9a-f]{12}\.js"/, + ); + } + }); + + it('is een no-op bij een tweede keer (al verwerkte pagina telt mee)', () => { + const files = validFiles(); + const first = planExternalization(files, context()); + for (const [file, content] of first.writes) files.set(file, content); + const second = planExternalization(files, context()); + expect(second.writes.size).toBe(0); + expect(second.violations).toEqual([]); + }); + + it('schrijft een scriptbestand dat al met dezelfde inhoud bestaat niet opnieuw', () => { + const files = validFiles(); + const first = planExternalization(files, context()); + const name = [...first.writes.keys()].find((f) => + f.startsWith('assets/inline-'), + )!; + files.set(name, first.writes.get(name)!); + const plan = planExternalization(files, context()); + expect(plan.writes.has(name)).toBe(false); + expect(plan.violations).toEqual([]); + }); + + it('schrijft een gedeeld script รฉรฉn keer', () => { + const files = validFiles(); + for (const file of ['index.html', 'over-mij.html']) { + files.set(file, page('gedeeld()')); + } + const plan = planExternalization(files, context()); + const shared = [...plan.writes.values()].filter( + (c) => c === 'gedeeld()', + ); + expect(shared).toHaveLength(1); + }); +}); + +describe('planExternalization: overtredingen', () => { + it('NO_HTML: geen enkel html-bestand, zonder de paginaโ€™s afzonderlijk te melden', () => { + const files = new Map([['sitemap.xml', SITEMAP]]); + expect(found(planExternalization(files, context()))).toEqual([ + '.: NO_HTML', + ]); + }); + + it('PAGE_MISSING: meldt alle ontbrekende paginaโ€™s', () => { + const files = validFiles(); + files.delete('over-mij.html'); + files.delete('soorten-fotoshoots/newborn.html'); + const plan = planExternalization(files, context()); + expect(found(plan)).toEqual([ + 'over-mij.html: PAGE_MISSING', + 'soorten-fotoshoots/newborn.html: PAGE_MISSING', + ]); + expect(plan.violations[0].detail).toContain('/over-mij'); + }); + + it('NOT_FOUND_PAGE_MISSING: 404.html ontbreekt', () => { + const files = validFiles(); + files.delete('404.html'); + expect(found(planExternalization(files, context()))).toEqual([ + '404.html: NOT_FOUND_PAGE_MISSING', + ]); + }); + + it('UNEXPECTED_HTML: een html-bestand buiten het register', () => { + const files = validFiles(); + files.set('soorten-fotoshoots/index.html', page()); + files.set('extra.html', page()); + expect(found(planExternalization(files, context()))).toEqual([ + 'extra.html: UNEXPECTED_HTML', + 'soorten-fotoshoots/index.html: UNEXPECTED_HTML', + ]); + }); + + it('NO_SCRIPTS_MOVED: een pagina zonder uitvoerbaar of verplaatst script', () => { + const files = validFiles(); + files.set( + 'index.html', + '

geen script

', + ); + expect(found(planExternalization(files, context()))).toEqual([ + 'index.html: NO_SCRIPTS_MOVED', + ]); + }); + + it('EXECUTABLE_REMAINS: de verdediging als het herschrijven iets overlaat', () => { + const scripts: ScriptStep = { + externalize: (html) => ({ html, moved: [] }), + find: () => ['geheim()'], + }; + const plan = planExternalization(validFiles(), context(), scripts); + expect(found(plan)).toContain('index.html: EXECUTABLE_REMAINS'); + expect(plan.violations.map(formatViolation).join('\n')).not.toContain( + 'geheim', + ); + }); + + it('UNSUPPORTED_SCRIPT en UNTERMINATED_SCRIPT: meldt de code en gooit niet', () => { + const files = validFiles(); + files.set('index.html', ''); + files.set('over-mij.html', '`, + moved: [{ fileName: 'inline-000000000000.js', body: html }], + }), + find: () => [], + }; + const plan = planExternalization(validFiles(), context(), scripts); + expect(found(plan)).toContain( + 'assets/inline-000000000000.js: COLLISION', + ); + }); + + it('SITEMAP_MISSING en SITEMAP_DIFFERS', () => { + const missing = validFiles(); + missing.delete('sitemap.xml'); + expect(found(planExternalization(missing, context()))).toEqual([ + 'sitemap.xml: SITEMAP_MISSING', + ]); + const differs = validFiles(); + differs.set('sitemap.xml', SITEMAP + ' '); + expect(found(planExternalization(differs, context()))).toEqual([ + 'sitemap.xml: SITEMAP_DIFFERS', + ]); + }); + + it('SOURCE_MAP_PRESENT: een .map-bestand', () => { + const files = validFiles(); + files.set('assets/index-abc.js.map', '{}'); + expect(found(planExternalization(files, context()))).toEqual([ + 'assets/index-abc.js.map: SOURCE_MAP_PRESENT', + ]); + }); + + it.each(ROOT_PATHS)('BUILD_PATH_LEAK: %s in een tekstbestand', (root) => { + const files = validFiles(); + files.set('assets/index-abc.js', `var p = "${root}/src/x.ts";`); + expect(found(planExternalization(files, context()))).toEqual([ + 'assets/index-abc.js: BUILD_PATH_LEAK', + ]); + }); + + it('EMAIL_IN_OUTPUT: in html, js, css en in de inhoud van een verplaatst script', () => { + const files = validFiles(); + files.set('assets/index-abc.js', `var a = "${ADDRESS}";`); + files.set('assets/index-abc.css', `a::after{content:"${ADDRESS}"}`); + files.set('over-mij.html', `

${ADDRESS}

${page('boot("o")')}`); + files.set('index.html', page(`mail("${ADDRESS}")`)); + const plan = planExternalization(files, context()); + const inline = [...plan.writes.entries()].find(([, c]) => + c.includes(ADDRESS), + )![0]; + expect(found(plan)).toEqual( + [ + 'assets/index-abc.js: EMAIL_IN_OUTPUT', + 'assets/index-abc.css: EMAIL_IN_OUTPUT', + 'over-mij.html: EMAIL_IN_OUTPUT', + `${inline}: EMAIL_IN_OUTPUT`, + ].sort(), + ); + }); + + it('slaat de adrescontrole over zonder adres (ongeldige delen)', () => { + const files = validFiles(); + files.set('assets/index-abc.js', `var a = "${ADDRESS}";`); + const plan = planExternalization(files, context({ address: null })); + expect(plan.violations).toEqual([]); + }); + + it('meldt alle overtredingen tegelijk, in een vast formaat zonder adres', () => { + const files = validFiles(); + files.delete('404.html'); + files.set('assets/index-abc.js', `"${ADDRESS}"`); + files.set('x.html', page()); + const lines = planExternalization(files, context()).violations.map( + formatViolation, + ); + expect(lines).toEqual( + expect.arrayContaining([ + '404.html: NOT_FOUND_PAGE_MISSING: de 404-pagina ontbreekt', + 'x.html: UNEXPECTED_HTML: html-bestand dat niet bij het register hoort', + 'assets/index-abc.js: EMAIL_IN_OUTPUT: e-mailadres in de uitvoer', + ]), + ); + expect(lines.join('\n')).not.toContain(ADDRESS); + }); +}); + +describe('containsAddress', () => { + const address = 'info@andreaslop.nl'; + + it.each([ + ['platte tekst', 'info@andreaslop.nl'], + ['hoofdletters', 'INFO@AndreaSlop.NL'], + ['URL-codering', 'mailto:info%40andreaslop.nl'], + ['JavaScript-escape', 'info\\u0040andreaslop.nl'], + ['JavaScript-escape met accolades', 'info\\u{40}andreaslop.nl'], + ['hexadecimale escape', 'info\\x40andreaslop.nl'], + ['decimale entiteit', 'info@andreaslop.nl'], + ['hexadecimale entiteit', 'info@andreaslop.nl'], + ['hexadecimale entiteit in hoofdletters', 'info@andreaslop.nl'], + ['benoemde entiteit', 'info@andreaslop.nl'], + ['midden in tekst', 'Mail info@andreaslop.nl!'], + ])('vindt het adres als %s', (_, text) => { + expect(containsAddress(text, address)).toBe(true); + }); + + it.each([ + ['alleen de gebruiker', 'info'], + ['alleen het domein', 'andreaslop.nl'], + ['met een spatie ertussen', 'info @ andreaslop.nl'], + ['een ander domein', 'info@andreaslop.com'], + ['een andere gebruiker', 'post@andreaslop.nl'], + ['een onbekende codering', 'infoAandreaslop.nl'], + ['lege tekst', ''], + ])('vindt het adres niet bij %s', (_, text) => { + expect(containsAddress(text, address)).toBe(false); + }); + + it('vindt niets bij een adres zonder @', () => { + expect(containsAddress('infoandreaslop.nl', 'infoandreaslop.nl')).toBe( + false, + ); + }); +}); + +describe('containsAddress: eigenschappen', () => { + // Onafhankelijke lijst van BR-MAIL-10 + const encodings = [ + '@', + '%40', + '\\u0040', + '\\u{40}', + '\\x40', + '@', + '@', + '@', + ]; + // Geen @, %, & of \ : een schrijfwijze kan er dus nooit in ontstaan + const safeText = fc.stringMatching(/^[a-z0-9 .<>/="'-]{0,30}$/); + const randomCase = (text: string, flips: boolean[]) => + [...text] + .map((char, i) => + flips[i % flips.length] ? char.toUpperCase() : char, + ) + .join(''); + + it('vindt het adres in elke schrijfwijze op elke plaats, in elke hoofdletterstand (oracle)', () => { + fc.assert( + fc.property( + validEmail, + fc.constantFrom(...encodings), + safeText, + safeText, + fc.array(fc.boolean(), { minLength: 1, maxLength: 8 }), + (email, encoding, before, after, flips) => { + const written = randomCase( + `${email.user}${encoding}${email.domain}`, + flips, + ); + expect( + containsAddress( + `${before}${written}${after}`, + `${email.user}@${email.domain}`, + ), + ).toBe(true); + }, + ), + ); + }); + + it('markeert tekst zonder het adres nooit (oracle)', () => { + fc.assert( + fc.property( + validEmail, + safeText, + fc.constantFrom(...encodings), + (email, text, encoding) => { + const address = `${email.user}@${email.domain}`; + expect(containsAddress(text, address)).toBe(false); + // Een deel van het adres is niet genoeg + expect( + containsAddress( + `${text}${email.user}${encoding}`, + address, + ), + ).toBe(false); + expect( + containsAddress( + `${encoding}${email.domain}${text}`, + address, + ), + ).toBe(false); + }, + ), + ); + }); +}); + +// De drie pagina's van `context()` plus 404.html, in de volgorde van het scenario +const SCENARIO_FILES = [ + 'index.html', + 'over-mij.html', + 'soorten-fotoshoots/newborn.html', + '404.html', +]; +const EXTRA_REFERENCE = + ''; + +function filesOf(scenario: OutputScenario, address: string) { + const files = new Map(); + scenario.pages.forEach((p, i) => { + if (!p.present) return; + files.set( + SCENARIO_FILES[i], + p.content.html + + (p.reference ? EXTRA_REFERENCE : '') + + (p.leakAddress ? `

${address}

` : '') + + (p.bad === 'unsupported' + ? '' + : '') + + (p.bad === 'unterminated' ? '`, + ); + }); + const first = planExternalization(files, context()); + expect(first.violations).toEqual([]); + for (const [file, content] of first.writes) { + files.set(file, content); + } + const second = planExternalization(files, context()); + expect(second.writes.size).toBe(0); + expect(second.violations).toEqual([]); + }), + ); + }); +}); + +// --------------------------------------------------------------------------- +// externalizeOutput met een echte map + +const temporary: string[] = []; +afterEach(() => { + for (const dir of temporary.splice(0)) { + rmSync(dir, { recursive: true, force: true }); + } +}); + +// /web/dist/client: de repositorywortel voor de lekcontrole is /web +function outputDir() { + const root = mkdtempSync(join(tmpdir(), 'externalize-')); + temporary.push(root); + const clientDir = join(root, 'web', 'dist', 'client'); + const put = (file: string, content: string) => { + mkdirSync(dirname(join(clientDir, file)), { recursive: true }); + writeFileSync(join(clientDir, file), content, 'utf8'); + }; + for (const path of Object.keys(sitePages)) { + put(pageFile(path), page(`boot("${path}")`)); + } + put('404.html', page('boot("404")')); + put('sitemap.xml', sitemapXml(pageList(sitePages), siteUrl)); + put('assets/index-abc.js', 'console.log(1);'); + return { root: join(root, 'web'), clientDir, put }; +} + +const listing = (dir: string) => + readdirSync(dir, { recursive: true, encoding: 'utf8' }).sort(); + +const silent = () => ({ log: vi.fn(), error: vi.fn() }); + +describe('externalizeOutput', () => { + it('schrijft eerst de scriptbestanden, dan de html, en meldt รฉรฉn regel', () => { + const { clientDir } = outputDir(); + const out = silent(); + const result = externalizeOutput(clientDir, out); + + expect(result.exitCode).toBe(0); + expect(result.violations).toEqual([]); + const firstHtml = result.written.findIndex((f) => f.endsWith('.html')); + expect(firstHtml).toBeGreaterThan(0); + expect( + result.written + .slice(0, firstHtml) + .every((f) => !f.endsWith('.html')), + ).toBe(true); + expect( + result.written.slice(firstHtml).every((f) => f.endsWith('.html')), + ).toBe(true); + + const index = readFileSync(join(clientDir, 'index.html'), 'utf8'); + const reference = /src="\/(assets\/inline-[0-9a-f]{12}\.js)"/.exec( + index, + )!; + expect(readFileSync(join(clientDir, reference[1]), 'utf8')).toBe( + 'boot("/")', + ); + expect(index).not.toContain('boot('); + expect(out.error).not.toHaveBeenCalled(); + expect(out.log).toHaveBeenCalledTimes(1); + expect(out.log.mock.calls[0][0]).toContain( + `${Object.keys(sitePages).length + 1} pagina's gecontroleerd`, + ); + expect(out.log.mock.calls[0][0]).toContain( + `${Object.keys(sitePages).length + 1} scripts verplaatst`, + ); + }); + + it('doet bij een tweede keer niets', () => { + const { clientDir } = outputDir(); + externalizeOutput(clientDir, silent()); + const before = listing(clientDir); + const out = silent(); + const result = externalizeOutput(clientDir, out); + expect(result).toEqual({ exitCode: 0, violations: [], written: [] }); + expect(listing(clientDir)).toEqual(before); + expect(out.log.mock.calls[0][0]).toContain('0 scripts verplaatst'); + }); + + it('schrijft niets en meldt alles bij een overtreding', () => { + const { clientDir, put } = outputDir(); + rmSync(join(clientDir, 'over-mij.html')); + put('assets/index-abc.js.map', '{}'); + const before = listing(clientDir); + const out = silent(); + const result = externalizeOutput(clientDir, out); + + expect(result.exitCode).toBe(1); + expect(result.written).toEqual([]); + expect(listing(clientDir)).toEqual(before); + expect(out.log).not.toHaveBeenCalled(); + expect(out.error.mock.calls.map(([line]) => line)).toEqual( + result.violations.map(formatViolation), + ); + expect(result.violations.map((v) => v.code).sort()).toEqual([ + 'PAGE_MISSING', + 'SOURCE_MAP_PRESENT', + ]); + }); + + it('vindt het e-mailadres van de site in een uitvoerbestand', () => { + const { clientDir, put } = outputDir(); + put('assets/index-abc.js', 'var a = "info@andreaslop.nl";'); + const result = externalizeOutput(clientDir, silent()); + expect(result.violations.map(formatViolation)).toEqual([ + 'assets/index-abc.js: EMAIL_IN_OUTPUT: e-mailadres in de uitvoer', + ]); + }); + + it.each([ + [ + 'met voorwaartse slashes', + (root: string) => root.replaceAll('\\', '/'), + ], + ['met backslashes', (root: string) => root.replaceAll('/', '\\')], + [ + 'met verdubbelde backslashes', + (root: string) => + root.replaceAll('/', '\\').replaceAll('\\', '\\\\'), + ], + ])('vindt het pad van de repository %s', (_, style) => { + const { clientDir, put, root } = outputDir(); + put('assets/index-abc.js', `var p = "${style(root)}";`); + const result = externalizeOutput(clientDir, silent()); + expect(result.violations.map((v) => v.code)).toEqual([ + 'BUILD_PATH_LEAK', + ]); + }); + + it('leest alleen tekstbestanden en gaat niet af op een bestandssysteemwortel', () => { + // clientDir direct onder de wortel: '../..' is de wortel zelf en mag + // niet elk bestand met een slash als lek aanmerken + const { clientDir, put } = outputDir(); + put('logo.png', 'binair'); + expect(externalizeOutput(clientDir, silent()).exitCode).toBe(0); + const rootResult = externalizeOutput(join(clientDir, '..'), silent()); + expect( + rootResult.violations.every((v) => v.code !== 'BUILD_PATH_LEAK'), + ).toBe(true); + }); +}); + +describe('externalizeOutput als opdrachtregel', () => { + const script = join( + dirname(fileURLToPath(import.meta.url)), + 'externalizeInlineScripts.ts', + ); + const run = (dir: string) => + spawnSync(process.execPath, [script, dir], { encoding: 'utf8' }); + + it('geeft exitcode 0 en รฉรฉn regel bij een geldige uitvoer', () => { + const { clientDir } = outputDir(); + const result = run(clientDir); + expect(result.status).toBe(0); + expect(result.stdout.trim().split('\n')).toHaveLength(1); + expect(existsSync(join(clientDir, 'assets'))).toBe(true); + }); + + it('geeft exitcode 1 en schrijft niets bij een overtreding', () => { + const { clientDir } = outputDir(); + rmSync(join(clientDir, '404.html')); + const before = listing(clientDir); + const result = run(clientDir); + expect(result.status).toBe(1); + expect(result.stderr).toContain('404.html: NOT_FOUND_PAGE_MISSING'); + expect(listing(clientDir)).toEqual(before); + }); +}); diff --git a/web/config/externalizeInlineScripts.ts b/web/config/externalizeInlineScripts.ts new file mode 100644 index 0000000..476947c --- /dev/null +++ b/web/config/externalizeInlineScripts.ts @@ -0,0 +1,363 @@ +// Stap na `vite build` die de inline scripts van Start in dist/client naar +// bestanden verplaatst en de uitvoer controleert. +// +// Waarom (BR-BLD-12): de CSP staat alleen script-src 'self' en Umami toe, en +// Start zet inline scripts in elke geprerenderde pagina. Zonder deze stap +// blokkeert de browser ze. De CSP blijft ongewijzigd. +// +// Alles wordt eerst in het geheugen gepland (planExternalization, puur). Pas +// als er geen enkele overtreding is, schrijft de runner: eerst de +// scriptbestanden, daarna de aangepaste HTML (BR-SCR-12, SECURITY-15). Een +// mislukte controle laat dist/client dus ongemoeid. +import { + mkdirSync, + readFileSync, + readdirSync, + statSync, + writeFileSync, +} from 'node:fs'; +import { dirname, join, parse, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { emailAddress } from '../src/lib/emailAddress.ts'; +import { siteUrl } from '../src/seo.ts'; +import siteContent from '../src/content/siteContent.ts'; +import { sitemapXml } from '../src/sitemap.ts'; +import sitePages, { pageList } from '../src/sitePages.ts'; +import { + ScriptError, + externalizeInlineScripts, + findExecutableInlineScripts, +} from './inlineScripts.ts'; +import { NOT_FOUND_FILE, pageFile } from './pageFiles.ts'; + +export type ViolationCode = + | 'NO_HTML' + | 'PAGE_MISSING' + | 'NOT_FOUND_PAGE_MISSING' + | 'UNEXPECTED_HTML' + | 'NO_SCRIPTS_MOVED' + | 'EXECUTABLE_REMAINS' + | 'UNSUPPORTED_SCRIPT' + | 'UNTERMINATED_SCRIPT' + | 'COLLISION' + | 'EMAIL_IN_OUTPUT' + | 'SITEMAP_MISSING' + | 'SITEMAP_DIFFERS' + | 'SOURCE_MAP_PRESENT' + | 'BUILD_PATH_LEAK'; + +export interface Violation { + file: string; + code: ViolationCode; + // Nooit een scriptinhoud en nooit het e-mailadres (BR-SCR-21) + detail: string; +} + +export interface ExpectedFileSet { + // Paginapad uit het register naar zijn bestand + pages: Map; + notFound: string; +} + +export interface PlanContext { + expected: ExpectedFileSet; + // Het samengestelde adres, of null als de delen ongeldig zijn + address: string | null; + sitemap: string; + // De repositorywortel in alle schrijfwijzen die in tekst kunnen staan + rootPaths: string[]; +} + +export interface OutputPlan { + // Relatief pad naar nieuwe inhoud + writes: Map; + violations: Violation[]; +} + +// De twee functies van de scriptstap als parameter, zodat de verdediging +// EXECUTABLE_REMAINS getest kan worden: met de echte functies kan ze niet +// optreden (BR-SCR-11). +export interface ScriptStep { + externalize: typeof externalizeInlineScripts; + find: typeof findExecutableInlineScripts; +} + +const defaultScriptStep: ScriptStep = { + externalize: externalizeInlineScripts, + find: findExecutableInlineScripts, +}; + +const ASSETS_DIR = 'assets'; +const SITEMAP_FILE = 'sitemap.xml'; +const MOVED_REFERENCE = /src="\/assets\/inline-[0-9a-f]{12}\.js"/; + +// Hoe een '@' in een bestand kan staan zonder dat het adres leesbaar is: +// platte tekst, URL-codering, JavaScript-escapes en HTML-entiteiten +const AT_ENCODINGS = [ + '@', + '%40', + '\\u0040', + '\\u{40}', + '\\x40', + '@', + '@', + '@', +]; + +// Staat het adres in een van de schrijfwijzen in de tekst? Hoofdletterongevoelig. +export function containsAddress(text: string, address: string): boolean { + const at = address.indexOf('@'); + if (at === -1) return false; + const haystack = text.toLowerCase(); + const user = address.slice(0, at).toLowerCase(); + const domain = address.slice(at + 1).toLowerCase(); + return AT_ENCODINGS.some((encoding) => + haystack.includes(`${user}${encoding}${domain}`), + ); +} + +const isHtml = (file: string) => file.endsWith('.html'); + +// Een ScriptError heeft het bericht `CODE: detail`; de runner zet er zelf de +// code en het bestand voor +const detailOf = (error: ScriptError) => + error.message.slice(error.code.length + 2); + +export function formatViolation({ file, code, detail }: Violation): string { + return `${file}: ${code}: ${detail}`; +} + +// De beslissingen van de runner zonder bestandssysteem. `files` bevat alle +// tekstbestanden (en eventuele .map-bestanden) onder dist/client op relatief +// pad met voorwaartse slashes. +export function planExternalization( + files: ReadonlyMap, + context: PlanContext, + scripts: ScriptStep = defaultScriptStep, +): OutputPlan { + const violations: Violation[] = []; + const writes = new Map(); + const add = (file: string, code: ViolationCode, detail: string) => + violations.push({ file, code, detail }); + + const htmlFiles = [...files.keys()].filter(isHtml).sort(); + const expectedFiles = new Set([ + ...context.expected.pages.values(), + context.expected.notFound, + ]); + + if (htmlFiles.length === 0) { + // De ontbrekende pagina's afzonderlijk melden zou alleen herhalen + add('.', 'NO_HTML', 'geen .html-bestand in de uitvoermap'); + } else { + for (const [path, file] of context.expected.pages) { + if (!files.has(file)) { + add(file, 'PAGE_MISSING', `pagina ${path} ontbreekt`); + } + } + if (!files.has(context.expected.notFound)) { + add( + context.expected.notFound, + 'NOT_FOUND_PAGE_MISSING', + 'de 404-pagina ontbreekt', + ); + } + } + for (const file of htmlFiles) { + if (!expectedFiles.has(file)) { + add( + file, + 'UNEXPECTED_HTML', + 'html-bestand dat niet bij het register hoort', + ); + } + } + + for (const file of htmlFiles) { + if (!expectedFiles.has(file)) continue; + const html = files.get(file)!; + + let result; + try { + result = scripts.externalize(html); + } catch (error) { + if (!(error instanceof ScriptError)) throw error; + add(file, error.code, detailOf(error)); + continue; + } + + const remaining = scripts.find(result.html).length; + if (remaining > 0) { + add( + file, + 'EXECUTABLE_REMAINS', + `${remaining} uitvoerbaar inline script blijft over`, + ); + } + // Een al verwerkte pagina telt mee, dus twee keer draaien mag + if (!MOVED_REFERENCE.test(result.html)) { + add( + file, + 'NO_SCRIPTS_MOVED', + 'geen verwijzing naar een verplaatst inline script', + ); + } + + for (const { fileName, body } of result.moved) { + const path = `${ASSETS_DIR}/${fileName}`; + const existing = writes.get(path) ?? files.get(path); + if (existing !== undefined && existing !== body) { + add(path, 'COLLISION', 'bestaat al met andere inhoud'); + } else if (existing === undefined) { + writes.set(path, body); + } + } + if (result.html !== html) writes.set(file, result.html); + } + + // De uitvoer zoals hij na het schrijven is: ook de verplaatste scripts + const finalFiles = new Map(files); + for (const [path, content] of writes) finalFiles.set(path, content); + + for (const [file, content] of finalFiles) { + if (file.endsWith('.map')) { + add(file, 'SOURCE_MAP_PRESENT', 'sourcemap in de uitvoer'); + } + if (context.address && containsAddress(content, context.address)) { + add(file, 'EMAIL_IN_OUTPUT', 'e-mailadres in de uitvoer'); + } + if (context.rootPaths.some((root) => content.includes(root))) { + add(file, 'BUILD_PATH_LEAK', 'pad van de repository in de uitvoer'); + } + } + + const sitemap = files.get(SITEMAP_FILE); + if (sitemap === undefined) { + add(SITEMAP_FILE, 'SITEMAP_MISSING', 'bestand ontbreekt'); + } else if (sitemap !== context.sitemap) { + add( + SITEMAP_FILE, + 'SITEMAP_DIFFERS', + 'inhoud wijkt af van het pagina-register', + ); + } + + return { writes, violations }; +} + +// Alleen deze bestanden worden gelezen en op adres en pad doorzocht +const TEXT_EXTENSIONS = [ + '.html', + '.js', + '.css', + '.xml', + '.txt', + '.json', + '.webmanifest', + '.map', +]; + +function readOutput(clientDir: string): Map { + const files = new Map(); + const entries = readdirSync(clientDir, { + recursive: true, + encoding: 'utf8', + }) + .map((entry) => entry.replaceAll('\\', '/')) + .filter((entry) => TEXT_EXTENSIONS.some((ext) => entry.endsWith(ext))) + .sort(); + for (const entry of entries) { + const path = join(clientDir, entry); + if (statSync(path).isFile()) + files.set(entry, readFileSync(path, 'utf8')); + } + return files; +} + +// De repositorywortel in de schrijfwijzen waarin hij in tekst kan staan: +// met / , met \ en met verdubbelde \ zoals in een JSON- of JS-string +function rootPathsOf(root: string): string[] { + // De wortel van het bestandssysteem zou alles als lek aanmerken + if (parse(root).root === root) return []; + return [ + ...new Set([ + root, + root.replaceAll('\\', '/'), + root.replaceAll('/', '\\'), + root.replaceAll('/', '\\').replaceAll('\\', '\\\\'), + ]), + ]; +} + +function contextFor(clientDir: string): PlanContext { + return { + expected: { + pages: new Map( + Object.keys(sitePages).map((path) => [path, pageFile(path)]), + ), + notFound: NOT_FOUND_FILE, + }, + address: emailAddress(siteContent.email), + sitemap: sitemapXml(pageList(sitePages), siteUrl), + rootPaths: rootPathsOf(resolve(clientDir, '../..')), + }; +} + +export interface RunResult { + exitCode: 0 | 1; + violations: Violation[]; + written: string[]; +} + +interface Log { + log: (message: string) => void; + error: (message: string) => void; +} + +// Leest de map, plant, en schrijft alleen zonder overtredingen. Geeft de +// exitcode terug in plaats van hem te zetten, zodat tests hem kunnen lezen. +export function externalizeOutput( + clientDir: string, + out: Log = console, +): RunResult { + const context = contextFor(clientDir); + const { writes, violations } = planExternalization( + readOutput(clientDir), + context, + ); + + if (violations.length > 0) { + for (const violation of violations) { + out.error(formatViolation(violation)); + } + return { exitCode: 1, violations, written: [] }; + } + + // Scriptbestanden eerst: een afgebroken run laat nooit HTML achter die + // naar een bestand verwijst dat niet bestaat + const paths = [...writes.keys()].sort( + (a, b) => Number(isHtml(a)) - Number(isHtml(b)), + ); + for (const path of paths) { + const target = join(clientDir, path); + mkdirSync(dirname(target), { recursive: true }); + writeFileSync(target, writes.get(path)!, 'utf8'); + } + + const moved = paths.filter((path) => !isHtml(path)).length; + out.log( + `Inline scripts verplaatst: ${context.expected.pages.size + 1} pagina's gecontroleerd, ${moved} scripts verplaatst, ${paths.length} bestanden geschreven`, + ); + return { exitCode: 0, violations, written: paths }; +} + +// Draait alleen als het bestand zelf wordt gestart (pnpm build), niet als een +// test het importeert. Optioneel argument: de map, standaard dist/client. +if ( + process.argv[1] && + resolve(process.argv[1]) === fileURLToPath(import.meta.url) +) { + process.exitCode = externalizeOutput( + resolve(process.argv[2] ?? 'dist/client'), + ).exitCode; +} diff --git a/web/config/inlineScripts.test.ts b/web/config/inlineScripts.test.ts new file mode 100644 index 0000000..4815750 --- /dev/null +++ b/web/config/inlineScripts.test.ts @@ -0,0 +1,507 @@ +import { createHash } from 'node:crypto'; +import fc from 'fast-check'; +import { describe, expect, it } from 'vitest'; +import { + canonicalHtmlWithModel, + htmlFragments, + htmlWithModel, + scriptBody, +} from '../src/test/htmlArbitraries'; +import { + ScriptError, + externalizeInlineScripts, + findExecutableInlineScripts, +} from './inlineScripts'; + +// Onafhankelijk van de implementatie: de naam volgens BR-SCR-07 +const fileOf = (body: string) => + `inline-${createHash('sha256').update(body, 'utf8').digest('hex').slice(0, 12)}.js`; + +const referenceOf = (attributes: string, body: string) => + ``; + +// Een door de stap geplaatste verwijzing: ', + ); + expect(result.html).toBe(referenceOf(' data-tsr-stream-part=""', 'A')); + expect(result.moved).toEqual([{ fileName: fileOf('A'), body: 'A' }]); + }); + + it('laat een extern module-script met async ongemoeid', () => { + const html = ''; + expect(externalizeInlineScripts(html)).toEqual({ html, moved: [] }); + }); + + it('verplaatst een kaal script en kent het bestand de inhoud toe', () => { + const result = externalizeInlineScripts( + '', + ); + expect(result.html).toBe( + referenceOf('', 'document.currentScript.remove()'), + ); + expect(result.moved).toHaveLength(1); + }); + + it.each([ + [ + 'een JSON-LD-blok', + '', + ], + [ + 'een style-body', + '', + ], + ['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 = `go()`; + 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 = `{"a":1}`; + 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('

{ + fails('go()go()', () => { + const html = ''; + expect(findExecutableInlineScripts(html)).toEqual([ + 'a = "
"; b = 1;', + ]); + expect(findExecutableInlineScripts('')).toEqual([ + 'a', + ]); + expect(findExecutableInlineScripts('`, + ); + expect(result.html).toBe(referenceOf(attributes, 'go()')); + }); + + it('behoudt een afsluitende / in de tag en leest de naam hoofdletterongevoelig', () => { + expect(externalizeInlineScripts('').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<script>x</script>', + ), + ).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 <script>x()</script>', + '', + '<script>x()</script>', + '', + ) + .map((html) => ({ kind: 'rawText' as const, html })); + +const attributeDecoyPiece: fc.Arbitrary = fc + .constantFrom( + '
t
', + "t", + '', + '

w()>t

', + ) + .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' ? ( + - ))} + {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 + + ))} {/* 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(