Files
AndreaSlopFotografie/aidlc-docs/features/prerendering/construction/plans/start-migration-code-generation-plan.md
T

521 lines
67 KiB
Markdown

# 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 <files>`), `pnpm test` (vitest with coverage and thresholds), `pnpm build`, `pnpm audit:deps`.
- Targeted tests while working: `pnpm exec vitest run <path>` (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 <file>`, 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 `<scratch>/baseline/mobile`.
3. Desktop: `pnpm exec lhci collect --config=lighthouserc.desktop.cjs --numberOfRuns=3`. Move `.lighthouseci` to `<scratch>/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 `<script ... src>` and `<link rel="modulepreload">` in `web/dist/index.html` ("entry JavaScript"), and of all `web/dist/assets/*.js` ("all JavaScript").
- Done when: the report exists with a table per device (rows = URL, columns = score, FCP, LCP, TBT, CLS, script transfer) plus the gzip numbers, method line (three runs, median, command lines), commit hash, machine description, Node version.
- Record: `aidlc-docs/features/prerendering/construction/start-migration/code/measurement-baseline.md`. Also keep the scratch script path in the report so Step 34 reuses the identical script.
---
## Part B: Early proof with the real app (batch B1, Sonnet, sequential)
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 [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.
- Why first: with `{ ssr: false }`, `document.readyState`, `document.hidden` and `window.location` evaluated in render, the server render throws, so no page can be prerendered. These edits are small, pure React and covered by the old tests (CP0). The behaviour tests for them come in Step 19.
- Files (modify unless "create"):
- `web/src/hooks/useHydrated.ts` (create): `useSyncExternalStore(subscribeNoop, () => true, () => false)`; one-line comment on why (same behaviour as the router's internal `useHydrated`).
- `web/src/hooks/usePageLoaded.ts`: store-based, `subscribe` adds a `load` listener (`{ once: true }`) and returns its removal, snapshot `document.readyState === 'complete'`, server snapshot `false`.
- `web/src/hooks/useInView.ts`: keep options and return shape. `unsupported` from `useSyncExternalStore(noopSubscribe, () => typeof IntersectionObserver === 'undefined', () => false)`; `inView = skip || intersected || unsupported`; the effect returns early when `!element || skip || unsupported || intersected`. Keep the "counts as in view" comment, adjusted.
- `web/src/hooks/useReveal.ts`, `web/src/components/Hero/useHeroSlider.ts`, `web/src/components/home/ContactSection/ContactSection.tsx`, `web/src/components/home/Testimonials/TestimonialCarousel.tsx`: remove `{ ssr: false }` from `useMediaQuery`; update the comments.
- `web/src/components/Hero/useHeroSlider.ts`: `hidden` from a store (`subscribe` to `document` `visibilitychange`, snapshot `document.hidden`, server snapshot `false`) instead of `useState(() => document.hidden)` plus effect.
- `web/src/components/NavigationBar/NavigationBar.tsx`: remove `{ ssr: false }` from `useBreakpointValue` only (the `activeOptions` change is Step 16).
- `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) [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.
- Do:
1. In `web/`: `pnpm add @tanstack/react-start@1.169.4` and `pnpm add -D playwright-core@1.55.0` (the Playwright version already pinned in CI as `PLAYWRIGHT_VERSION`; used from Step 26). If pnpm reports a peer conflict with `@tanstack/react-router`, try `@tanstack/react-router@1.170.46` (the spike's version); record the resolved versions. Any other conflict: STOP. Check that the `seroval` and `seroval-plugins` overrides in `pnpm-workspace.yaml` still apply (`pnpm why seroval`). Run `pnpm audit:deps`; a failure that is not fixable by a patch bump: STOP.
2. Read Start's type definitions and docs in `node_modules/@tanstack/react-start` for the exact plugin and prerender option names (spike facts in application-design.md: output in `dist/client`, `autoSubfolderIndex: false`, pages with `outputPath`). Do not guess option names.
3. `web/vite.config.ts`: replace `tanstackRouter(...)` by the Start plugin with prerender enabled for `Object.keys(sitePages)` (import from `./src/sitePages.ts`; the list is derived, never typed twice) plus `{ path: '/404', outputPath: '/404.html' }` (use `NOT_FOUND_PATH` and `NOT_FOUND_FILE` from a temporary local constant now; Step 7 creates `config/pageFiles.ts` and Step 24 switches the import), `autoSubfolderIndex: false`, no link crawling beyond that list (V5), route code splitting kept (V6). The Start plugin is applied only outside Vitest (`defineConfig(({ mode }) => ...)` with `mode !== 'test'`; verify that Vitest passes `mode: 'test'`). Keep `react()` and `sitemapPlugin()`, `resolve.tsconfigPaths`, the `server.headers` and `preview.headers` and the whole `test` block. Add `define: { 'import.meta.env.VITE_BUILD_YEAR': JSON.stringify(String(new Date().getFullYear())) }` (BR-HYD-14) and declare the type if `tsc` needs it.
4. `web/config/sitemapPlugin.ts`: emit `sitemap.xml` only in the client environment (`this.environment.name === 'client'`, V7); keep the Dutch comments style, extend the comment with why. Verify that `public/` has no `sitemap.xml`.
5. `web/src/router.tsx` (create): `routerOptions()` returning `{ routeTree, scrollRestoration: true, defaultErrorComponent: ErrorPage }` and `getRouter()` calling `createRouter(routerOptions())`; the `declare module '@tanstack/react-router' { interface Register { router: ReturnType<typeof getRouter> } }` moved from `main.tsx`. Keep the two Dutch comments of `main.tsx` (scroll restoration, error component).
6. `web/src/routes/__root.tsx`: `shellComponent` rendering `<html lang="nl">`, `<head><HeadContent /></head>`, `<body>` with `ChakraProvider value={system}` (keep the Dutch comment "De site is alleen licht...") around `{children}`, then `<Scripts />`; the four `@fontsource` CSS imports move here; `head()` returns charset, viewport, `rel="icon" type="image/png" href="/favicon.png"` and `rel="apple-touch-icon"` plus the existing `siteHead(siteContent)` content; `component` stays a layout rendering `AppShell` and the devtools `Suspense` but not `HeadContent`; `notFoundComponent` and `errorComponent` stay (BR-ENT-02, 04, BR-BLD-05, 07).
7. `web/src/client.tsx` (create): `startSentry()` first, then hydrate Start's client inside `StrictMode`, following Start's documented custom client entry (V1). Delete `web/src/main.tsx` and `web/index.html` with plain `rm`. Check that nothing else imports `main.tsx` or relies on the `data-fallback` tags.
8. `web/src/routes/$.tsx` (create): `createFileRoute('/$')({ component: NotFound })` (BR-404-01). No `head()`, no `notFound()`.
9. Add `.tanstack` to `web/.gitignore` (generated Start cache; `eslint.config.js` already ignores it).
10. Create `code/verification-log.md` with the 18 rows (Status "open") and fill V1, V3 (first look), V5, V6, V7, V11 (normal pages), V13, V15 (styles present: `<style data-emotion` in the HTML of `/over-mij`), V17 (grep the HTML for ` on[a-z]+=` and `javascript:`).
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) [x]
- Executor: Sonnet.
- Implements: BR-TST-01, 02; D12; NFR-PR-Q-01; V2.
- Do:
1. `web/src/test/renderApp.tsx`: build the router with `createRouter({ ...routerOptions(), history: createMemoryHistory({ initialEntries: [path] }) })`, render inside `ChakraProvider`, no `<html>`. Keep the exports (`renderApp`, `expectShell`) and the test names that use them.
2. Settle V2: does `RouterProvider` in jsdom render the root route's `shellComponent` (an `<html>` inside the RTL container)? Test with one page. If it does, make the tests use a root route variant without `shellComponent` (for example build the tree for tests from the same `routeTree` but with the root options overridden, or a test-only root created in `src/test`), without changing production code paths; if neither works within the design (D12), STOP.
3. Make sure the route tree used by tests includes the new `$` route (`src/routeTree.gen.ts` is regenerated by the Start plugin during `pnpm build`; commit-worthy; keep it excluded from coverage and lint). Check `git diff --stat src/routeTree.gen.ts` and read the diff: only the `$` route and Start's declarations may be new.
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 [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).
- Done when: the report exists. If every one of V1, V2, V5, V6, V7 is OK, continue with the parallel batches. If any is BLOCKED or DEVIATION, STOP and report to the main session; do not start B2 to B4.
---
## Part C: Script step (batch B2, Sonnet; parallel with B3 and B4)
Files are new `config/*` files and `src/test/htmlArbitraries.ts`. Config files are Dutch-commented like their neighbours. They run under Node type stripping: relative imports with `.ts`, no aliases.
### Step 7: `config/pageFiles.ts` [x]
- Executor: Sonnet.
- Implements: BR-BLD-02, 03; domain-entities `config/pageFiles.ts`.
- Do: create the pure module with `NOT_FOUND_PATH = '/404'`, `NOT_FOUND_FILE = '404.html'`, `pageFile(path: string): string` (`/` gives `index.html`; otherwise the path without its leading slash plus `.html`) and `pagePath(file: string): string | undefined` (inverse; `undefined` for `404.html` and anything that is not a `.html` page file). Comment on why one mapping serves `vite.config.ts`, the runner and the preview server.
- Done when: `pnpm exec tsc --noEmit` clean. (Switching `vite.config.ts` to import it happens in Step 24, to keep B2 off B1's files.)
### Step 8: `config/inlineScripts.ts` [x]
- Executor: Sonnet.
- Implements: BR-SCR-01 to 11, 22 (nothing to build for 22); FR-PR-19, 20; D2, D3.
- Do: create the module with the exports of component-methods.md (`MovedScript`, `ExternalizeResult`, `externalizeInlineScripts`, `findExecutableInlineScripts`) and no dependency except `node:crypto` for SHA-256. Implement one internal scanner (BR-SCR-02) that yields script elements with their range, verbatim attribute text and body; the classification of flowchart 1.1 (BR-SCR-04: `src` attribute in any form, empty body, type list, `module`); the unsupported-form checks that throw (BR-SCR-05: `async`/`defer` on a classic script, `<!--` in the body, relative specifier in a module body; error type or message with the codes `UNSUPPORTED_SCRIPT` and `UNTERMINATED_SCRIPT` so the runner can map them); naming (BR-SCR-07, 08; first 12 hex of SHA-256 of the UTF-8 body); the replacement `<script` + attribute text + ` src="/assets/inline-<hash>.js"` + `></script>` (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) [x]
- 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 `</script`, no `<!--`, no `async`/`defer`), external scripts, empty scripts, data blocks (`application/ld+json`, `importmap`, `speculationrules`), comments and `style` bodies and attribute values that contain script-like text, plain markup. Export an arbitrary of `{ html, model }` and one of independent fragment lists (for P9). Also decoys that must be skipped (BR-SCR-02). Reuse nothing from the lib that is not needed; keep generators reusable (PBT-07).
2. `inlineScripts.test.ts`: example-based tests for every row of business-logic-model.md § 3.1 and for each branch of BR-SCR-04 (type list incl. `type=""`, uppercase, `module`; `src` present without value), BR-SCR-05 (a, b, c), BR-SCR-03 (unterminated), attribute retention, trailing `/` in the tag, `>` 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) [x]
- 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` [x]
- 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-<hash>.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 `<file>: <CODE>: <detail>`; 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) [x]
- 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) [x]
- 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 <dir>`).
- 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 `<!--`, NO_SCRIPTS_MOVED, UNEXPECTED_HTML): analyse; if the cause is in Start's output format, STOP (design BR-SCR-05 and 17 need a decision), do not relax a check. Then temporarily bypass the email check only in the scratch run (for example by running the plan with `address: null` from a throwaway script in the scratch folder) to confirm that otherwise the run is clean and idempotent (second run prints no writes), that every page has the expected number of moved scripts (list the counts; V4 asks whether the minimum of one in BR-SCR-17 is right or two should be demanded), and V3's final list (bootstrap, boundary, scroll restoration, React completion scripts). Grep the moved files and HTML for a build timestamp and a build path (V13) and for `on*=` attributes and `javascript:` (V17).
- Done when: the verification log rows V3, V4, V13, V17 are updated with evidence. Report V4's recommendation in the log (keep one or demand two); the design says one unless the log shows a reason; a change to two is a design change: STOP and report instead of editing.
---
## Part D: Hydration safety (batch B3, Sonnet; parallel with B2 and B4)
Disjoint from B2 and B4. Runs only targeted `vitest run` commands. The editing order inside the batch is the step order.
### Step 14: `lib` changes for the e-mail address [x]
- Executor: Sonnet.
- Implements: BR-MAIL-07, 08; FR-PR-22.
- Files: `web/src/lib/emailAddress.ts`, `web/src/lib/contactChannels.ts`.
- Do: add `isEmailAddressValid(parts: EmailAddress): boolean`; `emailAddress` reuses it (same results as today). `contactChannels(email, socials, assemble)` with the third parameter: `assemble` false and valid parts give `{ kind: 'email-pending' }` first (no `href`, no `label`); `assemble` true gives the existing email channel; invalid parts none. Extend the `ContactChannel` union (and `external: false` stays on the email kind only). Existing callers are updated in Step 17. Comments in English like the file.
- Done when: `pnpm exec tsc --noEmit` reports only the call sites to be fixed in Step 17 (note them), nothing else.
### Step 15: Tests for the `lib` changes (P14, P15) [x]
- Executor: Sonnet.
- Implements: NFR-PR-Q-01, Q-02; PBT-03, 05, 10; P14, P15; 100% coverage of `src/lib`.
- Files: `web/src/lib/emailAddress.test.ts`, `web/src/lib/contactChannels.test.ts` (extend; keep the existing tests, Dutch titles like the file).
- Do: examples for each branch of the new parameter and the new function. P15 (oracle): `isEmailAddressValid(p) === (emailAddress(p) !== null)` over `anyEmail`. P14 (invariant): with `assemble` false, `JSON.stringify(contactChannels(...))` never contains the assembled address, and the channel count equals the count with `assemble` true, over `anySiteContent`/`validEmail` and `socialLink` lists.
- Done when: `pnpm exec vitest run src/lib/emailAddress.test.ts src/lib/contactChannels.test.ts` passes.
### Step 16: Search gating, navigation, not found [x]
- Executor: Sonnet.
- Implements: BR-HYD-10, 11, 12, 13; BR-404-04, 05; FR-PR-06, 07, 15.
- Files: `web/src/routes/index.tsx`, `web/src/routes/contact.tsx`, `web/src/routes/portfolio.tsx`, `web/src/components/NavigationBar/NavigationBar.tsx`, `web/src/components/NavigationBar/MobileNav.tsx`, `web/src/components/StatusPage/NotFound.tsx`.
- Do:
- Routes: `const hydrated = useHydrated()` and pass `hydrated ? search.pakket : undefined` (portfolio: `search.shoot`) on; leave `validateSearch`, `head`, the tidy effect and the navigation callback otherwise unchanged.
- Navigation: all top-level `NavLink`s in `NavigationBar` and the plain `RouterLink`s in `MobileNav` get `activeOptions={{ exact: true, includeSearch: false }}` (a shared constant per file like `NavSubmenu` has).
- `NotFound`: use `hydrated && isShootSectionPath(pathname)`. Keep the in-body `<title>` and `noindex` meta.
- Done when: `pnpm exec tsc --noEmit` clean; the old tests of these files pass (`pnpm exec vitest run src/app.test.tsx src/navSubmenu.test.tsx src/components/NavigationBar src/components/StatusPage`); tests that fail because they assumed the first-render search are adapted per BR-TST-02 and listed in the Record line.
- Record (2026-10-31): no old test needed a change; new test cases in `NavigationBar.test.tsx`, `NotFound.test.tsx`, `src/routes/hydration.test.tsx`.
### Step 17: Footer and e-mail components [x]
- Executor: Sonnet.
- Implements: BR-HYD-14; BR-MAIL-01 to 06, 09 (placeholders only); FR-PR-22; V10 (first sizing).
- Files: `web/src/hooks/useEmailAddress.ts` (create), `web/src/components/Footer/Footer.tsx`, `web/src/components/ContactDetails/ContactDetails.tsx`, `web/src/components/ContactForm/ContactFormGate.tsx`, `web/src/components/ContactForm/ContactForm.tsx`.
- Do:
- `useEmailAddress(email)` returns `{ available, address }` (BR-MAIL-01) using `useHydrated`, `isEmailAddressValid`, `emailAddress`.
- `Footer`: `year` is `hydrated ? new Date().getFullYear() : Number(import.meta.env.VITE_BUILD_YEAR)`; Contact column rendered when `available`: before hydration one empty `li` with `aria-hidden="true"`, `data-email-pending`, `data-testid="footer-email-pending"`, sized like `FooterLink` (`minH` `{ base: '44px', lg: 'auto' }` plus one text line from `lg`); after hydration the existing link (`footer-email-link`). Update the Dutch comment on the year and the email.
- `ContactDetails`: `contactChannels(email, socials, hydrated)`; for `email-pending` render an empty `li` with `aria-hidden`, `data-email-pending`, `data-testid="contact-details-email-pending"`, `minH="44px"`; keep returning `null` only when there are no channels at all (no social and `available` false). `iconOf`/key handling must cope with the new kind.
- `ContactFormGate`: per BR-MAIL-05: sentence "Het contactformulier komt binnenkort." alone before hydration; hidden (`visibility: hidden`, `aria-hidden`) inline block `n` characters wide (`n` from `user.length + 1 + domain.length` without assembling) where " Mail me voor nu op <address>" will come, and a hidden placeholder of the button using the same `linkButton` recipe and label, `data-testid="contact-gate-mail-pending"`, `data-email-pending`; `mb` depends on `available`; after hydration the existing link and `contact-gate-mail` button.
- `ContactForm`: use `useEmailAddress` instead of `emailAddress(email)`; the failed-state link unchanged otherwise. `shownAt` unchanged (BR-HYD-16).
- Update the call sites that Step 14 broke.
- Done when: `pnpm exec tsc --noEmit` clean; `pnpm lint` clean; `renderToString` of `Footer`, `ContactDetails`, `ContactFormGate` with the real `siteContent` contains no `@andreaslop.nl`/`info@` (quick manual check; the tests come in Step 21). Placeholder sizes are first estimates; they are measured in Steps 27 and 34 (V10).
- Record (2026-10-31): placeholder sizes are estimates, see V10 in the verification log. `src/test/hydrate.tsx` (new) is the shared hydration test helper. `useInView.ts` got a guard in the effect (see Step 19).
### Step 18: Testimonials in the HTML [x]
- Executor: Sonnet.
- Implements: BR-LZY-02; FR-PR-01; NFR-PR-S-02; V9 (code part).
- Files: `web/src/components/home/Testimonials/Testimonials.tsx`.
- Do: `CarouselPlaceholder` renders every visible testimonial as a `TestimonialSlide`: the longest in normal flow as today (it sets the height), the others in a wrapper that is visually hidden (use Chakra's visually hidden recipe/`srOnly`-style props used elsewhere in the repo), `aria-hidden="true"` and `inert`. Do not change the carousel itself, the single-review path, or `inView` logic. Update the comment.
- Done when: `pnpm exec tsc --noEmit` clean; `renderToString` of `Testimonials` with the real testimonials contains every quote text (manual check; test in Step 21).
### Step 19: Tests for hooks (hydration phases) [x]
- Executor: Sonnet.
- Implements: BR-HYD-02 to 05, 09; BR-TST-02; NFR-PR-Q-01; PBT: "No PBT properties identified" for hooks (business-logic-model.md § 9), example-based only.
- Files: new or extended `web/src/hooks/useHydrated.test.tsx`, `usePageLoaded.test.tsx`, `useInView.test.tsx` (new), `useReveal.test.tsx`, `web/src/components/Hero/useHeroSlider.test.tsx`.
- Do: for each hook test (a) `renderToString` (server snapshot value), (b) hydrating a server-rendered markup with `hydrateRoot` shows the server value in the hydrating render and the real value afterwards, (c) a plain `render` (client mount) shows the real value at once. Cases: `useHydrated` false/true; `usePageLoaded` false then `load` event; `useInView` without `IntersectionObserver` (true after hydration, `skip` respected) and with a fake observer (`src/test/fakeIntersectionObserver.ts`); `useReveal` first-render `reducedMotion` false; `useHeroSlider` `hidden` from `visibilitychange`. Keep all existing tests of these files.
- Done when: `pnpm exec vitest run src/hooks src/components/Hero` passes.
- Record (2026-10-31): found while testing: the effect of the hydrating render still sees `unsupported` false and threw `ReferenceError` without `IntersectionObserver`; `useInView.ts` now checks `typeof IntersectionObserver` in the effect too. No old test changed.
### Step 20: Tests for routes, navigation and not found [x]
- Executor: Sonnet.
- Implements: BR-HYD-10 to 13; BR-404-04, 05; FR-PR-06, 07, 15; NFR-PR-Q-01.
- Files: extend `web/src/app.test.tsx` or the route/contact/portfolio tests that exist, `web/src/components/NavigationBar/activeOptions.test.tsx`, a new `web/src/components/StatusPage/NotFound.test.tsx` if none exists. PBT: "No PBT properties identified" (markup with small fixed input).
- Do: direct load simulation (`renderApp('/contact?pakket=...')`) still preselects the package and tidies the address bar; `/?pakket=` still scrolls/focuses via the `ContactSection` effect; `/portfolio?shoot=gezin` filters and filter clicks still navigate with `replace`; `NotFound` shows one button while hydrating and the two extra buttons under `/soorten-fotoshoots/` after (use `hydrateRoot`), and on a plain mount at once; no navigation link is current on an unknown sub-path such as `/over-mij/x`, current on real pages and with a search.
- Done when: the touched test files pass with targeted `vitest run`.
### Step 21: Tests for Footer, e-mail components and Testimonials [x]
- Executor: Sonnet.
- Implements: BR-HYD-14; BR-MAIL-01 to 07; BR-LZY-02; FR-PR-22; V9 (test part); NFR-PR-Q-01.
- Files: `web/src/components/Footer/Footer.test.tsx`, `ContactDetails` test, `ContactFormGate`/`ContactForm` tests, `web/src/hooks/useEmailAddress.test.tsx` (new), `Testimonials` test. PBT: P14 and P15 live in Step 15; components: "No PBT properties identified".
- Do: `renderToString` output never contains the assembled address nor `mailto:` for each component with the real and with `validEmail` content; the three states (absent, pending, ready) per component incl. testids `footer-email-pending`, `contact-details-email-pending`, `contact-gate-mail-pending`; after `hydrateRoot` the link and `contact-gate-mail` button appear; year equals `VITE_BUILD_YEAR` while hydrating (stub the env) and the real year afterwards; all testimonial texts are in the server HTML and the hidden copies are `aria-hidden`; axe still passes (`src/test/axe.ts`) on the page containing the hidden slides.
- Done when: touched test files pass. Hand the batch to the merge point: **CP2** is reached when B2, B3 and B4 are all done and the main session (or the next executor) runs `pnpm exec tsc --noEmit`, `pnpm lint`, `pnpm test` (coverage thresholds) and `pnpm build`, all green. A failure at CP2 is fixed by the batch that owns the file; if unclear, STOP.
---
## Part E: Preview server (batch B4, Sonnet; parallel with B2 and B3)
### Step 22: `config/previewServer.ts` [x]
- Executor: Sonnet.
- Implements: BR-SRV-01 to 08; D10; NFR-PR-SEC-01; FR-PR-14 (preview part).
- Do: create `resolveRequest(path, fileExists)` per BR-SRV-01 to 07 (decode once; reject NUL, backslash, `..` segments; `/` to `index.html`; no-dot last segment through `pageFile` when the file exists; dot last segment is a file request; else `404.html` with status 404; trailing slash and `/404` interim behaviour exactly as BR-SRV-07 says, with a comment "final rule in unit 3 Infrastructure Design"; never returns `{ redirect }`). `startPreviewServer(clientDir, port)` with Node `http`: `GET`/`HEAD` only (405 otherwise), `securityHeaders('production')` on every response, `Cache-Control: no-cache` for HTML, content types from the extension, bind `127.0.0.1`, prints a line containing `Local` with the URL (matches `startServerReadyPattern` in `lighthouserc.cjs`), CLI entry parses `--port` (default 4173), `--strictPort` (fail if taken), and an optional `--dir` (default `dist/client`). Import `pageFile` from `./pageFiles.ts` (Step 7; if B2 has not finished, wait for it) and `securityHeaders` from `./securityHeaders.ts`. Dutch header comment explaining why a own server (D10: real 404 and `.html` mapping, no Node server in production).
- Done when: `pnpm exec tsc --noEmit` clean; starting it manually on the Step 4 output answers `curl -I http://127.0.0.1:4173/over-mij` with 200 and the CSP header, and `/nope` with 404 (stop the server afterwards; skip this check while Lighthouse is running anywhere).
### Step 23: Tests for the preview server (P16, P17) [x]
- Executor: Sonnet.
- Implements: PBT-03, 05, 07, 08, 10; P16, P17; SECURITY-11 misuse case.
- Files: `web/src/test/requestArbitraries.ts` (create), `web/config/previewServer.test.ts` (create).
- Do: generators for request paths including `..`, `%2e%2e`, `%00`, backslashes, unicode, double slashes, and for sets of existing files; examples per BR-SRV-02 to 06 and the interim cases of 07; P16 (invariant) and P17 (oracle) as in business-logic-model.md § 9; an HTTP-level test on an ephemeral port with a temp directory (headers on 200 and 404, 405 for `POST`, `HEAD` has no body, content type).
- Done when: `pnpm exec vitest run config/previewServer.test.ts` passes.
---
## Part F: Integration (batch B5; after CP2)
### Step 24: Wire the build, preview and configuration [x]
- Executor: Haiku.
- Implements: BR-BLD-01, 03, 04, 09, 10 (client path); BR-SRV-08; BR-SEC-01; CP3.
- Files: `web/package.json`, `web/vite.config.ts`, `web/tsconfig.json`, `web/eslint.config.js`, `web/.gitignore`.
- Do:
1. `package.json`: `"build": "tsc && vite build && node config/externalizeInlineScripts.ts"`; `"preview": "node config/previewServer.ts"`; `"e2e": "vitest run --config vitest.e2e.config.ts"` (config created in Step 26); `"check"`: insert `pnpm e2e` after `pnpm build`.
2. `vite.config.ts`: import `NOT_FOUND_PATH`/`NOT_FOUND_FILE` from `./config/pageFiles.ts` instead of the temporary constants of Step 4; add `'e2e/**'` to `test.exclude` (keep Vitest's default excludes: spread `configDefaults.exclude`).
3. `tsconfig.json`: add `e2e` and `vitest.e2e.config.ts` to `include`. `eslint.config.js`: add Node globals for `config/**/*.ts`, `e2e/**/*.ts`, `vitest.e2e.config.ts` (the file currently has browser globals only; use `globals.node` for those paths).
4. Run `pnpm build`.
5. Check that `pnpm lighthouse` still works against the new preview server on a fresh `dist/client` for one URL (`pnpm exec lhci collect --config=lighthouserc.cjs --numberOfRuns=1 --url=http://localhost:4173/over-mij`). Lighthouse audits for `/bestaat-niet` may fail, because the new preview server answers 404 and Lighthouse rejects non-2xx documents; verify with `--url=http://localhost:4173/bestaat-niet`. If it fails, set `notFoundPath` in `lighthouserc.cjs` to `/404.html` and adapt the test that guards that file. Under BR-SRV-04 that URL is a file request with status 200, so Lighthouse audits the same page and its assertions stay in force, while the real 404 status is covered by the e2e tests. This is the only `lighthouserc.cjs` edit in unit 1; targets stay as they are. Record the Lighthouse error as evidence in the log.
- Done when: **CP3**: `pnpm build` succeeds, the runner prints its success line (this requires Steps 17 and 21 done, otherwise EMAIL_IN_OUTPUT fails the build, which is the check working). Port 4173 and CPU rules of Step 2 apply to item 5.
- Record: verification log notes under V5, V7, and the lighthouse finding.
### Step 25: Prerender-safety test (BR-TST-07) [x]
- Executor: Sonnet.
- Implements: BR-TST-07; FR-PR-05; NFR-PR-Q-03 (fast feedback).
- Files: `web/src/prerender.test.tsx` (create, `// @vitest-environment node`).
- Do: for every key of `sitePages` plus an unknown path, create a router with memory history from `routerOptions()`, await `router.load()`, render with `react-dom/server` inside `ChakraProvider`, and expect no throw and a non-empty string containing the page's `<h1>`. This catches `window`/`document` use in render paths. If it cannot be made to work with the shell, drop the shell from the test as in Step 5. Feasibility is the open point: if the Chakra provider or the router cannot render in a Node environment at all, record "not feasible, the build's own prerender is the guard" in the verification log and replace the test by a documented skip-free alternative (a test that scans nothing is not acceptable): in that case STOP and report instead of deleting the step. Add the assertion that the server HTML of `/contact` has no assembled address.
- Done when: `pnpm exec vitest run src/prerender.test.tsx` passes.
### Step 26: e2e harness and smoke test [x]
- Executor: Sonnet.
- Implements: BR-TST-05 (harness); D11; NFR-PR-Q-03; V1 (browser side), V8 early.
- Files: `web/vitest.e2e.config.ts` (create), `web/e2e/support/server.ts` (create), `web/e2e/support/browser.ts` (create), `web/e2e/smoke.e2e.ts` (create).
- Do:
- `vitest.e2e.config.ts`: `environment: 'node'`, `include: ['e2e/**/*.e2e.ts']`, long `testTimeout` (60 s; the Pi is slow), a `globalSetup` that builds nothing (requires an existing `dist/client`; fail with a clear message if missing). No coverage.
- `support/server.ts`: starts `startPreviewServer` from `../../config/previewServer.ts` on an ephemeral port and returns `{ origin, close }`.
- `support/browser.ts`: launches Chromium with `playwright-core` using `executablePath: process.env.CHROME_PATH` when set, otherwise `channel: 'chrome'`; extra args from `LIGHTHOUSE_CHROME_FLAGS` (CI needs `--no-sandbox --disable-dev-shm-usage`); helper `openPage(url, { javaScript })` that collects `console` messages of type error/warning, `pageerror`, and `securitypolicyviolation` events (via `page.addInitScript`/`page.exposeFunction` registered before navigation); closes everything after each test.
- `smoke.e2e.ts`: `/` and `/contact` and `/onbekend`: page loads under the production CSP, the heading is visible, zero console errors/warnings and zero CSP violations. This is the first real-browser proof; if it fails with hydration or CSP errors, analyse; failures that need a design change: STOP.
- Done when: `pnpm build && pnpm e2e` passes locally (Chrome must be installed or `CHROME_PATH` set; if no browser is available on this machine, STOP and ask the main session instead of skipping).
### Step 27: Full e2e tests (BR-TST-05, BR-TST-06; V8, V9, V10, V11, V12, V14, V15, V16, V17) [x]
- Executor: Sonnet.
- Implements: BR-TST-05, 06; BR-HYD-17, 20, 21; BR-LZY-01, 05; BR-404-03, 04, 05, 07; BR-ENT-06; BR-MAIL-10; FR-PR-05 to 08, 14, 15, 22; NFR-PR-S-02, SEC-01, Q-03, Q-04; PBT: "No PBT properties identified" (browser flows).
- Files: `web/e2e/hydration.e2e.ts`, `web/e2e/rawHtml.e2e.ts`, `web/e2e/interaction.e2e.ts` (create).
- Do:
- `hydration.e2e.ts`: for the eleven pages, `/404`, `/onbekend`, `/soorten-fotoshoots/onbekend`, and the variants `/?pakket=gezin#contact`, `/contact?pakket=gezin`, `/portfolio?shoot=gezin`: zero console errors and warnings, zero `securitypolicyviolation`; for variants the search value is applied after hydration (package preselected, filter active, address bar tidied for pakket); `/` and the shoot pages show the same price text (V16); `404.html` served for `/soorten-fotoshoots/onbekend` shows the two extra buttons after hydration and one button before (check with JavaScript disabled for the "before" part); V12 and V8 (`/contact`: form fields in the HTML and no hydration error); record the V7-style check that `/Over-Mij` and `/over-mij/` behave as BR-404-07 describes (record the observed result in the log; this is an observation for unit 3, not an assertion that fails the suite).
- `rawHtml.e2e.ts` (no JavaScript, plain `fetch` of the preview server): BR-TST-06 for every `sitePages` path and `404.html`: `<title>` equal to `pageHead` title, exactly one `<h1>`, at least 40 visible characters in `main` outside the `h1`, a link to every `mainNav` and `footerNav` target, canonical URL, JSON-LD blocks present and parseable, no assembled address, no `data-fallback`, exactly one `<title>` and one `description` (V11), `404.html` with one `noindex` robots meta; testimonial quote texts in `/` (V9).
- `interaction.e2e.ts`: mobile menu opens and closes (`nav-menu-toggle`), one client-side navigation works, the e-mail link (`footer-email-link`) is absent in raw HTML and present after hydration, focus moves to `main` after a client navigation but not on first load (V14), the contact page's tidy navigation still ends at `/contact` without extra history entries (V14), `/?pakket=...#contact` scrolls to the contact section, JSON-LD blocks cause no CSP violation (BR-SCR-22), styles present in the raw HTML and a screenshot comparison with JavaScript disabled versus enabled for `/over-mij` at widths 390 and 1280 saved under the scratch folder and reviewed by you (V15: no visible jump; describe in the log).
- Done when: `pnpm build && pnpm e2e` passes; verification log rows V8, V9, V11, V12, V14, V15, V16, V17 filled with evidence. Failures that point to the design (for example V12 hydration error on the 404 page) are STOP cases.
### Step 28: CI changes [x]
- Executor: Haiku.
- Implements: BR-BLD-10; BR-TST-05 (CI run); NFR-PR-Q-03; V18. No deployment steps are touched or run.
- Files: `.gitea/workflows/continuous_integration.yaml`.
- Do:
1. Job `check`, step "Upload build artifact": `path: web/dist/client/` (artifact root then holds `index.html`; the deploy jobs keep downloading to `web/dist`).
2. Job `lighthouse`, step "Download build artifact": `path: web/dist/client` (the preview server and `pnpm e2e` read `dist/client`).
3. Job `lighthouse`: add a step "Browsertests" after "Install Chromium" and before "Lighthouse": env `LIGHTHOUSE_CHROME_FLAGS: '--no-sandbox --headless=new --disable-dev-shm-usage'`, run `pnpm e2e` (the `CHROME_PATH` env set by the Chromium step is read by the harness). Comment in Dutch like the file.
4. Leave `deploy-test` and `deploy-production` unchanged (upload order and server rules are unit 3).
5. Verify the layout locally: after `pnpm build`, `web/dist/client/index.html` exists and `web/dist/server` is not inside `dist/client`; emulate the deploy steps' `dist/*` copy on a scratch copy of `dist/client` to confirm `index.html` lands at the destination root (V18).
- Done when: **CP4**: `pnpm lint`, `pnpm format:check`, `pnpm test`, `pnpm build`, `pnpm e2e`, `pnpm audit:deps` all succeed in `web/`; the workflow file diff shows only the three edits above; V18 filled.
---
## Part G: Finish (batch B6)
### Step 29: Comments, documentation in code, naming review [x]
- Executor: Sonnet.
- Implements: BR-BLD-12 (code part); NFR-PR-Q-05.
- Do: review every new or changed file for header comments that say why (the strict CSP and Start's inline scripts for `inlineScripts.ts`, `externalizeInlineScripts.ts`, `previewServer.ts`; why `useHydrated` and the store pattern exist; why `ssr` defaults are used), comment language per neighbour, no leftover temporary constants, no `TODO` without owner, `data-testid` naming. Run `pnpm exec prettier --write` on touched files, then `pnpm lint` and `pnpm format:check`.
- Done when: lint and format checks are clean and a `git diff --stat` shows only files named in this plan (plus `pnpm-lock.yaml`, `src/routeTree.gen.ts`).
### Step 30: Dependency hygiene (BR-BLD-11, V6) [x]
- Executor: Haiku.
- Implements: BR-BLD-11; NFR-PR-SEC-02; V6 (second part).
- Do: find packages that are now unused (`@tanstack/router-plugin` if Start replaced it: `grep -rn "router-plugin" web --include=*.ts --include=*.json -l`; nothing else imports it) and ask the main session before removing anything whose use is not obvious; if it is clearly unused run `pnpm remove <name>` (this is the only install action allowed here). Check `pnpm-workspace.yaml` overrides are intact. Run `pnpm audit:deps` and `pnpm audit:dev`.
- Done when: audit passes, lockfile consistent (`pnpm install --frozen-lockfile` succeeds), V6 updated.
### Step 31: Unit build and test verification (Step 13.5) [x]
- Executor: Haiku.
- Implements: Code Generation Step 13.5; CP5; NFR-PR-Q-01.
- Do, in `web/`: `pnpm lint`, `pnpm format:check`, `pnpm test` (coverage thresholds), `pnpm build`, `pnpm e2e`, `pnpm audit:deps`. Note counts of test files and tests (expected: more than the Step 1 baseline), the fast-check seed, and whether any test is flaky (rerun a failing property test once with `FC_SEED=<seed>`; a failure that passes on a different seed is a real finding, report it, do not retry until green).
- Done when: everything is green, or the unresolved failure and its open question are written in the code summary (Step 32).
- Record: counts and outcomes go into the code summary.
### Step 32: Code summary [x]
- Executor: Sonnet.
- Do: write `aidlc-docs/features/prerendering/construction/start-migration/code/code-summary.md`: list of created/modified/removed files (from `git status --short` and `git diff --stat`), grouped by component group of components.md, with the rule ids each implements; test inventory (files, counts, which properties P1 to P17 where); the verification log (V1 to V18) condensed; the Step 31 outcome; deviations (should be none); what unit 2 and 3 can rely on (business-rules.md § 3); open points for the owner (including the preview and Lighthouse 404 finding of Step 24, and the BR-404-07 observation). Format like `aidlc-docs/features/shoot-type-pages/construction/content-and-seo-foundation/code/code-summary.md` (look at it).
- Done when: the file exists and every file of the diff is listed.
### Step 33: Shared reverse-engineering delta [x]
- Executor: Sonnet.
- Implements: NFR-PR-Q-05; team agreement (only this feature's lines are updated).
- Files: `aidlc-docs/_shared/reverse-engineering/code-structure.md`, `technology-stack.md`, `dependencies.md`, `architecture.md`, `component-inventory.md` (and others only where they name `main.tsx`, `index.html`, `vite preview` or the SPA fallback; use `grep` to find them).
- Do: minimal, line-level edits: entry (`src/client.tsx`, `src/router.tsx`, document shell in `__root.tsx`), build output (`dist/client`, prerendered HTML, `dist/server` not deployed), new `config/` files, new hooks and `src/routes/$.tsx`, `e2e/`, new dependencies, test setup (`renderApp`, `vitest.e2e.config.ts`), removal of `main.tsx` and `index.html`. Mark each edited line with the feature name in the style the files already use for earlier features (look at how the shoot-type-pages feature did it). Do not rewrite sections.
- Done when: `git diff -- aidlc-docs/_shared/reverse-engineering` shows only line-level edits for this feature.
### Step 34: Gate measurement (BR-MEA-02, 03, 04, 05; V10) [ ]
- Executor: Haiku for the runs, Sonnet for the report. Exclusive: same conditions as Step 2 (port 4173 free, no other CPU work, same machine, power plan and Node version).
- Implements: BR-MEA-02, 03, 04, 05; NFR-PR-P-03, P-04; NFR-PR-Q-04; V10 (final).
- Do:
1. Record `git status --short` to a scratch file (`status-before.txt`) and the SHA-256 of `web/src/hooks/useReveal.ts` (`status-before` and `useReveal.sha256`). Make a scratch copy of `useReveal.ts`.
2. **Measurement A (the unit as it is):** `pnpm build`; remove `.lighthouseci`; mobile `pnpm exec lhci collect --config=lighthouserc.cjs --numberOfRuns=3` and desktop with `lighthouserc.desktop.cjs`, collected to `<scratch>/after/mobile` and `<scratch>/after/desktop`, with the same URL list as Step 2, except for the not-found URL if Step 24 changed it to `/404.html` (say so in the report). Run the Step 2 script on both folders; compute gzip entry and all-JavaScript sizes of `dist/client` as in Step 2 (the entry JavaScript = scripts and modulepreload links referenced from `dist/client/index.html`, including the moved `inline-*.js` files, reported separately); count and gzip size of the moved script files per page (BR-MEA-03).
3. BR-MEA-03 timing: for `/` and `/over-mij` read from one mobile LHR the `network-requests` start/end of the moved `inline-*.js` files relative to FCP and LCP.
4. BR-MEA-04: CLS for `/` and `/contact` (mobile and desktop) must stay below 0.01. If not, report which placeholder (footer item, contact card item, gate notice) shifts and STOP the step; the fix belongs to Step 17 (resize), then repeat the measurement.
5. **Measurement B (BR-MEA-05, indication only):** temporarily change `web/src/hooks/useReveal.ts` so that `visible` is always true (return `visible: inView || true`, keeping `tsc` happy under `noUnusedLocals`). `pnpm build`; collect mobile and desktop to `<scratch>/revealvisible/...`; run the script. **Restore:** copy the scratch copy of `useReveal.ts` back, verify the SHA-256 equals the recorded one and `git status --short` equals `status-before.txt`; run `pnpm build` again so `dist` matches the committed state. Never run `git add`, `git stash` or `git commit` during this step; the temporary change must never be committed.
6. Report (Sonnet): `aidlc-docs/features/prerendering/construction/start-migration/code/measurement-gate.md` with side-by-side tables (baseline from Step 2, A, B per page, mobile and desktop), the gzip sizes, the moved-scripts table, the CLS result, the method, and a short neutral reading ("better", "worse", "equal" per metric; no recommendation to continue or stop: the owner decides, NFR-PR-P-03). Label B clearly as an indication with `Reveal` forced visible.
- Done when: the report exists, `git status --short` is identical to the state before item 5, `useReveal.ts` has the recorded checksum, `dist` was rebuilt from the real code.
---
## 4. Suggested logical commit boundaries (for the main session; commit only when the owner approves)
1. Docs: functional design, this plan, verification log and reports (aidlc-docs only).
2. Start setup: `package.json`, `pnpm-lock.yaml`, `vite.config.ts`, `config/sitemapPlugin.ts`, `src/router.tsx`, `src/client.tsx`, `src/routes/__root.tsx`, `src/routes/$.tsx`, `src/routeTree.gen.ts`, `.gitignore`, removal of `src/main.tsx` and `index.html`, `src/test/renderApp.tsx` (Steps 4, 5).
3. Hydration safety: hooks, routes, navigation, `NotFound`, `Footer`, e-mail components, `lib`, `Testimonials` with their tests (Steps 3, 14 to 21).
4. Script step: `config/pageFiles*`, `inlineScripts*`, `externalizeInlineScripts*`, `src/test/htmlArbitraries.ts` (Steps 7 to 13).
5. Preview server: `config/previewServer*`, `src/test/requestArbitraries.ts` (Steps 22, 23).
6. Build wiring and browser tests: `package.json` scripts, `tsconfig.json`, `eslint.config.js`, `vitest.e2e.config.ts`, `e2e/`, `src/prerender.test.tsx`, CI workflow (Steps 24 to 28).
7. Docs: code summary, reverse-engineering delta, measurement reports (Steps 29 to 34).
## 5. Open points for the main session (not plannable without a decision)
- **Lighthouse and the not-found URL (decided by the main session).** The unit changes the preview server to a real 404, and Lighthouse may refuse to audit a document with status 404. Step 24 checks it; if so, `notFoundPath` becomes `/404.html`, which keeps the page audited.
- **Start option names and the custom client entry** are not known without reading the installed package (Step 4 reads them); the plan avoids guessing them.
- **Whether `RouterProvider` renders `shellComponent` in jsdom** (V2) and **whether the Node render test is feasible** (Step 25) decide the exact shape of the test harness.
- **Placeholder sizes** (V10) are measured, not designed; Step 34 can send work back to Step 17.
- **BR-SCR-17 minimum** (one moved script per page) may need a design decision if Step 13 shows a reason to demand two.