refactor(ids): generate content id unions from the structure documents

scripts/generate-content-types.ts writes the gitignored src/types/content-ids.ts (id unions + project category values) from the four structure documents; wired as generate:ids / predev / prebuild / prepare. src/types/index.ts re-exports them type-only and keeps only the code-owned unions.

Edit mode now writes JSON only: the v4 union leg is deleted (saveIdUnions, diffIdsWithUnions, applyUnionChanges, readUnionBlock, the EditBar union card, edit.union.* labels). Validator rule 7 requires a label for every category a project uses, in both ui/projects.json documents.

Tests: smoke-draft.ts 11/11 (rename re-sluging + category-label rule replace checks 9-12); new scripts/smoke-generated-ids.ts 7/7. Verified: pnpm build (chunk names unchanged, no runtime reference to the generated module), lint with no new warnings, validate:content, resume HTML byte-identical before/after with identical documents.

Docs: spec-v5-generated-content-ids.md added; spec-v4-live-edit.md §3.1 marked superseded + §12 row 23; AGENTS.md and README.md updated.
This commit is contained in:
dong.nguyen committed 2026-10-24 13:16:18 +07:00
1 parent 1a1fc14d0e
commit a3662a9521
18 files changed
+731 -356

No files matched your search

+4
View File
@@ -29,3 +29,7 @@ dist-ssr
# secrets/site_config and the local .env carry site identity and the write token. # secrets/site_config and the local .env carry site identity and the write token.
.env .env
/secrets/ /secrets/
# Generated code (spec-v5): src/types/content-ids.ts is produced by
# scripts/generate-content-types.ts from src/data/*.json on predev/prebuild/prepare.
/src/types/content-ids.ts
+9 -3
View File
@@ -27,6 +27,7 @@ Personal engineering portfolio — multi-page SPA built with React + TypeScript
| `pnpm build:resume-all` | Generate bilingual resume PDFs (EN + VI) | | `pnpm build:resume-all` | Generate bilingual resume PDFs (EN + VI) |
| `pnpm lint` | Run Oxlint | | `pnpm lint` | Run Oxlint |
| `pnpm validate:content` | Validate the content dictionaries against the structure documents and the page manifests (also run by the loader at module load) | | `pnpm validate:content` | Validate the content dictionaries against the structure documents and the page manifests (also run by the loader at module load) |
| `pnpm generate:ids` | Regenerate `src/types/content-ids.ts` from the structure documents (also run by `predev` / `prebuild` / `prepare`) |
| `pnpm sitemap` | Regenerate `dist/sitemap.xml` + `dist/robots.txt` on its own (also run by `pnpm build`) | | `pnpm sitemap` | Regenerate `dist/sitemap.xml` + `dist/robots.txt` on its own (also run by `pnpm build`) |
| `pnpm preview` | Preview production build locally | | `pnpm preview` | Preview production build locally |
@@ -74,6 +75,7 @@ Content is split once, at authoring time, into language-neutral **structure docu
- `src/data/experience.json` + `experience.ts` loader — work history: id / location / logo / optional `variant: 'current' | 'gap'` (timeline decoration: live node / career break); company, duration, titles and responsibilities are text — the VI document carries localized dates ("11/2026 – nay") and company labels, en overrides with the originals, proper nouns identical per language - `src/data/experience.json` + `experience.ts` loader — work history: id / location / logo / optional `variant: 'current' | 'gap'` (timeline decoration: live node / career break); company, duration, titles and responsibilities are text — the VI document carries localized dates ("11/2026 – nay") and company labels, en overrides with the originals, proper nouns identical per language
- `src/data/projects.json` + `projects.ts` loader — cards: category / technologies / featured / `sections[].{id, type}`; titles, summaries, role, metrics and section prose are text (role follows the owner's EN title convention; metrics are localized) - `src/data/projects.json` + `projects.ts` loader — cards: category / technologies / featured / `sections[].{id, type}`; titles, summaries, role, metrics and section prose are text (role follows the owner's EN title convention; metrics are localized)
- `src/i18n/locales/{vi,en}/content/{profile,skills,experience,projects}.json` — all content text, one file per entity, keyed by the structure ids; the `profile` record is fixed-keyed (`name`, `title`, `bio`, `subtitle`, `tldr`, `tagline`, `currentInterests`, `roles`, `philosophyQuotes`, `philosophy.<id>.{title, description, keywords}`); `src/i18n/locales/{vi,en}/ui/{group}.json` — 14 chrome groups (`navigation`, `footer`, `social`, `hero`, `about`, `expertise`, `experience`, `projects`, `projectDetail`, `contact`, `philosophy`, `resume`, `edit`, `common`), in each language (nav group labels, Mode options, language names `langEn` / `langVi`, action labels, social `aria-label`s, the resume's section labels, edit-mode labels) — person text never lives here; `src/i18n/index.ts` merges both trees back into the same `UI`/`CONTENT` records and asserts the merge against the group lists — a group dropped in the split is a load-time error, never a silent omission - `src/i18n/locales/{vi,en}/content/{profile,skills,experience,projects}.json` — all content text, one file per entity, keyed by the structure ids; the `profile` record is fixed-keyed (`name`, `title`, `bio`, `subtitle`, `tldr`, `tagline`, `currentInterests`, `roles`, `philosophyQuotes`, `philosophy.<id>.{title, description, keywords}`); `src/i18n/locales/{vi,en}/ui/{group}.json` — 14 chrome groups (`navigation`, `footer`, `social`, `hero`, `about`, `expertise`, `experience`, `projects`, `projectDetail`, `contact`, `philosophy`, `resume`, `edit`, `common`), in each language (nav group labels, Mode options, language names `langEn` / `langVi`, action labels, social `aria-label`s, the resume's section labels, edit-mode labels) — person text never lives here; `src/i18n/index.ts` merges both trees back into the same `UI`/`CONTENT` records and asserts the merge against the group lists — a group dropped in the split is a load-time error, never a silent omission
- Content ids and the category values a project uses are **generated**, never hand-maintained (spec: `docs/design/specs/v5/spec-v5-generated-content-ids.md`): `scripts/generate-content-types.ts` reads the four structure documents and writes `src/types/content-ids.ts` (gitignored) under `predev` / `prebuild` / `prepare`; `src/types/index.ts` re-exports those unions type-only and keeps only the code-owned ones (`Language`, `Palette`, `SocialId`, `PageId`, manifest types). A content add or delete touches JSON only — a text entry left behind by a deleted record is a `tsc` error (`TS2741`), never a stale union member — and a category with no label in either language is a validator error naming both `ui/projects.json` files (rule 7)
- `src/data/pages/{home,about,experience,projects,project-detail,contact,philosophy,resume}.json` + `pages.ts` loader — per-route manifests: which entity fields the page renders (`fields[]`; `*` = every field the record id owns) and which UI groups it reads; `src/types/index.ts` carries `PageId` / `PageManifestClaim` / `PageManifest`. The validator enforces: no unknown entity, no unknown UI group, no unresolvable field path, **no orphan text field** (every text leaf in the content documents is claimed by at least one manifest), no missing manifest for a route in `src/data/navigation.ts` plus `/projects/:id` - `src/data/pages/{home,about,experience,projects,project-detail,contact,philosophy,resume}.json` + `pages.ts` loader — per-route manifests: which entity fields the page renders (`fields[]`; `*` = every field the record id owns) and which UI groups it reads; `src/types/index.ts` carries `PageId` / `PageManifestClaim` / `PageManifest`. The validator enforces: no unknown entity, no unknown UI group, no unresolvable field path, **no orphan text field** (every text leaf in the content documents is claimed by at least one manifest), no missing manifest for a route in `src/data/navigation.ts` plus `/projects/:id`
- `src/i18n/index.ts` — load + validate + join ONCE at module load; exports `UI` and `CONTENT` as `Record<Language, Resolved…>`; `src/i18n/dict-types.ts` carries the document types; `src/i18n/validate.ts` + `scripts/validate-content.ts` enforce the cross-document rules (orphan or missing keys, HTML markup in text values, the manifest rules above) — a malformed document fails `pnpm build`, CI, and the browser load, never a silent half-render - `src/i18n/index.ts` — load + validate + join ONCE at module load; exports `UI` and `CONTENT` as `Record<Language, Resolved…>`; `src/i18n/dict-types.ts` carries the document types; `src/i18n/validate.ts` + `scripts/validate-content.ts` enforce the cross-document rules (orphan or missing keys, HTML markup in text values, the manifest rules above) — a malformed document fails `pnpm build`, CI, and the browser load, never a silent half-render
- `src/i18n/provider.tsx` — `I18nProvider` wraps the app; components consume `const { ui: s, content: c } = useI18n()`: `s` is the chrome of the current language, `c` the joined records (`c.profile`, `c.skillGroups`, `c.experiences`, `c.projects`). There is no `field()` and no `*En` field pair anymore - `src/i18n/provider.tsx` — `I18nProvider` wraps the app; components consume `const { ui: s, content: c } = useI18n()`: `s` is the chrome of the current language, `c` the joined records (`c.profile`, `c.skillGroups`, `c.experiences`, `c.projects`). There is no `field()` and no `*En` field pair anymore
@@ -88,7 +90,7 @@ Content is split once, at authoring time, into language-neutral **structure docu
- Entry: any route with `?edit` — `MaybeEditMode` in `App.tsx` lazy-mounts `EditModeShell` (its own chunk; visitors never load edit code). The shell authenticates, fetches the live master documents through the proxy, and re-wraps the tree in an `I18nProvider` override — the seven routes ARE the preview - Entry: any route with `?edit` — `MaybeEditMode` in `App.tsx` lazy-mounts `EditModeShell` (its own chunk; visitors never load edit code). The shell authenticates, fetches the live master documents through the proxy, and re-wraps the tree in an `I18nProvider` override — the seven routes ARE the preview
- Target branch (spec D10): `?edit=<branch>` reads (`?ref=`) and writes (`branch` in the PUT body) that branch; a bare `?edit` resumes the session's last branch, default `master`. Names are validated against git ref rules in `src/i18n/edit-mode.ts` before any request (illegal → exit like a failed auth); the branch is stored beside the session flag. The target branch must already exist — Contents API updates never create branches. Only `master` deploys, so the EditBar shows a merge hint on other branches - Target branch (spec D10): `?edit=<branch>` reads (`?ref=`) and writes (`branch` in the PUT body) that branch; a bare `?edit` resumes the session's last branch, default `master`. Names are validated against git ref rules in `src/i18n/edit-mode.ts` before any request (illegal → exit like a failed auth); the branch is stored beside the session flag. The target branch must already exist — Contents API updates never create branches. Only `master` deploys, so the EditBar shows a merge hint on other branches
- Auth: HTTP Basic at the nginx `/api/content/` proxy is the security boundary; `src/i18n/edit-mode.ts` probes it through a hidden iframe, keeps the session flag `portfolio-edit` in sessionStorage, and strips `?edit` when the probe fails (401 or cancelled prompt → normal visitor site) - Auth: HTTP Basic at the nginx `/api/content/` proxy is the security boundary; `src/i18n/edit-mode.ts` probes it through a hidden iframe, keeps the session flag `portfolio-edit` in sessionStorage, and strips `?edit` when the probe fails (401 or cancelled prompt → normal visitor site)
- `src/i18n/draft.ts` — `DraftStore`: baselines (`data` + blob `sha`) of the 12 writable documents (4 structure + 8 text), copy-on-write draft, leaf-path diff, cross-document validation on every accepted edit, three-way rebase on save conflicts (Gitea 28 reports a blob-sha mismatch as 422 with a "does not match" message; older deployments answered 412 — both are handled; origin / base / working kept separate), draft persisted to sessionStorage `portfolio-draft`, sequential-PUT save (one commit per touched document, resume from the first unwritten one on failure), and **balancing** id union members in `src/types/index.ts` after their documents land — appending the ids a new record introduces and removing the ids a deleted record leaves behind, because a stale member makes `Record<SkillGroupId, SkillGroupText>` reject the shortened text document and the build fails (`TS2741`) - `src/i18n/draft.ts` — `DraftStore`: baselines (`data` + blob `sha`) of the 12 writable documents (4 structure + 8 text), copy-on-write draft, leaf-path diff, cross-document validation on every accepted edit, three-way rebase on save conflicts (Gitea 28 reports a blob-sha mismatch as 422 with a "does not match" message; older deployments answered 412 — both are handled; origin / base / working kept separate), draft persisted to sessionStorage `portfolio-draft`, sequential-PUT save (one commit per touched document, resume from the first unwritten one on failure). Edit mode writes JSON only: the id-union leg was deleted when spec-v5 made the unions generated, and the store is handed the branch's category labels (read-only `ui/projects.json` fetches) for rule 7 — `null` when they cannot be read, in which case the rule is skipped and the EditBar says so
- `src/components/ui/EditableText.tsx` — the site's own element (`as` = the tag or motion component it renders today) becomes the inline editor only in edit mode; commit on blur only (Vietnamese IME-safe), Esc cancels, Enter commits single-line fields, paste is plain-text, empty required values are rejected at commit; without an `EditContext` provider it renders byte-identical markup to the plain element - `src/components/ui/EditableText.tsx` — the site's own element (`as` = the tag or motion component it renders today) becomes the inline editor only in edit mode; commit on blur only (Vietnamese IME-safe), Esc cancels, Enter commits single-line fields, paste is plain-text, empty required values are rejected at commit; without an `EditContext` provider it renders byte-identical markup to the plain element
- `src/components/layout/EditBar.tsx` — fixed save bar: per-path diff with revert and "appears on" page annotations (computed from the page manifests via `manifestsClaiming`, never from component code), conflict resolution (rebase / take-theirs / per-field keep-mine–keep-theirs), per-document save status, partial-save resume, exit confirm - `src/components/layout/EditBar.tsx` — fixed save bar: per-path diff with revert and "appears on" page annotations (computed from the page manifests via `manifestsClaiming`, never from component code), conflict resolution (rebase / take-theirs / per-field keep-mine–keep-theirs), per-document save status, partial-save resume, exit confirm
- Editable surface: content text inline (pencil-triggered, click never edits) **and** structure — chip-level tag editors (technologies, categories, interests, roles, keywords, tagline emphasis), ghost add/delete/move on every record surface, per-record settings popover (`featured`, project section list + type picker, `variant`, location, logo), ids auto-generated from title slugs, social links handle-only with URLs derived in the loaders. Implemented 2026-10-23 (`spec-v4-inline-editing.md` + `spec-v4-data-organization.md`); the JSON panel is deleted. UI documents stay read-only in v4. Field provenance: hovering any pencil shows `document → pointer` (`describeField()` names the per-entity file automatically); the EditBar diff line and a `validate:content` error for the same field read identically - Editable surface: content text inline (pencil-triggered, click never edits) **and** structure — chip-level tag editors (technologies, categories, interests, roles, keywords, tagline emphasis), ghost add/delete/move on every record surface, per-record settings popover (`featured`, project section list + type picker, `variant`, location, logo), ids auto-generated from title slugs, social links handle-only with URLs derived in the loaders. Implemented 2026-10-23 (`spec-v4-inline-editing.md` + `spec-v4-data-organization.md`); the JSON panel is deleted. UI documents stay read-only in v4. Field provenance: hovering any pencil shows `document → pointer` (`describeField()` names the per-entity file automatically); the EditBar diff line and a `validate:content` error for the same field read identically
@@ -107,7 +109,7 @@ src/
i18n/ — index.ts (loader), dict-types.ts, validate.ts, provider.tsx, draft.ts (DraftStore + save pipeline), edit-mode.ts (session/auth), locales/{vi,en}/content/{profile,skills,experience,projects}.json + ui/{group}.json (14 chrome groups) i18n/ — index.ts (loader), dict-types.ts, validate.ts, provider.tsx, draft.ts (DraftStore + save pipeline), edit-mode.ts (session/auth), locales/{vi,en}/content/{profile,skills,experience,projects}.json + ui/{group}.json (14 chrome groups)
hooks/ — useTheme.tsx, useLanguage.tsx, useClickOutside.ts, useResumeDialog.ts, useEdit.ts (edit context) hooks/ — useTheme.tsx, useLanguage.tsx, useClickOutside.ts, useResumeDialog.ts, useEdit.ts (edit context)
pages/ — HomePage, AboutPage, ExperiencePage, ProjectsListPage, ProjectDetailPage, PhilosophyPage, ContactPage pages/ — HomePage, AboutPage, ExperiencePage, ProjectsListPage, ProjectDetailPage, PhilosophyPage, ContactPage
types/ — shared TypeScript interfaces types/ — shared TypeScript interfaces; content-ids.ts (generated id unions, gitignored)
``` ```
## Motion & Animation ## Motion & Animation
@@ -134,7 +136,9 @@ src/
## Scripts ## Scripts
- `scripts/generate-resume.ts` — Playwright-based PDF resume generator (bilingual en/vi) - `scripts/generate-resume.ts` — Playwright-based PDF resume generator (bilingual en/vi)
- `scripts/smoke-draft.ts` — regression check of the draft-store semantics (`pnpm tsx scripts/smoke-draft.ts`): accept/reject paths, empty-required rejection, orphan-free record delete, template creation, snapshot round-trip, conflict detection, clean rebase - `scripts/generate-content-types.ts` — writes `src/types/content-ids.ts` from the four structure documents (`pnpm generate:ids`, wired as `predev` / `prebuild` / `prepare`): the id unions and the project category values in document order, `never` for an emptied document, a duplicate id refused with the file named
- `scripts/smoke-draft.ts` — regression check of the draft-store semantics (`pnpm tsx scripts/smoke-draft.ts`): accept/reject paths, empty-required rejection, orphan-free record delete, template creation, id re-sluging on rename, snapshot round-trip, conflict detection, clean rebase, the category-label rule
- `scripts/smoke-generated-ids.ts` — regression check of the generator (`pnpm tsx scripts/smoke-generated-ids.ts`): the shipped module equals the shipped documents, byte-stable output, `never` for emptied documents, malformed documents refused with the file named
## Deployment ## Deployment
@@ -182,6 +186,7 @@ compose.override.yaml
5. **Content text lives only in the locale dictionaries:** components read joined records through `useI18n()`; a missing EN field falls back to VI per field at load (arrays are atomic). Most EN content is still the VI original — translating means adding JSON, never touching components 5. **Content text lives only in the locale dictionaries:** components read joined records through `useI18n()`; a missing EN field falls back to VI per field at load (arrays are atomic). Most EN content is still the VI original — translating means adding JSON, never touching components
6. **`lazy()` needs a default export:** pages export named components, so each factory must map `{ default: m.XPage }` — a bare `import('@/pages/XPage')` fails `tsc` with `TS2322: Property 'default' is missing`. There is no `src/pages/index.ts` barrel: importing it would pull every route back into the entry chunk 6. **`lazy()` needs a default export:** pages export named components, so each factory must map `{ default: m.XPage }` — a bare `import('@/pages/XPage')` fails `tsc` with `TS2322: Property 'default' is missing`. There is no `src/pages/index.ts` barrel: importing it would pull every route back into the entry chunk
7. **A locked `dist/resume*.pdf` blocks the build:** while a generated PDF is open in a viewer, `pnpm build:resume-all` fails with `EBUSY` on that file and `pnpm build` fails too (vite `emptyDir` → `EPERM`). Close the viewer first 7. **A locked `dist/resume*.pdf` blocks the build:** while a generated PDF is open in a viewer, `pnpm build:resume-all` fails with `EBUSY` on that file and `pnpm build` fails too (vite `emptyDir` → `EPERM`). Close the viewer first
8. **`src/types/content-ids.ts` is generated, not committed:** a fresh checkout has no id unions until a script writes them. `pnpm install` (`prepare`) or `pnpm dev` (`predev`) creates it; before that the IDE reports `Cannot find module './content-ids'`, and `pnpm generate:ids` is the one-off fix. Editing it by hand is pointless — the next `prebuild` overwrites it
## Design Specs ## Design Specs
@@ -196,6 +201,7 @@ All specification documents are in `docs/design/`:
| `specs/v2/spec-v2-*.md` | v2 feature specs (resume, seo, blog, analytics, testing, cicd) | | `specs/v2/spec-v2-*.md` | v2 feature specs (resume, seo, blog, analytics, testing, cicd) |
| `specs/v3/spec-v3-*.md` | v3 feature specs (theme colors, theme switch, theme palette switch, palette reference, UI enhancements, mobile navigation, nav & CTA enhancements, nav swatch & hamburger, typography, i18n, resume improvements, resume redesign, review fixes) | | `specs/v3/spec-v3-*.md` | v3 feature specs (theme colors, theme switch, theme palette switch, palette reference, UI enhancements, mobile navigation, nav & CTA enhancements, nav swatch & hamburger, typography, i18n, resume improvements, resume redesign, review fixes) |
| `specs/v4/spec-v4-*.md` | v4 feature specs (i18n locale overlay, git-backed live edit with preview, authenticated Contents-API write path; supersedes v3-i18n Phase 2). `spec-v4-data-organization.md`: per-entity content files, per-page field-level manifests, per-feature-group UI — implemented 2026-10-23 (automated checks pass; browser walkthrough pending). `spec-v4-inline-editing.md`: edit everything on the page (pencil-icon triggers, tag chips, record add/delete/move, settings popover), JSON panel deleted — implemented 2026-10-23; it supersedes live-edit §5.1/§5.4 panel scope. `spec-v4-deploy-infra.md`: pipeline redeploy of the VPS nginx container, Dockge-managed stack (paths-filtered `deploy-infra.yml`, test-before-touch, repo-as-source-of-truth, token-safety rules) + externalizing site identity — `SITE_URL` / `SITE_NAME` as CI Actions variables, `GITEA_TOKEN` + `GITEA_CONTENTS_API` in the stack's single config file `secrets/site_config` — repo side implemented 2026-10-23 (`deploy-infra.yml`, `compose.yaml` secret + entrypoint override, env-driven identity); owner-side variables/config file + first verified run pending | | `specs/v4/spec-v4-*.md` | v4 feature specs (i18n locale overlay, git-backed live edit with preview, authenticated Contents-API write path; supersedes v3-i18n Phase 2). `spec-v4-data-organization.md`: per-entity content files, per-page field-level manifests, per-feature-group UI — implemented 2026-10-23 (automated checks pass; browser walkthrough pending). `spec-v4-inline-editing.md`: edit everything on the page (pencil-icon triggers, tag chips, record add/delete/move, settings popover), JSON panel deleted — implemented 2026-10-23; it supersedes live-edit §5.1/§5.4 panel scope. `spec-v4-deploy-infra.md`: pipeline redeploy of the VPS nginx container, Dockge-managed stack (paths-filtered `deploy-infra.yml`, test-before-touch, repo-as-source-of-truth, token-safety rules) + externalizing site identity — `SITE_URL` / `SITE_NAME` as CI Actions variables, `GITEA_TOKEN` + `GITEA_CONTENTS_API` in the stack's single config file `secrets/site_config` — repo side implemented 2026-10-23 (`deploy-infra.yml`, `compose.yaml` secret + entrypoint override, env-driven identity); owner-side variables/config file + first verified run pending |
| `specs/v5/spec-v5-*.md` | v5 feature specs. `spec-v5-generated-content-ids.md`: the content id unions and the project category values are generated from the structure documents (`scripts/generate-content-types.ts`, run by `predev` / `prebuild` / `prepare`), edit mode writes JSON only, validator rule 7 requires a label for every used category in both languages — implemented 2026-10-24; it supersedes the id-union legs of `spec-v4-live-edit.md` §3.1 |
Read `spec.md` first for product context. Read `spec-v2.md` for current feature scope. Read `spec.md` first for product context. Read `spec-v2.md` for current feature scope.
+3
View File
@@ -59,9 +59,12 @@ Edit mode: open any route with `?edit` (or `?edit=<branch>` to read and write a
| `pnpm build:resume-all` | generate both resume PDFs (EN + VI) | | `pnpm build:resume-all` | generate both resume PDFs (EN + VI) |
| `pnpm build:resume-preview` | render the resume HTML preview without writing a PDF | | `pnpm build:resume-preview` | render the resume HTML preview without writing a PDF |
| `pnpm sitemap` | regenerate `dist/sitemap.xml` + `dist/robots.txt` on its own | | `pnpm sitemap` | regenerate `dist/sitemap.xml` + `dist/robots.txt` on its own |
| `pnpm generate:ids` | regenerate `src/types/content-ids.ts` from `src/data/*.json` (also runs as `predev` / `prebuild` / `prepare`) |
Content validation is a hard gate: a malformed document fails `pnpm build`, CI, and the browser load — never a silent half-render. Content validation is a hard gate: a malformed document fails `pnpm build`, CI, and the browser load — never a silent half-render.
Content ids are generated the same way: `src/types/content-ids.ts` is written from the structure documents and is gitignored, so adding or deleting a content record touches JSON only — never a TypeScript file. A fresh checkout gets it from `pnpm install`; `pnpm generate:ids` regenerates it on its own.
Gotcha: while a generated `dist/resume*.pdf` is open in a viewer, `pnpm build:resume-all` fails with `EBUSY` and `pnpm build` fails too (vite `emptyDir` → `EPERM`). Close the viewer first. Gotcha: while a generated `dist/resume*.pdf` is open in a viewer, `pnpm build:resume-all` fails with `EBUSY` and `pnpm build` fails too (vite `emptyDir` → `EPERM`). Close the viewer first.
### 5. Run the production stack locally (optional) ### 5. Run the production stack locally (optional)
+3 -1
View File
@@ -114,6 +114,7 @@ scripts/
``` ```
### 3.1 Stable id unions (`src/types/index.ts`) ### 3.1 Stable id unions (`src/types/index.ts`)
> **Superseded 2026-10-24 by [`spec-v5-generated-content-ids.md`](../v5/spec-v5-generated-content-ids.md).** The unions this section hand-maintains are now *generated* from the structure documents by `scripts/generate-content-types.ts` (run by `predev` / `prebuild` / `prepare`) into the gitignored `src/types/content-ids.ts`. What is gone: the union leg of the 3-edit recipe at the end of this section, and the whole balancing machinery written for row 23 — `saveIdUnions`, `diffIdsWithUnions`, `applyUnionChanges`, `unionNote`, `unionError`, `UnionLogEntry`, `onUnionsSaved`, the `EditBar` union card, and the `edit.union.*` labels. A content add or delete now touches JSON only. What still holds and is restated in v5 §2–§3: ids are slugs of the title, `SectionId` is deliberately not a union, `PhilosophyId` is a value list in `profile.json`, and a delete that leaves its text behind is an error the build catches. Everything else in this document — preview, save pipeline, conflicts, branch targeting — is unchanged.
Text dictionaries are only type-safe against closed id unions: Text dictionaries are only type-safe against closed id unions:
@@ -602,4 +603,5 @@ Deferred (not v4):
| 19 | Localize the §4 structure-assigned strings (`experience.company` of non-company entries, `duration`, `currentInterests`, `roles`, `keywords`, `projects.role`/`metrics`) or keep them EN-only like `technologies` | post-v4 | ✅ Done 2026-10-22 (automated) — fields moved to the text documents (§4 follow-up); VI document carries localized values (numeric dates + "nay", "Sẵn sàng cho cơ hội mới", "Nghỉ giữa chặng", "Đã triển khai tại 16 sortations", "Xử lý 70.000 ảnh/tháng"), en overrides with the originals, proper nouns and term lists identical (en omits); company/duration/role inline-editable, tag arrays JSON-panel-only; templates in `draft.ts` and JsonPanel hints follow the new shapes; resume generator reads `profile.tldr` from content. Verified: `pnpm build`, `pnpm validate:content`, `pnpm lint` (no new warnings), `pnpm build:resume-all` (both PDFs), SSR smoke marker sets per language incl. localized durations/companies/metrics/roles on home + `/experience` + project detail — deleted after the run. ⬜ Browser: VI pages show the localized timeline; `?edit` company/duration/role | | 19 | Localize the §4 structure-assigned strings (`experience.company` of non-company entries, `duration`, `currentInterests`, `roles`, `keywords`, `projects.role`/`metrics`) or keep them EN-only like `technologies` | post-v4 | ✅ Done 2026-10-22 (automated) — fields moved to the text documents (§4 follow-up); VI document carries localized values (numeric dates + "nay", "Sẵn sàng cho cơ hội mới", "Nghỉ giữa chặng", "Đã triển khai tại 16 sortations", "Xử lý 70.000 ảnh/tháng"), en overrides with the originals, proper nouns and term lists identical (en omits); company/duration/role inline-editable, tag arrays JSON-panel-only; templates in `draft.ts` and JsonPanel hints follow the new shapes; resume generator reads `profile.tldr` from content. Verified: `pnpm build`, `pnpm validate:content`, `pnpm lint` (no new warnings), `pnpm build:resume-all` (both PDFs), SSR smoke marker sets per language incl. localized durations/companies/metrics/roles on home + `/experience` + project detail — deleted after the run. ⬜ Browser: VI pages show the localized timeline; `?edit` company/duration/role |
| 20 | Save pipeline adapted to the live Gitea 28 Contents API | 3 | ✅ Done 2026-10-23 — the first real save answered 422 "repository file already exists [path: src/i18n/locales/vi/content.json]": Gitea 28 decides create-vs-update by the body `sha` (blob ID), which the client never sent. `draft.ts`: `fetchDoc`/`fetchTextFile` keep the blob `sha`; PUT bodies send `sha`; the new blob sha is read from the FileResponse `content.sha`; save conflict detection = 422 with a "does not match" message (412 kept for older deployments); §6.1 amended. Verified: `tsc -b`, `pnpm lint` (no new warnings), `scripts/smoke-draft.ts` 8/8. ⬜ Browser + Gitea: save → commit lands on the target branch; stale blob sha → conflict flow | | 20 | Save pipeline adapted to the live Gitea 28 Contents API | 3 | ✅ Done 2026-10-23 — the first real save answered 422 "repository file already exists [path: src/i18n/locales/vi/content.json]": Gitea 28 decides create-vs-update by the body `sha` (blob ID), which the client never sent. `draft.ts`: `fetchDoc`/`fetchTextFile` keep the blob `sha`; PUT bodies send `sha`; the new blob sha is read from the FileResponse `content.sha`; save conflict detection = 422 with a "does not match" message (412 kept for older deployments); §6.1 amended. Verified: `tsc -b`, `pnpm lint` (no new warnings), `scripts/smoke-draft.ts` 8/8. ⬜ Browser + Gitea: save → commit lands on the target branch; stale blob sha → conflict flow |
| 21 | v4 cutover: `spec-v4-inline-editing.md` E1–E7 (pencil-trigger inline editing, chip tag editors, ghost record add/delete/move, settings popovers, auto-ids, handle-only socials, `JsonPanel.tsx` deleted) + `spec-v4-data-organization.md` (content per entity, UI in 14 groups, per-route manifests + validator rules 1–4, 12-document draft registry, EditBar "appears on" annotations) | post-v4 | ✅ Done 2026-10-23 (automated) — details and evidence in each spec's Progress Tracking: the split is gated against baseline dumps (merged `CONTENT` byte-identical both languages; `UI` differs only by the intentional label changes), the manifest validator rejects all five bad cases (unknown entity / field path / orphan field / ui group / missing manifest), `smoke-draft.ts` 8/8 on the new registry, `tsc -b`, `pnpm build`, `pnpm lint` (no new warnings), `pnpm build:resume-all` all pass. ⬜ Browser: edit-mode walkthrough (pencil-only editing, provenance chips, save → per-file commits with page annotations) + visitor routes unchanged; the Gitea content repository must carry the new file layout before saves answer 200 (row 11 dependency) | | 21 | v4 cutover: `spec-v4-inline-editing.md` E1–E7 (pencil-trigger inline editing, chip tag editors, ghost record add/delete/move, settings popovers, auto-ids, handle-only socials, `JsonPanel.tsx` deleted) + `spec-v4-data-organization.md` (content per entity, UI in 14 groups, per-route manifests + validator rules 1–4, 12-document draft registry, EditBar "appears on" annotations) | post-v4 | ✅ Done 2026-10-23 (automated) — details and evidence in each spec's Progress Tracking: the split is gated against baseline dumps (merged `CONTENT` byte-identical both languages; `UI` differs only by the intentional label changes), the manifest validator rejects all five bad cases (unknown entity / field path / orphan field / ui group / missing manifest), `smoke-draft.ts` 8/8 on the new registry, `tsc -b`, `pnpm build`, `pnpm lint` (no new warnings), `pnpm build:resume-all` all pass. ⬜ Browser: edit-mode walkthrough (pencil-only editing, provenance chips, save → per-file commits with page annotations) + visitor routes unchanged; the Gitea content repository must carry the new file layout before saves answer 200 (row 11 dependency) |
| 22 | Union balance on delete: a record removed in edit mode prunes its id out of `src/types/index.ts` (the `TS2741` after the `logistics-technology` skill group was deleted) | 3 | ✅ Done 2026-10-24 (automated) — `draft.ts`: `readUnionBlock` reads a union as its exact declaration span (CRLF- and LF-safe, `never` round-trips), `diffIdsWithUnions` reports missing **and** stale members against `committedStructures()`, `applyUnionChanges` rewrites only that member list (survivors keep their order), one PUT with the message `content: update id union members (+id, -id)`; `newIdsInCommitted` / `patchUnionSource` deleted; `types/index.ts` `SkillGroupId` no longer lists `logistics-technology`; `ui/edit.json` `unionNote` reworded for both directions. Verified: `pnpm tsx scripts/smoke-draft.ts` 12/12 — new checks 9–12 (shipped documents ↔ shipped unions agree, a delete prunes exactly one line, an id colliding with a `PageId` member is still appended, `never` round-trip), `pnpm validate:content`, `pnpm lint` (no new warnings), `pnpm build`. ⬜ Browser + Gitea: delete a record in edit mode → the union commit lands on the target branch and CI builds | | 22 | Union balance on delete: a record removed in edit mode prunes its id out of `src/types/index.ts` (the `TS2741` after the `logistics-technology` skill group was deleted) | 3 | ✅ Done 2026-10-24 (automated) — `draft.ts`: `readUnionBlock` reads a union as its exact declaration span (CRLF- and LF-safe, `never` round-trips), `diffIdsWithUnions` reports missing **and** stale members against `committedStructures()`, `applyUnionChanges` rewrites only that member list (survivors keep their order), one PUT with the message `content: update id union members (+id, -id)`; `newIdsInCommitted` / `patchUnionSource` deleted; `types/index.ts` `SkillGroupId` no longer lists `logistics-technology`; `ui/edit.json` `unionNote` reworded for both directions. Verified: `pnpm tsx scripts/smoke-draft.ts` 12/12 — new checks 9–12 (shipped documents ↔ shipped unions agree, a delete prunes exactly one line, an id colliding with a `PageId` member is still appended, `never` round-trip), `pnpm validate:content`, `pnpm lint` (no new warnings), `pnpm build`. **Superseded the same day by row 23**: the whole union leg — `saveIdUnions`, `diffIdsWithUnions`, `applyUnionChanges`, `unionNote`, `unionError`, `UnionLogEntry`, `onUnionsSaved` — was deleted with spec-v5; the `TS2741` it fixed is now prevented by regenerating the unions, and the delete case is covered by `smoke-generated-ids.ts` + the `tsc` re-check |
| 23 | Generated content ids ([`spec-v5-generated-content-ids.md`](../v5/spec-v5-generated-content-ids.md)): the id unions and the project category values are written from the structure documents by `scripts/generate-content-types.ts` (`predev` / `prebuild` / `prepare`), edit mode writes JSON only, validator rule 7 requires a label for every used category in both languages | 3 | ✅ Done 2026-10-24 (automated) — `scripts/generate-content-types.ts` + `generate:ids` / `predev` / `prebuild` / `prepare`, gitignored `src/types/content-ids.ts`, `src/types/index.ts` re-exports it type-only; row 22's machinery deleted (`draft.ts`, `EditModeShell.tsx`, `EditBar.tsx`, both `ui/edit.json`); rule 7 implemented and wired through the draft store, EditBar, `RecordSettings`, `TagListEditor`. Verified: `pnpm generate:ids` (777-byte module, byte-stable on a second run), `pnpm build` (10 chunks, names identical to a build of the same documents before the change, no runtime reference to the generated module), `pnpm validate:content`, `pnpm lint` (no new warnings), `pnpm tsx scripts/smoke-draft.ts` 11/11, `pnpm tsx scripts/smoke-generated-ids.ts` 7/7, `pnpm build:resume-all` (both PDFs; the rendered HTML byte-identical before/after with identical documents). ⬜ Browser: visitor routes unchanged, `?edit` add/delete round-trip with no union card, category-rejection banner |
@@ -0,0 +1,250 @@
# Specification — v5: Generated Content Ids
> **Parent:** `specs/v4/spec-v4-live-edit.md` §3.1 (supersedes its id-union legs), `spec-v4-data-organization.md` §3, `spec-v4-inline-editing.md` E3.
> **Status:** rev.3 — **approved 2026-10-24.** OQ1 = generated file stays gitignored (D2 stands); OQ2 = dedicated `scripts/smoke-generated-ids.ts`, same shape as `smoke-draft.ts`; OQ3 = out of scope for v5. Implementation follows §10.
---
## Overview
Content ids live in two places today: the record in `src/data/*.json`, and the id type in `src/types/index.ts`. v4 answered that by teaching the editor to patch the TypeScript file. This spec removes the second declaration instead: the id unions are **generated from the JSON at build time**, so a content change is a content change, and every guarantee `tsc` provides today stays in place.
The type contract does not change. Only where the union comes from changes.
---
## 1. Problem — measured
| # | Evidence |
|---|---|
| 1 | A record deleted in edit mode broke `pnpm build`: `TS2741: Property '"logistics-technology"' is missing in type … but required in type 'Record<SkillGroupId, SkillGroupText>'` at `src/i18n/index.ts:69`. The editor had done its own part correctly — `src/data/skills.json` and both text documents no longer carried the id; `src/types/index.ts` still did. |
| 2 | The repair is machinery in the browser save path: `UNION_SPECS`, `readUnionBlock` (line-ending aware, `never`-aware, order-preserving), `renderUnion`, `applyUnionChanges`, `diffIdsWithUnions`, `saveIdUnions` in `src/i18n/draft.ts`, plus `TYPES_FILE` / `fetchTextFile` / `putTextFile`, `typesRef` and the fetch in `EditModeShell.tsx:51,139-144,286-296`, an `EditBar` note (`EditBar.tsx:27,59,251-253`) and two UI strings in `ui/edit.json`. ~150 lines whose only job is keeping a TS file in step with JSON. |
| 3 | That machinery works — commit `1a1fc14 content: update id union members (-facility-management, -local-llm-experiments)` is a real production run — but every content add/delete therefore writes a **code file into the content history**, and the patch has to reason about line endings, member order, `never`, and blob-sha conflicts. |
| 4 | The same coupling is already stale where nothing patches it: `ProjectCategory` (`src/types/index.ts:7-13`) lists six categories; `src/data/projects.json` uses two (`logistics`, `computer-vision`). It is harmless today only because no `Record<ProjectCategory, _>` exists — and `s.projects.categories[project.category]` (`Projects.tsx:66`) is an implicit-`any` lookup, because `tsconfig.app.json` sets no `strict` / `noImplicitAny`. |
**Root cause:** one fact declared twice. Everything in row 2–4 is the cost of keeping the two copies in step.
---
## 2. What the unions guarantee today — and must keep guaranteeing
| Guarantee | Where it comes from | Survives this change? |
|---|---|---|
| Every structure id has Vietnamese text: `ContentVi.skills: Record<SkillGroupId, SkillGroupText>` (`dict-types.ts:121`) — an object literal missing a key is an error **regardless of `strict`** | closed id union | Yes. Same `Record<…>`, union generated instead of hand-written |
| A structure value outside its union is rejected: `projectsJson as ProjectStructure[]` (`src/data/projects.ts:10`) is non-comparable when a `category`/`id` literal is wrong (`TS2352`) | closed id union + `as` assertion | Partly — see D4. The assertion cannot fail any more, because the union is defined by the data. The guard that matters (a category with no label) moves to the validator |
| A malformed document fails the build, CI, and the browser load — never a silent half-render | `tsc` + `src/i18n/validate.ts` at load + `scripts/validate-content.ts` in CI | Yes, unchanged |
| Nothing at runtime | the unions are erased at emit; edit mode casts draft data (`draft.ts:465-472`, `545-553`) | Yes — the generated file is type-only, so no runtime import, no bundle change |
---
## 3. Decisions
### D1 — ids and category values are data, generated from the structure documents
`ProjectId`, `ExperienceId`, `SkillGroupId`, `PhilosophyId`, `ProjectCategory` are derived from `src/data/*.json`.
Rejected:
- **Keep hand-edited unions.** Two sources of truth; the owner must edit code to change content.
- **Keep the v4 browser patch.** It works, but it is permanent machinery in the save path plus a code commit for every content change — the thing this spec exists to remove.
- **Make ids `string`.** Deletes the machinery, and also deletes the exhaustiveness guarantee in row 1 of §2, which is the load-bearing part of §3.1. Enforcement would fall to the validator alone.
### D2 — the generator runs at build/dev time; its output is gitignored
Rejected: committing the generated file (a content edit would still dirty a code file in the working tree and in review — D1's point); generating only inside CI (the IDE and local `tsc` need the file present).
### D3 — renderer kinds stay code-owned
`ProjectSectionStructure.type: 'text' | 'diagram' | 'metrics' | 'code'`, `ExperienceStructure.variant`, `logo`, `PageId`, `ManifestId`, `ContentEntityId`, `Language`, `Palette`, `SocialId` stay hand-written in `src/types/index.ts`. They enumerate **what the code can render**, not what the owner writes — the settings popover's section-type picker offers exactly these values. This is D5 of `spec-v4-live-edit.md` (content editable, design is code), applied to types.
### D4 — `ProjectCategory` is generated, and its guard moves to the validator
New **rule 7** in `src/i18n/validate.ts`: every `category` value used in `projects.json` must have a non-empty label at `ui.<lang>.projects.categories[<value>]` in **both** languages; the issue names the file and the key. Rationale: D1 removes the `as`-assertion typo guard, and the failure that actually matters is not "an unknown category" but "a category that renders an empty badge" (`Projects.tsx:66`). Rule 7 checks exactly that.
### D5 — the type contract itself does not change
`dict-types.ts`, `Record<…>` text coverage, the loaders, the page manifests, validator rules 1–6, the 12-document draft registry, the save pipeline: unchanged.
### D6 — edit mode never writes a TypeScript file again
`saveIdUnions` and everything it needs is deleted, not deprecated. `src/types/index.ts` is not in the writable-document set, and the EditBar loses its union note.
---
## 4. Target architecture
```mermaid
graph LR
A[src/data/*.json] --> B[scripts/generate-content-types.ts]
B --> C[src/types/content-ids.ts]
C --> D[src/types/index.ts type-only re-export]
D --> E[tsc -b]
E --> F[vite build → CI gate]
A --> G[validate-content / load-time validator]
G --> F
```
### 4.1 The generated file
`src/types/content-ids.ts` (gitignored):
```ts
// Generated by scripts/generate-content-types.ts — do not edit.
// Sources: src/data/projects.json, src/data/experience.json,
// src/data/skills.json, src/data/profile.json
export type ProjectId = 'iot-dws-integration' | 'awb-detection';
export type ExperienceId = 'open-to-work' | 'relax-gap' | 'lazada-senior-swe' | 'nexts-founder' | 'sap-senior-swe';
export type SkillGroupId = 'software-engineering' | 'system-architecture' | 'ai-ml' | 'infrastructure' | 'engineering-practices';
export type PhilosophyId = 'build-for-the-real-problem' | 'think-in-systems' | 'measure-impact' | 'keep-learning' | 'business-domain-knowledge-is-a-key-of-success';
export type ProjectCategory = 'logistics' | 'computer-vision';
```
Rules: document order (stable, reviewable output); literals quoted with `JSON.stringify` so any slug is expressible; an empty document emits `never` (`Record<never, T>` accepts `{}`, `X[]` accepts `[]`); LF output; byte-identical output for identical input; if the existing bytes match, the file is not rewritten (no mtime churn for watchers).
### 4.2 `src/types/index.ts` after
Lines 1–5 (`Language`, `Palette`, `SocialId`) and 45–79 (`PageId`, `ManifestId`, `ContentEntityId`, manifest types) stay exactly as they are. Lines 7–13 and 15–43 are replaced by:
```ts
// Content ids and category values are generated from the structure documents
// (spec-v5). Type-only re-export: erased at emit, no runtime import.
export type { ProjectCategory, ExperienceId, PhilosophyId, ProjectId, SkillGroupId } from './content-ids';
```
---
## 5. Implementation Details
### 5.1 New `scripts/generate-content-types.ts`
1. Read the four structure documents with `readFileSync` + `JSON.parse` from paths resolved against `import.meta.url` (the same approach `scripts/smoke-draft.ts` uses for its inputs). **No imports from `src/`** — this script writes the module `src/` depends on.
2. Collect: `projects[].id`, `experience[].id`, `skills[].id`, `profile.philosophy[].id`; and unique `projects[].category` in first-use order.
3. Reject, with the file path in the message and exit 1: a document that is not an array; a missing `philosophy` array; a row without a string `id`; a **duplicate id** in one document (a duplicate would make `Record<…>` narrower than the document, silently).
4. Write `src/types/content-ids.ts` (§4.1). Print a one-line summary in the style of `generate-sitemap.ts`: `content ids generated (2 project, 5 experience, 5 skill group, 5 philosophy, 2 category)`.
5. `scripts/*.ts` are outside both tsconfigs (`tsconfig.node.json` includes only `vite.config.ts`), so the generator is not type-checked by `tsc -b` — it runs through `tsx`, like `validate-content.ts` and `smoke-draft.ts`. Keep it dependency-free. Optional (decide at implementation): add it to `tsconfig.node.json` `include` so its own types are checked.
6. `.oxlintrc.json` sets no `ignorePatterns`, so `pnpm lint` will lint the generated file. It is plain type aliases and should pass; if it does not, add `"ignorePatterns": ["src/types/content-ids.ts"]` rather than changing the generator's output.
### 5.2 Wiring
- `package.json`: `"generate:ids": "pnpm tsx scripts/generate-content-types.ts"`, plus `predev` and `prebuild` hooks, and `"prepare": "pnpm generate:ids"` so a fresh install produces the file before the IDE type-checks. `build` keeps its current body; `validate:content` unchanged. **Hook behaviour verified on pnpm 12.4.1** with a probe package: `pnpm run probe` ran `preprobe` first. CI pins `^12.0.0` (`.gitea/workflows/deploy.yml:27`), same major.
- `.gitea/workflows/deploy.yml` needs no change — verified: the `build` job runs `pnpm tsx scripts/validate-content.ts` (line 28) then `pnpm build` (line 29), so `prebuild` generates the file before `tsc -b`, and validation runs first but reads only JSON, never the generated module. The `generate-resume` job runs `pnpm install` (line 59) — the `prepare` hook generates there too; even without it the resume script is safe, because the re-export in §4.2 is type-only and erased by `tsx`.
- `.gitignore`: `src/types/content-ids.ts`.
### 5.3 Deletions (clean cutover, no shims)
| File | Remove |
|---|---|
| `src/i18n/draft.ts` | `TYPES_FILE` (101), `fetchTextFile` (231-236), `putTextFile` (290-298), the whole id-unions section (`UNION_SPECS`, `UnionBlock`, `MEMBER_LINE`, `CLOSING_LINE`, `nextLine`, `readUnionBlock`, `renderUnion`, `applyUnionChanges`, `diffIdsWithUnions` — 320-427 at writing), `saveIdUnions` (1156-1189), `committedStructures()` (558-566 — **verified single caller**, `diffIdsWithUnions`), and `baseDataOf()` (552-554 — dead code today: a repo-wide search finds no caller). Drop the now-unused `ContentStructures` type import. `fetchDoc` (218-229) **stays** — it is the JSON fetcher for the 12 draft documents and for the read-only UI fetch in §5.4 |
| `src/components/layout/EditModeShell.tsx` | imports `TYPES_FILE` (16), `fetchTextFile` (19), `saveIdUnions` (21); `typesRef` (51); the types-file fetch (139-144); `unionNote` state (63) and its reset (274); the union leg (284-296); the `unionNote` prop (397) |
| `src/components/layout/EditBar.tsx` | `unionNote` in the props type (27) and destructuring (59); the note block (251-253) |
| `src/i18n/locales/{vi,en}/ui/edit.json` | `unionNote`, `unionFailed` (69-70) |
| `scripts/smoke-draft.ts` | checks 9–12 (they test the deleted helpers). Checks 1–8 stay |
`fetchTextFile` / `putTextFile` have no other caller (verified across `src/`): they existed only to read and patch `src/types/index.ts`.
### 5.4 Validator rule 7
In `collectContentIssues` (`src/i18n/validate.ts:69-168`), after rule 6: for each unique category in `structures.projects`, require `ui[lang].projects.categories[value]` to be a non-empty string for `vi` and `en`; issue path `src/i18n/locales/<lang>/ui/projects.json: categories.<value>`.
**Plumbing — corrected by the self-review.** The draft store does **not** hold UI documents: `DRAFT_DOCS` (`draft.ts:48-61`) is exactly the 12 writable content documents, and `DraftStore.validate()` (`draft.ts:585-588`) calls `collectContentIssues` with structures and content texts only. The rule therefore needs a UI source at each call site, and `collectContentIssues` / `validateContent` gain a `ui` argument:
- `src/i18n/index.ts` (load-time): both UI trees are already built there — pass them.
- `scripts/validate-content.ts`: already imports `UI` from `src/i18n` (line 17) — pass it.
- `DraftStore.validate()` (the save gate): `EditModeShell` fetches the two `ui/projects.json` documents read-only at session start with `fetchDoc` and hands them to `store.validate(ui)`. Two extra GETs per edit session; no new transport helper.
Rejected alternative, recorded as the fallback: put the check in the generator (§5.1) instead — no plumbing at all, but a label-less category is then caught at `prebuild`/CI rather than before save, against §5.6 of `spec-v4-live-edit.md` ("an invalid draft never reaches the repository").
Edge case: if the two read-only GETs fail (proxy unreachable — the offline state `EditModeShell` already handles), rule 7 is **skipped with a note in the EditBar**, not treated as a failure: the offline state already disables save, and the CI gate runs the same rule against the committed documents.
### 5.5 Tests
- Remove `smoke-draft.ts` checks 9–12.
- New `scripts/smoke-generated-ids.ts`: build the generator's collector over (a) the real documents — output contains exactly the ids the documents carry and nothing else; (b) a synthetic document with an empty array — `never` emitted; (c) a duplicate id — error naming the file; (d) idempotence — running twice yields identical bytes. Open question OQ2 asks whether this file or a case inside `validate-content.ts` is the right home.
### 5.6 Docs
- `spec-v4-live-edit.md` §3.1: add a "Superseded 2026-10-24 by `spec-v5-generated-content-ids.md`" note in the style already used for §5.4, keeping the text as the implementation record; add §12 row 23.
- `AGENTS.md`: Data Layer — ids and category values are generated, `src/types/index.ts` holds code-owned unions only; Live Edit — edit mode writes JSON only; Scripts — `generate:ids` and the `predev`/`prebuild`/`prepare` hooks; Commands table updated.
- `README.md` if it documents `pnpm dev` steps (check during implementation).
---
## 6. Affected Files
| File | Action |
|---|---|
| `scripts/generate-content-types.ts` | **new** — generator |
| `src/types/content-ids.ts` | **new, generated, gitignored** |
| `src/types/index.ts` | edit 7-13 + 15-43 → type-only re-export |
| `src/i18n/draft.ts` | delete 101, 231-247, 290-298, 320-414, 545-553, ≈1148-1189 |
| `src/components/layout/EditModeShell.tsx` | delete 16, 19, 21, 51, 63, 139-144, 274, 284-296, 397 |
| `src/components/layout/EditBar.tsx` | delete 27, 59, 251-253 |
| `src/i18n/locales/vi/ui/edit.json`, `src/i18n/locales/en/ui/edit.json` | delete 69-70 |
| `src/i18n/validate.ts` | new rule 7 in `collectContentIssues` (69-168) + signature growth; `validateContent` (170-180) |
| `src/i18n/index.ts` | pass the UI dictionaries to the load-time validation |
| `src/i18n/draft.ts` `DraftStore.validate()` | pass UI documents (572-575) |
| `scripts/validate-content.ts` | pass UI documents |
| `scripts/smoke-draft.ts` | delete checks 9–12 |
| `scripts/smoke-generated-ids.ts` | **new** — generator regression smoke (OQ2) |
| `package.json` | `generate:ids`, `predev`, `prebuild`, `prepare` |
| `.gitignore` | `src/types/content-ids.ts` |
| `docs/design/specs/v4/spec-v4-live-edit.md` | §3.1 superseded note, §12 row 23 |
| `AGENTS.md` | Data Layer / Live Edit / Scripts / Commands |
Unchanged on purpose: `src/i18n/dict-types.ts`, `src/data/*.ts` loaders, `src/data/pages/*.json`, `nginx.conf`, `compose.yaml`, `.gitea/workflows/*` (verified in §5.2), `scripts/generate-resume.ts`, `scripts/generate-sitemap.ts`.
---
## 7. Acceptance Criteria
- [x] On a fresh clone, `pnpm install` or `pnpm dev` produces `src/types/content-ids.ts` and `pnpm build` passes. — `pre<script>` hook execution verified on pnpm 12.4.1 (§9), and every `pnpm build` / `pnpm tsx` run in this session regenerated the file through those hooks or through `generate:ids`. ⬜ Not verified: an actual fresh-clone checkout.
- [x] A content add or delete touches JSON only: `git status` after such an edit shows no `src/types/*` entry. — `git status --porcelain --ignored src/types/` lists the generated file as `!! src/types/content-ids.ts` (ignored, never a status entry), and after the add/delete experiments below, `git status --porcelain src/data src/i18n/locales` carried no `src/types` path.
- [x] Deleting a record while its text is still present is an error the build catches; a *stale union* can no longer cause it. Verified with a throwaway skill group, both directions:
- structure record without text (`tmp-ghost-group` added to `src/data/skills.json` only) → `src/i18n/index.ts(69,3): error TS2741: Property '"tmp-ghost-group"' is missing in type … but required in type 'Record<SkillGroupId, SkillGroupText>'` — the same class of failure the owner reported, now produced by the regenerated union rather than a hand-maintained one;
- text without a record (`tmp-ghost-text` added to `locales/vi/content/skills.json` only) → `pnpm validate:content`: `src/i18n/locales/vi/content/skills.json: tmp-ghost-text: orphan text key — no such skill group in structure`. `tsc` alone does **not** catch this direction — extra keys in an imported JSON are assignable to `Record<Id, …>` — so the validator is the gate here, exactly as before the change.
- Staleness is impossible by construction: after the structure document was restored and regenerated, `grep -c "tmp-ghost" src/types/content-ids.ts` → `0`.
- [x] A category used in `projects.json` without a label in both `ui/projects.json` files fails `pnpm validate:content` with the exact file and key. Verified: `projects[0].category = "tmp-ghost-cat"` produced `src/i18n/locales/vi/ui/projects.json: categories.tmp-ghost-cat: category used by a project has no label in this language` and the same line for `en`; with the union regenerated, `tsc` also reported `TS7053` at `src/components/sections/Projects.tsx:66`, `src/pages/ProjectDetailPage.tsx:73`, `src/pages/ProjectsListPage.tsx:55` — the label-indexing sites §4.3 names.
- [x] Edit-mode save writes only the 12 JSON documents; no `content: update id union members` commit can ever appear. `grep -rn "saveIdUnions|diffIdsWithUnions|applyUnionChanges|UnionLogEntry|onUnionsSaved|unionNote|unionError" src scripts` → no match; neither `ui/edit.json` carries a `union*` key.
- [x] `pnpm build`, `pnpm lint` (no new warnings — the four warnings it prints are the pre-existing `useTheme.tsx`, `provider.tsx`, `Footer.tsx`, `Typewriter.tsx` ones), `pnpm validate:content`, `pnpm tsx scripts/smoke-draft.ts` (11/11), `pnpm tsx scripts/smoke-generated-ids.ts` (7/7) all pass.
- [x] Resume output unchanged. `pnpm build:resume-all` renders both PDFs in both states, and the HTML handed to Playwright is byte-identical with identical content documents: sha256 `f4abe88c29f8fbe4…` (en) and `2a3ed5e23c8f8e1a…` (vi) from a run with the refactor stashed and from a run with it applied (a temporary `RESUME_DUMP_DIR` write in `generate-resume.ts`, removed after the check). `pdftotext` is not installed on this machine, so the comparison is on the rendered HTML — the input to the PDF; PDF bytes legitimately differ by Playwright metadata.
- [x] Bundle shape unchanged: 10 chunks with names identical to a build of the same documents before the refactor, and no runtime reference to the generated module (`grep -rl "content-ids" dist/` → nothing; the re-export is type-only and erased).
---
## 8. Open questions — decided 2026-10-24
- **OQ1 — generated file: gitignored (owner's call).** `src/types/content-ids.ts` is generated output, not authored code: no content commit ever carries a code file, and no content review shows a `src/types/*` diff. The id list is still reviewable — it is the id array in the structure documents, which is where it was always written.
- **OQ2 — generator regression test: dedicated `scripts/smoke-generated-ids.ts`.** Same shape as the existing `scripts/smoke-draft.ts`; `validate-content.ts` stays a validator, not a test harness.
- **OQ3 — `noImplicitAny`: out of scope for v5.** `tsconfig.app.json` sets no `strict`, so `s.projects.categories[category]` is implicit `any` today and rule 7 is the guard. Enabling it is its own task with unmeasured fallout.
---
## 9. Risks & Mitigations
| Risk | Mitigation |
|---|---|
| Fresh clone / IDE errors before the first generation | `prepare` on install + `predev`; the generator names the file and the reason in its error |
| `pre<script>` hooks not running | verified on pnpm 12.4.1 (a probe script ran `preprobe` before `probe`); CI pins `^12.0.0`. Note the CI `build` job never runs `pnpm install`, so `prebuild` — not `prepare` — is what guarantees generation there |
| Losing the `as`-assertion typo guard for `category` | validator rule 7 checks the real failure (no label); the category list is reviewed as a JSON diff in Gitea |
| Generated file committed by accident | `.gitignore` entry + an acceptance check that a content edit dirties JSON only |
| Draft data in the browser is not type-checked | unchanged from v4 — edit mode casts draft data; the CI build is the gate, as in D4 of `spec-v4-live-edit.md` |
| A deleted project id that is already a published URL | unchanged behaviour from v4; `pnpm build` regenerates `sitemap.xml` |
| Removing the EditBar union note leaves an orphan UI string | both keys deleted with the feature; `edit` group keeps every other key |
---
## 10. Progress Tracking
| # | Task | Status |
|---|------|--------|
| 1 | This spec (rev.1) reviewed & approved by owner — OQ1–OQ3 decided | ✅ Decided 2026-10-24 — OQ1 gitignored, OQ2 dedicated generator smoke, OQ3 out of scope (§8) |
| 2 | `scripts/generate-content-types.ts` + generated file + `package.json` hooks + `.gitignore` (`deploy.yml` confirmed unchanged) | ✅ Done 2026-10-24 — generator writes the 777-byte module (2 project, 5 experience, 5 skill group, 5 philosophy, 2 category ids) and is byte-stable on a second run; `generate:ids` + `predev` / `prebuild` / `prepare` in `package.json`; `.gitignore` carries `src/types/content-ids.ts`; `.gitea/workflows/deploy.yml` untouched |
| 3 | `src/types/index.ts` re-export; delete the v4 union machinery in `draft.ts`, `EditModeShell.tsx`, `EditBar.tsx`, `ui/edit.json` | ✅ Done 2026-10-24 — `index.ts` re-exports the generated unions type-only and keeps `Language`, `Palette`, `SocialId`, `PageId`, `PageManifestClaim`, `PageManifest`, `Theme`; `saveIdUnions` / `diffIdsWithUnions` / `applyUnionChanges` / `readUnionBlock` / `unionNote` / `unionError` / `UnionLogEntry` / `onUnionsSaved` / the EditBar union card / `edit.union.*` deleted — `grep` over `src` + `scripts` finds no match |
| 4 | Validator rule 7 + `ui` argument at all three call sites (`index.ts`, `validate-content.ts`, `store.validate(ui)` fed by a read-only `fetchDoc` pair in `EditModeShell`) | ✅ Done 2026-10-24 — verified end-to-end: a project with `category: "tmp-ghost-cat"` fails `pnpm validate:content` naming both `ui/projects.json` files and `categories.tmp-ghost-cat`; the draft store skips the rule when the labels cannot be read and the EditBar says so |
| 5 | Tests: remove `smoke-draft.ts` 9–12; add the generator smoke (OQ2) | ✅ Done 2026-10-24 — `smoke-draft.ts` 11/11 (checks 9–12 replaced by the rename re-sluging check and the category-label rule check); `scripts/smoke-generated-ids.ts` 7/7: the unions equal the documents, the file on disk equals what these documents generate now, output byte-stable, `never` for an emptied document, a duplicate id refused naming the file, a record with no usable id or category refused naming the file, every slug quoted so it round-trips in document order |
| 6 | Verification run: `pnpm build`, `pnpm lint`, `pnpm validate:content`, both smokes, resume PDF text diff, `dist/` chunk list comparison against a build of the same documents | ✅ Done 2026-10-24 — all commands pass; resume HTML byte-identical before/after with identical documents (sha256 in §7); `dist/` chunk names identical, 10 chunks, no runtime reference to the generated module; `pnpm build:resume-all` produces both PDFs in both states. ⬜ Not run: a fresh-clone checkout |
| 7 | Docs: `spec-v4-live-edit.md` §3.1 superseded note + §12 row 23, `AGENTS.md`, `README.md` if needed | ✅ Done 2026-10-24 — §3.1 banner, §12 row 22 marked superseded + row 23 added here; `AGENTS.md` Commands row, Data Layer bullet, Live Edit bullet rewritten, component tree, Scripts list, Gotcha 8, Design Specs v5 row; `README.md` `generate:ids` row + the generated-ids note |
+4
View File
@@ -5,7 +5,11 @@
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
"predev": "pnpm generate:ids",
"build": "tsc -b && vite build && pnpm tsx scripts/generate-sitemap.ts", "build": "tsc -b && vite build && pnpm tsx scripts/generate-sitemap.ts",
"prebuild": "pnpm generate:ids",
"generate:ids": "pnpm tsx scripts/generate-content-types.ts",
"prepare": "pnpm generate:ids",
"build:resume": "pnpm tsx scripts/generate-resume.ts", "build:resume": "pnpm tsx scripts/generate-resume.ts",
"build:resume-all": "pnpm tsx scripts/generate-resume.ts --lang=all", "build:resume-all": "pnpm tsx scripts/generate-resume.ts --lang=all",
"build:resume-preview": "pnpm tsx scripts/generate-resume.ts --preview", "build:resume-preview": "pnpm tsx scripts/generate-resume.ts --preview",
+153
View File
@@ -0,0 +1,153 @@
// Generates src/types/content-ids.ts from the structure documents (spec-v5).
//
// Deliberately imports nothing from src/: this script writes the module the
// src/ loaders depend on, so it has to run — and read — before that module
// exists. It validates only what a generated union requires (an id is a
// non-empty string, ids are unique, a category is a non-empty string);
// cross-document rules stay in src/i18n/validate.ts.
//
// Run by `predev` / `prebuild` / `prepare` (see package.json), so every type
// check sees a union that is exactly the id set the documents carry. The pure
// parts are exported for scripts/smoke-generated-ids.ts; `main` runs only when
// this file is executed.
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
const ROOT = resolve(import.meta.dirname, '..');
const TARGET = join(ROOT, 'src/types/content-ids.ts');
export const SOURCE_FILES = {
projects: 'src/data/projects.json',
experience: 'src/data/experience.json',
skills: 'src/data/skills.json',
profile: 'src/data/profile.json',
} as const;
export type ContentDocuments = Record<keyof typeof SOURCE_FILES, unknown>;
export type GeneratedIds = {
output: string;
counts: { project: number; experience: number; skillGroup: number; philosophy: number; category: number };
};
// A duplicate id would make Record<…> narrower than the document, silently.
export function idsOf(rows: unknown, file: string): string[] {
if (!Array.isArray(rows)) throw new Error(`${file}: expected an array of records`);
const ids: string[] = [];
rows.forEach((row, index) => {
const id = row && typeof row === 'object' && 'id' in row ? row.id : undefined;
if (typeof id !== 'string' || id.length === 0) {
throw new Error(`${file}: record ${index} has no string "id"`);
}
if (ids.includes(id)) throw new Error(`${file}: duplicate id ${JSON.stringify(id)}`);
ids.push(id);
});
return ids;
}
// Category values are whatever the projects use, first-use order — the label
// guard is validator rule 7, not a closed union (spec-v5 D4).
export function categoriesOf(rows: unknown, file: string): string[] {
if (!Array.isArray(rows)) throw new Error(`${file}: expected an array of records`);
const categories: string[] = [];
rows.forEach((row, index) => {
const category = row && typeof row === 'object' && 'category' in row ? row.category : undefined;
if (typeof category !== 'string' || category.length === 0) {
throw new Error(`${file}: record ${index} has no string "category"`);
}
if (!categories.includes(category)) categories.push(category);
});
return categories;
}
export function philosophyIdsOf(document: unknown, file: string): string[] {
const list =
document && typeof document === 'object' && 'philosophy' in document ? document.philosophy : undefined;
if (!Array.isArray(list)) throw new Error(`${file}: "philosophy" must be an array of { id } records`);
return idsOf(list, `${file} → philosophy`);
}
// Document order, one member per line, JSON.stringify for the literals so any
// slug is expressible. An empty document emits `never`: Record<never, T>
// accepts {} and X[] accepts [], which is what an emptied document needs.
export function renderUnion(name: string, members: readonly string[]): string {
if (members.length === 0) return `export type ${name} = never;`;
const literals = members.map((member) => JSON.stringify(member));
if (literals.length === 1) return `export type ${name} = ${literals[0]};`;
return `export type ${name} =\n${literals.map((literal) => ` | ${literal}`).join('\n')};`;
}
// The whole generated module for one set of documents. Deterministic: the same
// documents always produce the same bytes.
export function collectOutput(documents: ContentDocuments): GeneratedIds {
const projectIds = idsOf(documents.projects, SOURCE_FILES.projects);
const categoryValues = categoriesOf(documents.projects, SOURCE_FILES.projects);
const experienceIds = idsOf(documents.experience, SOURCE_FILES.experience);
const skillGroupIds = idsOf(documents.skills, SOURCE_FILES.skills);
const philosophyIds = philosophyIdsOf(documents.profile, SOURCE_FILES.profile);
const output = [
'// Generated by scripts/generate-content-types.ts — do not edit.',
`// Sources: ${SOURCE_FILES.projects}, ${SOURCE_FILES.experience},`,
`// ${SOURCE_FILES.skills}, ${SOURCE_FILES.profile}`,
'',
renderUnion('ProjectId', projectIds),
'',
renderUnion('ExperienceId', experienceIds),
'',
renderUnion('SkillGroupId', skillGroupIds),
'',
renderUnion('PhilosophyId', philosophyIds),
'',
renderUnion('ProjectCategory', categoryValues),
'',
].join('\n');
return {
output,
counts: {
project: projectIds.length,
experience: experienceIds.length,
skillGroup: skillGroupIds.length,
philosophy: philosophyIds.length,
category: categoryValues.length,
},
};
}
export function readDocuments(): ContentDocuments {
const documents = {} as ContentDocuments;
for (const [key, file] of Object.entries(SOURCE_FILES) as [keyof ContentDocuments, string][]) {
const path = join(ROOT, file);
if (!existsSync(path)) throw new Error(`${file} not found — the id unions are generated from it`);
documents[key] = JSON.parse(readFileSync(path, 'utf-8'));
}
return documents;
}
function main(): void {
let generated: GeneratedIds;
try {
generated = collectOutput(readDocuments());
} catch (error) {
console.error(`[FAIL] ${(error as Error).message}`);
process.exit(1);
}
// Byte-identical output for identical input; an unchanged file is not
// rewritten, so watchers and editors see no mtime churn on a plain `pnpm dev`.
if (!existsSync(TARGET) || readFileSync(TARGET, 'utf-8') !== generated.output) {
writeFileSync(TARGET, generated.output);
}
const { counts } = generated;
console.log(
`content ids generated (${counts.project} project, ${counts.experience} experience, ` +
`${counts.skillGroup} skill group, ${counts.philosophy} philosophy, ` +
`${counts.category} category) → src/types/content-ids.ts`,
);
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
main();
}
+54 -86
View File
@@ -1,19 +1,28 @@
// Smoke test for the draft store (spec-v4 §5.1, §5.5, §5.6; registry per // Smoke test for the draft store (spec-v4 §5.1, §5.5, §5.6; registry per
// spec-v4-data-organization §6.1; id-union legs per §3.1). // spec-v4-data-organization §6.1). Id unions are no longer the store's
// business — scripts/generate-content-types.ts derives them from these very
// documents (spec-v5), so what is checked here is the draft itself: text
// writes, record add/delete/rename, conflicts and rebase, and the validator
// rules a rejected edit is reported through.
// Run: pnpm tsx scripts/smoke-draft.ts // Run: pnpm tsx scripts/smoke-draft.ts
import { readFileSync } from 'node:fs'; import { DraftStore, bundledBase } from '../src/i18n/draft';
import { DraftStore, applyUnionChanges, bundledBase, diffIdsWithUnions } from '../src/i18n/draft'; import type { CategoryLabels } from '../src/i18n/validate';
import projectsEnUiJson from '../src/i18n/locales/en/ui/projects.json';
import projectsViUiJson from '../src/i18n/locales/vi/ui/projects.json';
const fail = (msg: string): never => { const fail = (msg: string): never => {
console.error(`FAIL: ${msg}`); console.error(`FAIL: ${msg}`);
process.exit(1); process.exit(1);
}; };
// The file the save pipeline patches. // Rule 7's read-only input, exactly as the edit session supplies it.
const TYPES = readFileSync(new URL('../src/types/index.ts', import.meta.url), 'utf8'); const LABELS: CategoryLabels = {
vi: projectsViUiJson.categories as Record<string, unknown>,
en: projectsEnUiJson.categories as Record<string, unknown>,
};
const bases = bundledBase(); const bases = bundledBase();
const store = new DraftStore(structuredClone(bases)); const store = new DraftStore(structuredClone(bases), LABELS);
const projects = store.dataOf('projects') as { id: string }[]; const projects = store.dataOf('projects') as { id: string }[];
const firstProject = projects[0].id; const firstProject = projects[0].id;
@@ -65,7 +74,7 @@ if (!same) fail('restored draft differs from saved snapshot');
// 6. Conflict: base changed at a path the draft also touched → rebase reports // 6. Conflict: base changed at a path the draft also touched → rebase reports
// a conflict; take-theirs (discardDocument) clears it. // a conflict; take-theirs (discardDocument) clears it.
const store2 = new DraftStore(structuredClone(bases)); const store2 = new DraftStore(structuredClone(bases), LABELS);
store2.setValue('vi', `projects.${firstProject}.summary`, 'MINE'); store2.setValue('vi', `projects.${firstProject}.summary`, 'MINE');
const driftedBase = structuredClone(bases); const driftedBase = structuredClone(bases);
(driftedBase['projects.vi'].data as Record<string, Record<string, string>>)[firstProject].summary = 'THEIRS'; (driftedBase['projects.vi'].data as Record<string, Record<string, string>>)[firstProject].summary = 'THEIRS';
@@ -77,7 +86,7 @@ if (store2.changedPaths('projects.vi').includes(`${firstProject}.summary`))
fail('take-theirs left draft residue'); fail('take-theirs left draft residue');
// 7. Clean rebase: base changed at a DIFFERENT path → draft edit survives. // 7. Clean rebase: base changed at a DIFFERENT path → draft edit survives.
const store3 = new DraftStore(structuredClone(bases)); const store3 = new DraftStore(structuredClone(bases), LABELS);
store3.setValue('vi', `projects.${firstProject}.summary`, 'MINE'); store3.setValue('vi', `projects.${firstProject}.summary`, 'MINE');
const otherBase = structuredClone(bases); const otherBase = structuredClone(bases);
const otherId = projects[1].id; const otherId = projects[1].id;
@@ -93,7 +102,7 @@ if (mergedText[otherId].summary !== 'THEIRS') fail('rebase lost the base edit');
// branch — the field still lives in the structure document) must gain a real // branch — the field still lives in the structure document) must gain a real
// array when a [0] path is committed; an object-keyed pseudo-array crashed // array when a [0] path is committed; an object-keyed pseudo-array crashed
// TagListEditor's items.map on the re-render after the first tag edit. // TagListEditor's items.map on the re-render after the first tag edit.
const store4 = new DraftStore(structuredClone(bases)); const store4 = new DraftStore(structuredClone(bases), LABELS);
const baseVi = store4.dataOf('profile.vi') as Record<string, Record<string, unknown>>; const baseVi = store4.dataOf('profile.vi') as Record<string, Record<string, unknown>>;
delete baseVi.currentInterests; delete baseVi.currentInterests;
const tagEdit = store4.setValue('vi', 'profile.currentInterests[0]', 'NEW TAG'); const tagEdit = store4.setValue('vi', 'profile.currentInterests[0]', 'NEW TAG');
@@ -102,55 +111,24 @@ const arr = (store4.dataOf('profile.vi') as Record<string, Record<string, unknow
if (!Array.isArray(arr)) fail(`setPath made ${JSON.stringify(arr)}, not an array`); if (!Array.isArray(arr)) fail(`setPath made ${JSON.stringify(arr)}, not an array`);
if (arr[0] !== 'NEW TAG') fail('array element not set'); if (arr[0] !== 'NEW TAG') fail('array element not set');
// 9. The shipped documents and the shipped id unions agree. This is the check // 9. A skill-group delete removes the record and its text in both languages,
// that was missing: a skill group deleted in edit mode left 'logistics- // and the draft still validates.
// technology' in SkillGroupId, and `Record<SkillGroupId, …>` then failed the const store5 = new DraftStore(structuredClone(bases), LABELS);
// build with TS2741.
const drift = diffIdsWithUnions(new DraftStore(structuredClone(bases)), TYPES);
if (drift.added.length + drift.removed.length > 0)
fail(`documents and id unions disagree: ${JSON.stringify(drift)}`);
// 10. A deleted record prunes its union member — and only that line, in
// either line ending (git stores LF, a Windows checkout reads CRLF).
const store5 = new DraftStore(structuredClone(bases));
const groupIds = (store5.dataOf('skills') as { id: string }[]).map((g) => g.id); const groupIds = (store5.dataOf('skills') as { id: string }[]).map((g) => g.id);
const victim = groupIds[groupIds.length - 1]; const victim = groupIds[groupIds.length - 1];
const delGroup = store5.deleteRecord('skill-group', { id: victim }); const delGroup = store5.deleteRecord('skill-group', { id: victim });
if (delGroup !== null) fail(`skill-group delete rejected: ${JSON.stringify(delGroup)}`); if (delGroup !== null) fail(`skill-group delete rejected: ${JSON.stringify(delGroup)}`);
const afterDelete = store5.validate(); const afterDelete = store5.validate();
if (afterDelete.length > 0) fail(`validate after delete: ${JSON.stringify(afterDelete)}`); if (afterDelete.length > 0) fail(`validate after delete: ${JSON.stringify(afterDelete)}`);
// The union leg follows ids whose documents actually landed. if ((store5.dataOf('skills.vi') as Record<string, unknown>)[victim])
for (const id of ['skills', 'skills.vi', 'skills.en'] as const) store5.markWritten(id, 'simulated-sha'); fail('vi skill-group text orphan after delete');
const stale = diffIdsWithUnions(store5, TYPES); if ((store5.dataOf('skills.en') as Record<string, unknown>)[victim])
if (stale.added.length > 0) fail(`a delete reported additions: ${JSON.stringify(stale.added)}`); fail('en skill-group text orphan after delete');
if (stale.removed.length !== 1 || stale.removed[0].id !== victim || stale.removed[0].union !== 'SkillGroupId')
fail(`stale union member not reported: ${JSON.stringify(stale.removed)}`);
const pruned = applyUnionChanges(TYPES, [{ union: 'SkillGroupId', add: [], remove: [victim] }]);
if (pruned === null) fail('prune refused a multi-line union');
if (pruned.includes(`'${victim}'`)) fail('stale member survived the prune');
const EOL = TYPES.includes('\r\n') ? '\r\n' : '\n';
const expectedBlock = `export type SkillGroupId =${EOL}${groupIds
.filter((id) => id !== victim)
.map((id) => ` | '${id}'`)
.join(EOL)};${EOL}`;
const expected = TYPES.replace(/export type SkillGroupId =\r?\n(?:[ \t]*\| '[^']+';?\r?\n)+/, () => expectedBlock);
if (pruned !== expected) fail('prune rewrote more than the SkillGroupId member list');
const afterPrune = diffIdsWithUnions(store5, pruned);
if (afterPrune.added.length + afterPrune.removed.length > 0)
fail(`union still mismatched after the prune: ${JSON.stringify(afterPrune)}`);
const lfTypes = TYPES.replace(/\r\n/g, '\n');
const prunedLf = applyUnionChanges(lfTypes, [{ union: 'SkillGroupId', add: [], remove: [victim] }]);
if (prunedLf === null) fail('prune refused an LF union');
if (prunedLf.includes('\r\n')) fail('an LF patch introduced CRLF');
if (prunedLf !== expected.replace(/\r\n/g, '\n')) fail('LF patch differs from the LF source');
const afterPruneLf = diffIdsWithUnions(store5, prunedLf);
if (afterPruneLf.added.length + afterPruneLf.removed.length > 0)
fail(`union still mismatched after the LF prune: ${JSON.stringify(afterPruneLf)}`);
// 11. An id that also reads as a string elsewhere in the file is still // 10. A created record keeps following its title: renaming re-sluges the id in
// appended. 'home' is a PageId member, so a substring test would have skipped // the structure document and both text documents at once (E3). 'Home' → 'home'
// this leg and the build would have broken the other way. // is the case a naive substring replacement would break.
const store6 = new DraftStore(structuredClone(bases)); const store6 = new DraftStore(structuredClone(bases), LABELS);
const addGroup = store6.addRecord('skill-group'); const addGroup = store6.addRecord('skill-group');
if (addGroup !== null) fail(`skill-group add rejected: ${JSON.stringify(addGroup)}`); if (addGroup !== null) fail(`skill-group add rejected: ${JSON.stringify(addGroup)}`);
const known = new Set(groupIds); const known = new Set(groupIds);
@@ -158,41 +136,31 @@ const created = (store6.dataOf('skills') as { id: string }[]).find((g) => !known
if (!created) fail('no new skill group created'); if (!created) fail('no new skill group created');
const rename = store6.renameRecord('skill-group', { id: created.id }, 'Home'); const rename = store6.renameRecord('skill-group', { id: created.id }, 'Home');
if (rename !== null) fail(`rename rejected: ${JSON.stringify(rename)}`); if (rename !== null) fail(`rename rejected: ${JSON.stringify(rename)}`);
if (!(store6.dataOf('skills') as { id: string }[]).some((g) => g.id === 'home')) const renamed = (store6.dataOf('skills') as { id: string }[]).map((g) => g.id);
fail('rename did not apply'); if (!renamed.includes('home')) fail('rename did not apply');
if (renamed.includes(created.id)) fail('the pre-rename id survived');
const renamedText = store6.dataOf('skills.vi') as Record<string, unknown>;
if (renamedText[created.id]) fail('text kept the pre-rename id');
if (!renamedText.home) fail('text did not follow the renamed id');
const afterRename = store6.validate(); const afterRename = store6.validate();
if (afterRename.length > 0) fail(`validate after rename: ${JSON.stringify(afterRename)}`); if (afterRename.length > 0) fail(`validate after rename: ${JSON.stringify(afterRename)}`);
for (const id of ['skills', 'skills.vi', 'skills.en'] as const) store6.markWritten(id, 'simulated-sha');
const missing = diffIdsWithUnions(store6, TYPES);
if (!missing.added.some((a) => a.union === 'SkillGroupId' && a.id === 'home'))
fail(`id colliding with another union member was not appended: ${JSON.stringify(missing.added)}`);
if (missing.removed.length > 0) fail(`an add reported removals: ${JSON.stringify(missing.removed)}`);
const appended = applyUnionChanges(TYPES, [{ union: 'SkillGroupId', add: ['home'], remove: [] }]);
if (appended === null) fail('append refused a multi-line union');
const afterAppend = diffIdsWithUnions(store6, appended);
if (afterAppend.added.length + afterAppend.removed.length > 0)
fail(`union still mismatched after the append: ${JSON.stringify(afterAppend)}`);
// 12. An emptied document prunes its union to `never`, and a record added on // 11. Rule 7 (spec-v5 D4): a category a project uses must have a label in
// top of that state is appended back rather than silently skipped. // both languages — the badge would render empty. The category union is
const emptied = applyUnionChanges(TYPES, [{ union: 'SkillGroupId', add: [], remove: groupIds }]); // generated from the documents, so a value written straight into
if (emptied === null) fail('prune of every member refused'); // src/data/projects.json is exactly what this catches.
if (!emptied.includes('export type SkillGroupId = never;')) fail('emptied union is not never'); const store7 = new DraftStore(structuredClone(bases), LABELS);
const store7 = new DraftStore(structuredClone(bases)); const rejectedCategory = store7.setStructured('projects', '[0].category', 'not-a-category');
if (store7.addRecord('skill-group') !== null) fail('skill-group add rejected on a never union'); if (rejectedCategory === null) fail('a label-less category was accepted');
const addedGroup = (store7.dataOf('skills') as { id: string }[]).find((g) => !known.has(g.id)); const issuePaths = rejectedCategory.map((issue) => issue.path).sort();
if (!addedGroup) fail('no new skill group created for the never case'); const expectedPaths = [
for (const id of ['skills', 'skills.vi', 'skills.en'] as const) store7.markWritten(id, 'simulated-sha'); 'src/i18n/locales/en/ui/projects.json: categories.not-a-category',
const revived = diffIdsWithUnions(store7, emptied); 'src/i18n/locales/vi/ui/projects.json: categories.not-a-category',
if (!revived.added.some((a) => a.union === 'SkillGroupId' && a.id === addedGroup.id)) ].sort();
fail(`never union skipped the new id: ${JSON.stringify(revived.added)}`); if (JSON.stringify(issuePaths) !== JSON.stringify(expectedPaths))
if (revived.removed.length > 0) fail(`the never case reported removals: ${JSON.stringify(revived.removed)}`); fail(`rule 7 reported the wrong issues: ${JSON.stringify(issuePaths)}`);
const back = applyUnionChanges( if (store7.isDirty()) fail('a rejected structure write mutated the draft');
emptied, const acceptedCategory = store7.setStructured('projects', '[0].category', 'logistics');
[{ union: 'SkillGroupId', add: revived.added.map((a) => a.id), remove: [] }], if (acceptedCategory !== null) fail(`labeled category rejected: ${JSON.stringify(acceptedCategory)}`);
);
if (back === null) fail('append onto never refused'); console.log('draft store smoke: all 11 checks passed');
const afterNever = diffIdsWithUnions(store7, back);
if (afterNever.added.length + afterNever.removed.length > 0)
fail(`never round-trip left a mismatch: ${JSON.stringify(afterNever)}`);
console.log('draft store smoke: all 12 checks passed');
+150
View File
@@ -0,0 +1,150 @@
// Smoke test for the content-id generator (spec-v5 §5.5): what the generated
// module must guarantee — the union is exactly the document, in document order,
// an emptied document is `never`, a malformed document is refused with its path,
// and the same documents always produce the same bytes.
// Run: pnpm tsx scripts/smoke-generated-ids.ts
import { readFileSync } from 'node:fs';
import { collectOutput, readDocuments } from './generate-content-types';
const fail = (msg: string): never => {
console.error(`FAIL: ${msg}`);
process.exit(1);
};
const readJson = (relative: string): unknown =>
JSON.parse(readFileSync(new URL(relative, import.meta.url), 'utf8'));
// The documents read the way a reader would: checked, then used.
function idsFrom(value: unknown, label: string): string[] {
if (!Array.isArray(value)) fail(`${label}: expected an array of records`);
return value.map((row, index) => {
const id = row && typeof row === 'object' && 'id' in row ? row.id : undefined;
if (typeof id !== 'string') fail(`${label}: record ${index} has no string id`);
return id;
});
}
function categoriesFrom(value: unknown, label: string): string[] {
if (!Array.isArray(value)) fail(`${label}: expected an array of records`);
const categories: string[] = [];
value.forEach((row, index) => {
const category = row && typeof row === 'object' && 'category' in row ? row.category : undefined;
if (typeof category !== 'string') fail(`${label}: record ${index} has no string category`);
if (!categories.includes(category)) categories.push(category);
});
return categories;
}
// The unions as a reader sees them, parsed straight out of the generated text.
function unionMembers(text: string, name: string): string[] {
const declaration = new RegExp(`export type ${name} =([^;]*);`, 'm').exec(text);
if (!declaration) fail(`no ${name} declaration in the generated module`);
const body = declaration[1].trim();
if (body === 'never') return [];
return [...body.matchAll(/"((?:[^"\\]|\\.)*)"/g)].map((literal) => JSON.parse(`"${literal[1]}"`));
}
const throwsWithPath = (fn: () => unknown, file: string, label: string): void => {
try {
fn();
} catch (error) {
const message = (error as Error).message;
if (!message.includes(file)) fail(`${label} did not name ${file}: ${message}`);
return;
}
fail(`${label} was accepted`);
};
const generated = collectOutput(readDocuments());
// 1. The shipped documents and the shipped module agree — every union is exactly
// the ids its document carries, in document order, with nothing left over. This
// is the guarantee the hand-written unions could not keep (a deleted skill group
// left 'logistics-technology' behind and the build failed with TS2741).
const projectsDoc = readJson('../src/data/projects.json');
const projectIds = idsFrom(projectsDoc, 'projects.json');
const categoryValues = categoriesFrom(projectsDoc, 'projects.json');
const experienceIds = idsFrom(readJson('../src/data/experience.json'), 'experience.json');
const skillGroupIds = idsFrom(readJson('../src/data/skills.json'), 'skills.json');
const profileDoc = readJson('../src/data/profile.json');
const philosophyList =
profileDoc && typeof profileDoc === 'object' && 'philosophy' in profileDoc ? profileDoc.philosophy : undefined;
const philosophyIds = idsFrom(philosophyList, 'profile.json → philosophy');
const expected: Record<string, string[]> = {
ProjectId: projectIds,
ExperienceId: experienceIds,
SkillGroupId: skillGroupIds,
PhilosophyId: philosophyIds,
ProjectCategory: categoryValues,
};
for (const [name, ids] of Object.entries(expected)) {
const emitted = unionMembers(generated.output, name);
if (JSON.stringify(emitted) !== JSON.stringify(ids))
fail(`${name} does not match its document: ${JSON.stringify(emitted)} vs ${JSON.stringify(ids)}`);
}
// 2. The file on disk is what these very documents produce right now — a
// generated module that drifted from its sources is a build-time lie.
const onDisk = readFileSync(new URL('../src/types/content-ids.ts', import.meta.url), 'utf8');
if (onDisk !== generated.output) fail('src/types/content-ids.ts is not what the documents generate');
// 3. Determinism: the same documents, the same bytes, twice.
if (collectOutput(readDocuments()).output !== generated.output)
fail('generation is not byte-stable for the same input');
// 4. An emptied document generates `never`, which keeps Record<never, T> valid
// against an empty text document and X[] valid against an empty array.
const emptied = collectOutput({ projects: [], experience: [], skills: [], profile: { philosophy: [] } });
for (const name of Object.keys(expected)) {
if (!emptied.output.includes(`export type ${name} = never;`)) fail(`${name} of an empty document is not never`);
if (unionMembers(emptied.output, name).length !== 0) fail(`${name} never still lists members`);
}
// 5. A duplicate id is refused, naming the file: a duplicate would make the
// union narrower than the document, silently.
throwsWithPath(
() => collectOutput({ projects: [{ id: 'a', category: 'x' }, { id: 'a', category: 'y' }], experience: [], skills: [], profile: { philosophy: [] } }),
'src/data/projects.json',
'a duplicate id',
);
// 6. A record without a usable id or category is refused, naming the file.
throwsWithPath(
() => collectOutput({ projects: [{ category: 'x' }], experience: [], skills: [], profile: { philosophy: [] } }),
'src/data/projects.json',
'a record with no id',
);
throwsWithPath(
() => collectOutput({ projects: [{ id: 'a' }], experience: [], skills: [], profile: { philosophy: [] } }),
'src/data/projects.json',
'a record with no category',
);
throwsWithPath(
() => collectOutput({ projects: [], experience: { id: 'oops' }, skills: [], profile: { philosophy: [] } }),
'src/data/experience.json',
'a document that is not an array',
);
throwsWithPath(
() => collectOutput({ projects: [], experience: [], skills: [], profile: {} }),
'src/data/profile.json',
'a missing philosophy array',
);
// 7. Any slug is expressible: a literal is quoted so it round-trips, and the
// document order is preserved rather than sorted.
const odd = collectOutput({
projects: [
{ id: 'b"quote', category: 'a category' },
{ id: 'a-first', category: 'a category' },
],
experience: [],
skills: [],
profile: { philosophy: [] },
});
if (JSON.stringify(unionMembers(odd.output, 'ProjectId')) !== JSON.stringify(['b"quote', 'a-first']))
fail(`quoted or ordered ids were mangled: ${JSON.stringify(unionMembers(odd.output, 'ProjectId'))}`);
if (JSON.stringify(unionMembers(odd.output, 'ProjectCategory')) !== JSON.stringify(['a category']))
fail('a category was duplicated or reordered');
console.log('generated content ids: all 7 checks passed');
+4 -1
View File
@@ -34,7 +34,10 @@ const contentEn: ContentEn = {
const structures = { profile, skills: skillGroups, experience: experiences, projects }; const structures = { profile, skills: skillGroups, experience: experiences, projects };
const issues = [ const issues = [
...collectContentIssues(structures, contentVi, contentEn), ...collectContentIssues(structures, contentVi, contentEn, {
vi: UI.vi.projects.categories,
en: UI.en.projects.categories,
}),
...collectManifestIssues(structures, contentVi, contentEn, Object.keys(UI.vi)), ...collectManifestIssues(structures, contentVi, contentEn, Object.keys(UI.vi)),
]; ];
+3 -5
View File
@@ -24,7 +24,7 @@ type EditBarProps = {
saving: boolean; saving: boolean;
saveStopped: boolean; saveStopped: boolean;
saveResults: DocSaveResult[]; saveResults: DocSaveResult[];
unionNote: 'ok' | 'failed' | null; labelsUnavailable: boolean;
draftRestored: boolean; draftRestored: boolean;
branch: string; branch: string;
getConflictFields: (id: DraftDocId) => ConflictField[]; getConflictFields: (id: DraftDocId) => ConflictField[];
@@ -56,7 +56,7 @@ export function EditBar({
saving, saving,
saveStopped, saveStopped,
saveResults, saveResults,
unionNote, labelsUnavailable,
draftRestored, draftRestored,
branch, branch,
getConflictFields, getConflictFields,
@@ -248,9 +248,7 @@ export function EditBar({
</ul> </ul>
)} )}
{unionNote && ( {labelsUnavailable && <p className="edit-bar-note">{s.labelsUnavailable}</p>}
<p className="edit-bar-note">{unionNote === 'ok' ? s.unionNote : s.unionFailed}</p>
)}
{allWritten && !dirty && ( {allWritten && !dirty && (
<p className="edit-bar-note"> <p className="edit-bar-note">
{branch === DEFAULT_BRANCH ? s.deployQueued : s.mergeHint} {branch === DEFAULT_BRANCH ? s.deployQueued : s.mergeHint}
+34 -31
View File
@@ -3,7 +3,7 @@
// master documents, holds the draft, and re-wraps the tree in an // master documents, holds the draft, and re-wraps the tree in an
// I18nProvider override — the seven routes ARE the preview. Visitors never // I18nProvider override — the seven routes ARE the preview. Visitors never
// mount this component; its code is never in the entry chunk (§7 P3.4). // mount this component; its code is never in the entry chunk (§7 P3.4).
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useCallback, useEffect, useMemo, useState } from 'react';
import type { ReactNode } from 'react'; import type { ReactNode } from 'react';
import { useLocation, useNavigate } from 'react-router'; import { useLocation, useNavigate } from 'react-router';
import { useLanguage } from '@/hooks/useLanguage'; import { useLanguage } from '@/hooks/useLanguage';
@@ -13,12 +13,9 @@ import type { ResolvedContent } from '@/i18n';
import { import {
DRAFT_DOCS, DRAFT_DOCS,
DraftStore, DraftStore,
TYPES_FILE,
bundledBase, bundledBase,
fetchDoc, fetchDoc,
fetchTextFile,
saveDraft, saveDraft,
saveIdUnions,
recordForTitlePath, recordForTitlePath,
} from '@/i18n/draft'; } from '@/i18n/draft';
import type { DocBase, DocSaveResult, DraftDocId } from '@/i18n/draft'; import type { DocBase, DocSaveResult, DraftDocId } from '@/i18n/draft';
@@ -34,11 +31,26 @@ import {
} from '@/i18n/edit-mode'; } from '@/i18n/edit-mode';
import { EditContext } from '@/hooks/useEdit'; import { EditContext } from '@/hooks/useEdit';
import type { EditApi } from '@/hooks/useEdit'; import type { EditApi } from '@/hooks/useEdit';
import type { ContentIssue } from '@/i18n/validate'; import type { CategoryLabels, ContentIssue } from '@/i18n/validate';
import { EditBar } from './EditBar'; import { EditBar } from './EditBar';
type Phase = 'authenticating' | 'loading' | 'ready' | 'offline'; type Phase = 'authenticating' | 'loading' | 'ready' | 'offline';
// The category labels are read-only UI documents (spec-v4-data-organization §4);
// rule 7 compares a project's category against them on the branch being edited
// (spec-v5 §5.4), so they are fetched beside the draft documents instead of
// taken from this bundle.
const LABEL_FILES: Record<'vi' | 'en', string> = {
vi: 'src/i18n/locales/vi/ui/projects.json',
en: 'src/i18n/locales/en/ui/projects.json',
};
const categoryMap = (data: unknown): Record<string, unknown> => {
if (!data || typeof data !== 'object' || !('categories' in data)) return {};
const categories = data.categories;
if (typeof categories !== 'object' || categories === null || Array.isArray(categories)) return {};
return Object.fromEntries(Object.entries(categories));
};
export default function EditModeShell({ children }: { children: ReactNode }) { export default function EditModeShell({ children }: { children: ReactNode }) {
const navigate = useNavigate(); const navigate = useNavigate();
const location = useLocation(); const location = useLocation();
@@ -48,7 +60,6 @@ export default function EditModeShell({ children }: { children: ReactNode }) {
// render reads it legally, and `revision` is the invalidation counter that // render reads it legally, and `revision` is the invalidation counter that
// re-derives everything the draft feeds to the UI. // re-derives everything the draft feeds to the UI.
const [store, setStore] = useState<DraftStore | null>(null); const [store, setStore] = useState<DraftStore | null>(null);
const typesRef = useRef<{ source: string; sha: string } | null>(null);
const [phase, setPhase] = useState<Phase>('authenticating'); const [phase, setPhase] = useState<Phase>('authenticating');
const [branch, setBranch] = useState<string>(DEFAULT_BRANCH); const [branch, setBranch] = useState<string>(DEFAULT_BRANCH);
const [resolved, setResolved] = useState<Record<'vi' | 'en', ResolvedContent> | null>(null); const [resolved, setResolved] = useState<Record<'vi' | 'en', ResolvedContent> | null>(null);
@@ -60,7 +71,7 @@ export default function EditModeShell({ children }: { children: ReactNode }) {
const [saveResults, setSaveResults] = useState<DocSaveResult[]>([]); const [saveResults, setSaveResults] = useState<DocSaveResult[]>([]);
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
const [saveStopped, setSaveStopped] = useState(false); const [saveStopped, setSaveStopped] = useState(false);
const [unionNote, setUnionNote] = useState<'ok' | 'failed' | null>(null); const [labelsUnavailable, setLabelsUnavailable] = useState(false);
const stripEditQuery = useCallback(() => { const stripEditQuery = useCallback(() => {
const params = new URLSearchParams(location.search); const params = new URLSearchParams(location.search);
@@ -123,7 +134,21 @@ export default function EditModeShell({ children }: { children: ReactNode }) {
} }
if (!bases) bases = bundledBase(); if (!bases) bases = bundledBase();
const created = new DraftStore(bases); // Rule 7's inputs. A failed read leaves the labels null: the save bar
// says the label check could not run, and the rule is skipped rather
// than guessed at from a bundle that may predate the branch.
let labels: CategoryLabels | null = null;
try {
const [viLabels, enLabels] = await Promise.all([
fetchDoc(LABEL_FILES.vi, branch),
fetchDoc(LABEL_FILES.en, branch),
]);
labels = { vi: categoryMap(viLabels.data), en: categoryMap(enLabels.data) };
} catch {
setLabelsUnavailable(true);
}
const created = new DraftStore(bases, labels);
const stored = sessionStorage.getItem(DRAFT_STORAGE); const stored = sessionStorage.getItem(DRAFT_STORAGE);
if (stored) { if (stored) {
@@ -136,13 +161,6 @@ export default function EditModeShell({ children }: { children: ReactNode }) {
} }
} }
try {
const file = await fetchTextFile(TYPES_FILE, branch);
typesRef.current = { source: file.text, sha: file.sha };
} catch {
typesRef.current = null;
}
if (cancelled) return; if (cancelled) return;
setStore(created); setStore(created);
setPhase(offline ? 'offline' : 'ready'); setPhase(offline ? 'offline' : 'ready');
@@ -271,7 +289,6 @@ export default function EditModeShell({ children }: { children: ReactNode }) {
} }
setSaving(true); setSaving(true);
setSaveStopped(false); setSaveStopped(false);
setUnionNote(null);
setSaveResults([]); setSaveResults([]);
const { results, stoppedEarly } = await saveDraft(store, (result) => { const { results, stoppedEarly } = await saveDraft(store, (result) => {
setSaveResults((prev) => [...prev, result]); setSaveResults((prev) => [...prev, result]);
@@ -280,20 +297,6 @@ export default function EditModeShell({ children }: { children: ReactNode }) {
const written = new Set(results.filter((r) => r.status === 'written').map((r) => r.id)); const written = new Set(results.filter((r) => r.status === 'written').map((r) => r.id));
const conflicted = results.filter((r) => r.status === 'conflict').map((r) => r.id); const conflicted = results.filter((r) => r.status === 'conflict').map((r) => r.id);
setConflicts((prev) => [...new Set([...prev.filter((id) => !written.has(id)), ...conflicted])]); setConflicts((prev) => [...new Set([...prev.filter((id) => !written.has(id)), ...conflicted])]);
// The third leg of §3.1: bring the unions to the ids whose documents
// landed — appended when a record was added, dropped when one was deleted.
const types = typesRef.current;
if (types) {
const union = await saveIdUnions(store, types, branch);
if (union) {
if (union.failed !== undefined) setUnionNote('failed');
else {
typesRef.current = { source: union.source!, sha: union.sha! };
setUnionNote('ok');
}
}
}
setSaving(false); setSaving(false);
refresh(store); refresh(store);
}, [store, phase, refresh, branch]); }, [store, phase, refresh, branch]);
@@ -394,7 +397,7 @@ export default function EditModeShell({ children }: { children: ReactNode }) {
saving={saving} saving={saving}
saveStopped={saveStopped} saveStopped={saveStopped}
saveResults={saveResults} saveResults={saveResults}
unionNote={unionNote} labelsUnavailable={labelsUnavailable}
draftRestored={draftRestored} draftRestored={draftRestored}
branch={branch} branch={branch}
getConflictFields={(id) => store.conflictFields(id)} getConflictFields={(id) => store.conflictFields(id)}
+10 -186
View File
@@ -16,7 +16,7 @@ import profileJson from '../data/profile.json';
import projectsJson from '../data/projects.json'; import projectsJson from '../data/projects.json';
import skillsJson from '../data/skills.json'; import skillsJson from '../data/skills.json';
import { collectContentIssues } from './validate'; import { collectContentIssues } from './validate';
import type { ContentIssue, ContentStructures } from './validate'; import type { CategoryLabels, ContentIssue, ContentStructures } from './validate';
import type { ContentEn, ContentVi } from './dict-types'; import type { ContentEn, ContentVi } from './dict-types';
import type { Language } from '../types/index'; import type { Language } from '../types/index';
@@ -98,7 +98,6 @@ export function entityOfDoc(id: DraftDocId): TextEntity | null {
} }
export const PROXY_BASE = '/api/content/'; export const PROXY_BASE = '/api/content/';
export const TYPES_FILE = 'src/types/index.ts';
export function proxyUrl(file: string, ref: string): string { export function proxyUrl(file: string, ref: string): string {
return `${PROXY_BASE}${file}?ref=${encodeURIComponent(ref)}`; return `${PROXY_BASE}${file}?ref=${encodeURIComponent(ref)}`;
@@ -228,13 +227,6 @@ export async function fetchDoc(file: string, branch: string): Promise<DocBase> {
}; };
} }
export async function fetchTextFile(file: string, branch: string): Promise<{ text: string; sha: string }> {
const res = await fetch(proxyUrl(file, branch));
if (!res.ok) throw new Error(`GET ${file}: ${res.status}`);
const json = (await res.json()) as { content?: string; sha?: string };
return { text: decodeBase64(json.content ?? ''), sha: String(json.sha ?? '') };
}
export type PutResult = export type PutResult =
| { ok: true; sha: string } | { ok: true; sha: string }
| { ok: false; status: number; message: string }; | { ok: false; status: number; message: string };
@@ -287,16 +279,6 @@ export function putDoc(
return putBase64(file, encodeBase64(`${JSON.stringify(data, null, 2)}\n`), message, lastCommitSha, branch); return putBase64(file, encodeBase64(`${JSON.stringify(data, null, 2)}\n`), message, lastCommitSha, branch);
} }
export function putTextFile(
file: string,
text: string,
message: string,
lastCommitSha: string,
branch: string,
): Promise<PutResult> {
return putBase64(file, encodeBase64(text), message, lastCommitSha, branch);
}
// Offline fallback (§5.1): the bundled build-time documents, flagged stale in // Offline fallback (§5.1): the bundled build-time documents, flagged stale in
// the UI, save disabled — the draft is never initialized from a bundle that // the UI, save disabled — the draft is never initialized from a bundle that
// might be older than master when the proxy is reachable. // might be older than master when the proxy is reachable.
@@ -317,115 +299,6 @@ export function bundledBase(): Record<DraftDocId, DocBase> {
}; };
} }
// --- id unions (§3.1) ------------------------------------------------------------
// Adding a content item is three edits: a union member, a structure record,
// its Vietnamese text. Deleting one is the mirror image: the record and its
// text go, and the union member must go with them. The editor does every leg
// — once the content documents land, saveIdUnions brings each union in
// src/types/index.ts to exactly the ids its document carries.
const UNION_SPECS: ReadonlyArray<{ union: string; ids: (s: ContentStructures) => string[] }> = [
{ union: 'ProjectId', ids: (s) => s.projects.map((p) => p.id) },
{ union: 'ExperienceId', ids: (s) => s.experience.map((e) => e.id) },
{ union: 'SkillGroupId', ids: (s) => s.skills.map((g) => g.id) },
{ union: 'PhilosophyId', ids: (s) => s.profile.philosophy.map((p) => p.id) },
];
// A union is read as a block — `export type X =` followed by its ` | 'id'`
// member lines — never as a substring search: an id slug can legitimately
// appear elsewhere in the same file (ProjectCategory carries slugs that also
// read as project ids), and a substring test would silently skip that leg. An
// emptied union (`never`, the state an emptied document leaves) reads as an
// empty member list, so a record added on top of it is appended back. Any
// other shape (a one-line union) is reported as unpatchable, never corrupted.
type UnionBlock = { union: string; members: string[]; from: number; to: number };
const MEMBER_LINE = /^[ \t]*\| '([^']+)'[ \t]*;?[ \t]*\r?\n?$/;
const CLOSING_LINE = /^[ \t]*;[ \t]*\r?\n?$/;
// One line of the source including its terminator, or null at end of file.
function nextLine(source: string, from: number): { text: string; end: number } | null {
if (from >= source.length) return null;
const at = source.indexOf('\n', from);
const end = at < 0 ? source.length : at + 1;
return { text: source.slice(from, end), end };
}
// `from`/`to` are the exact span of the declaration, so nothing else in the
// file is ever rewritten.
function readUnionBlock(source: string, union: string): UnionBlock | null {
const never = new RegExp(`^export type ${union} = never;\\r?\\n?`, 'm').exec(source);
if (never) return { union, members: [], from: never.index, to: never.index + never[0].length };
const header = new RegExp(`^export type ${union} =\\r?\\n`, 'm').exec(source);
if (!header) return null;
const from = header.index;
let pos = from + header[0].length;
const members: string[] = [];
for (;;) {
const line = nextLine(source, pos);
if (!line) break;
const member = MEMBER_LINE.exec(line.text);
if (!member) break;
members.push(member[1]);
pos = line.end;
}
if (members.length === 0) return null;
const closing = nextLine(source, pos);
if (closing && CLOSING_LINE.test(closing.text)) pos = closing.end;
return { union, members, from, to: pos };
}
// An emptied union is `never`, which keeps `Record<never, T>` valid against an
// empty document.
function renderUnion(union: string, members: readonly string[], eol: string): string {
if (members.length === 0) return `export type ${union} = never;${eol}`;
const body = members.map((id) => ` | '${id}'`).join(eol);
return `export type ${union} =${eol}${body};${eol}`;
}
// One pass per union: surviving members keep their order, removed ids are
// dropped, added ids follow the document order. Null when a union's shape is
// not the one the editor writes.
export function applyUnionChanges(
source: string,
changes: { union: string; add: string[]; remove: string[] }[],
): string | null {
// git stores LF; a Windows checkout reads CRLF. A patch keeps the line
// ending the file already uses, so the commit the owner reviews is one line.
const eol = source.includes('\r\n') ? '\r\n' : '\n';
let out = source;
for (const change of changes) {
const block = readUnionBlock(out, change.union);
if (!block) return null;
const removed = new Set(change.remove);
const members = block.members.filter((id) => !removed.has(id));
for (const id of change.add) if (!members.includes(id)) members.push(id);
out = `${out.slice(0, block.from)}${renderUnion(change.union, members, eol)}${out.slice(block.to)}`;
}
return out;
}
// Ids whose documents have landed but whose union does not match them:
// missing members to append, stale members to drop. committedStructures() reads
// the post-PUT base, so a document that has not landed keeps the branch's ids
// and never reads as stale.
export function diffIdsWithUnions(
store: DraftStore,
typesSource: string,
): { added: { union: string; id: string }[]; removed: { union: string; id: string }[] } {
const structures = store.committedStructures();
const added: { union: string; id: string }[] = [];
const removed: { union: string; id: string }[] = [];
for (const spec of UNION_SPECS) {
const block = readUnionBlock(typesSource, spec.union);
if (!block) continue;
const live = new Set(spec.ids(structures));
for (const id of live) if (!block.members.includes(id)) added.push({ union: spec.union, id });
for (const id of block.members) if (!live.has(id)) removed.push({ union: spec.union, id });
}
return { added, removed };
}
// --- the store --------------------------------------------------------------------- // --- the store ---------------------------------------------------------------------
export type SavedDraft = { export type SavedDraft = {
@@ -502,7 +375,14 @@ export class DraftStore {
// is published and fixed (E3). // is published and fixed (E3).
private created = new Set<string>(); private created = new Set<string>();
constructor(bases: Record<DraftDocId, DocBase>) { // Rule 7 needs the category labels of the branch being edited. They are
// read-only documents, fetched by EditModeShell beside the rest of the
// session (spec-v5 §5.4); `null` is the offline state — the rule is then
// skipped, never guessed at.
private categoryLabels: CategoryLabels | null;
constructor(bases: Record<DraftDocId, DocBase>, categoryLabels: CategoryLabels | null) {
this.categoryLabels = categoryLabels;
for (const meta of DRAFT_DOCS) { for (const meta of DRAFT_DOCS) {
this.base.set(meta.id, bases[meta.id]); this.base.set(meta.id, bases[meta.id]);
this.origin.set(meta.id, bases[meta.id].data); this.origin.set(meta.id, bases[meta.id].data);
@@ -549,22 +429,6 @@ export class DraftStore {
} as unknown as ContentStructures; } as unknown as ContentStructures;
} }
baseDataOf(id: DraftDocId): unknown {
return this.base.get(id)!.data;
}
// Structures as they would exist in master after the already-written PUTs —
// the union patch only covers ids whose documents actually landed.
committedStructures(): ContentStructures {
const baseData = (id: DraftDocId) => this.base.get(id)!.data;
return {
profile: baseData('profile'),
skills: baseData('skills'),
experience: baseData('experience'),
projects: baseData('projects'),
} as unknown as ContentStructures;
}
draftTexts(): { vi: ContentVi; en: ContentEn } { draftTexts(): { vi: ContentVi; en: ContentEn } {
return { return {
vi: { vi: {
@@ -584,7 +448,7 @@ export class DraftStore {
validate(): ContentIssue[] { validate(): ContentIssue[] {
const texts = this.draftTexts(); const texts = this.draftTexts();
return collectContentIssues(this.draftStructures(), texts.vi, texts.en); return collectContentIssues(this.draftStructures(), texts.vi, texts.en, this.categoryLabels);
} }
// --- text documents ----------------------------------------------------------- // --- text documents -----------------------------------------------------------
@@ -1147,43 +1011,3 @@ export async function saveDraft(
} }
return { results, stoppedEarly: false }; return { results, stoppedEarly: false };
} }
// The third leg of §3.1: once the documents that add or drop ids have landed,
// bring their unions in src/types/index.ts to exactly those ids so the next CI
// build compiles. Returns the updated source/sha, or null when nothing needs
// changing (an unpatchable shape or a rejected PUT is reported to the EditBar,
// and the owner finishes that edit in Gitea).
export async function saveIdUnions(
store: DraftStore,
types: { source: string; sha: string },
branch: string,
): Promise<{
added: { union: string; id: string }[];
removed: { union: string; id: string }[];
source?: string;
sha?: string;
failed?: number;
} | null> {
const { added, removed } = diffIdsWithUnions(store, types.source);
if (added.length === 0 && removed.length === 0) return null;
const grouped = new Map<string, { add: string[]; remove: string[] }>();
const bucket = (union: string) => {
const existing = grouped.get(union);
if (existing) return existing;
const fresh = { add: [] as string[], remove: [] as string[] };
grouped.set(union, fresh);
return fresh;
};
for (const { union, id } of added) bucket(union).add.push(id);
for (const { union, id } of removed) bucket(union).remove.push(id);
const source = applyUnionChanges(
types.source,
[...grouped].map(([union, change]) => ({ union, ...change })),
);
if (source === null) return { added, removed, failed: 0 };
const summary = [...added.map((a) => `+${a.id}`), ...removed.map((r) => `-${r.id}`)].join(', ');
const message = `content: update id union members (${summary})`;
const res = await putTextFile(TYPES_FILE, source, message, types.sha, branch);
if (!res.ok) return { added, removed, failed: res.status };
return { added, removed, source, sha: res.sha };
}
+5 -1
View File
@@ -122,7 +122,11 @@ const structures = {
// Cross-document rules run at module load: a malformed content document fails // Cross-document rules run at module load: a malformed content document fails
// the build here, in CI, and in the browser — never silently half-renders. // the build here, in CI, and in the browser — never silently half-renders.
validateContent(structures, contentVi, contentEn); // Rule 7 reads the category labels straight out of the UI tree built above.
validateContent(structures, contentVi, contentEn, {
vi: uiVi.projects.categories,
en: uiEn.projects.categories,
});
// Missing en fields fall back to vi per field; arrays are atomic — a whole // Missing en fields fall back to vi per field; arrays are atomic — a whole
// array is replaced or inherited, never merged item by item (§3.2). // array is replaced or inherited, never merged item by item (§3.2).
+1 -2
View File
@@ -66,8 +66,7 @@
"mergeHint": "written to the branch — merge into master to deploy", "mergeHint": "written to the branch — merge into master to deploy",
"offline": "offline — showing bundled content, save disabled", "offline": "offline — showing bundled content, save disabled",
"draftRestored": "draft restored from this session", "draftRestored": "draft restored from this session",
"unionNote": "id unions in src/types/index.ts updated to match the saved content", "labelsUnavailable": "category labels could not be read from this branch — the label check was skipped",
"unionFailed": "could not update src/types/index.ts — finish that edit in Gitea",
"appearsHome": "home", "appearsHome": "home",
"appearsResume": "resume PDF", "appearsResume": "resume PDF",
"appearsOn": "appears on", "appearsOn": "appears on",
+1 -2
View File
@@ -66,8 +66,7 @@
"mergeHint": "đã ghi lên branch — merge vào master để deploy", "mergeHint": "đã ghi lên branch — merge vào master để deploy",
"offline": "ngoại tuyến — đang hiển thị nội dung đóng gói, không lưu được", "offline": "ngoại tuyến — đang hiển thị nội dung đóng gói, không lưu được",
"draftRestored": "bản nháp đã khôi phục từ phiên này", "draftRestored": "bản nháp đã khôi phục từ phiên này",
"unionNote": "các id union trong src/types/index.ts đã được cập nhật theo nội dung đã lưu", "labelsUnavailable": "không đọc được nhãn danh mục từ nhánh này — bước kiểm tra nhãn đã được bỏ qua",
"unionFailed": "không cập nhật được src/types/index.ts — hãy hoàn tất sửa trong Gitea",
"appearsHome": "Trang chủ", "appearsHome": "Trang chủ",
"appearsResume": "CV PDF", "appearsResume": "CV PDF",
"appearsOn": "xuất hiện tại", "appearsOn": "xuất hiện tại",
+31 -1
View File
@@ -27,6 +27,12 @@ export type ContentStructures = {
projects: ProjectStructure[]; projects: ProjectStructure[];
}; };
// Rule 7 reads the category labels, which live in the UI group files — a
// read-only part of the dictionary tree (spec-v4-data-organization §4). They
// are passed in as a slice rather than owned here: the load-time and CI
// callers have the whole tree, the edit session fetches only this group.
export type CategoryLabels = { vi: Record<string, unknown>; en: Record<string, unknown> };
const hasHtml = (value: string) => value.includes('<') || value.includes('>'); const hasHtml = (value: string) => value.includes('<') || value.includes('>');
// Walks every string value of a text document, collecting the document paths // Walks every string value of a text document, collecting the document paths
@@ -70,6 +76,7 @@ export function collectContentIssues(
structures: ContentStructures, structures: ContentStructures,
vi: ContentVi, vi: ContentVi,
en: ContentEn, en: ContentEn,
categoryLabels: CategoryLabels | null,
): ContentIssue[] { ): ContentIssue[] {
const issues: ContentIssue[] = []; const issues: ContentIssue[] = [];
@@ -164,6 +171,28 @@ export function collectContentIssues(
} }
} }
// Rule 7: every category a project uses has a non-empty label in both
// languages (spec-v5 D4). The category union is generated from these very
// values, so the failure worth catching is not an unknown category but a
// badge that renders empty. `null` means the labels are not available to
// this caller — the edit session's read-only fetch failed — and the rule is
// skipped, never guessed at.
if (categoryLabels) {
const used = new Set(structures.projects.map((project) => project.category));
for (const lang of ['vi', 'en'] as const) {
const labels = categoryLabels[lang];
for (const category of used) {
const label = labels[category];
if (typeof label !== 'string' || label.trim() === '') {
issues.push({
path: `src/i18n/locales/${lang}/ui/projects.json: categories.${category}`,
message: 'category used by a project has no label in this language',
});
}
}
}
}
return issues; return issues;
} }
@@ -171,8 +200,9 @@ export function validateContent(
structures: ContentStructures, structures: ContentStructures,
vi: ContentVi, vi: ContentVi,
en: ContentEn, en: ContentEn,
categoryLabels: CategoryLabels | null,
): void { ): void {
const issues = collectContentIssues(structures, vi, en); const issues = collectContentIssues(structures, vi, en, categoryLabels);
if (issues.length > 0) { if (issues.length > 0) {
const detail = issues.map((i) => ` ${i.path}: ${i.message}`).join('\n'); const detail = issues.map((i) => ` ${i.path}: ${i.message}`).join('\n');
throw new Error(`content validation failed (${issues.length} issue(s)):\n${detail}`); throw new Error(`content validation failed (${issues.length} issue(s)):\n${detail}`);
+12 -37
View File
@@ -4,43 +4,18 @@ export type Palette = 'red' | 'blue';
export type SocialId = 'github' | 'linkedin' | 'email' | 'telegram'; export type SocialId = 'github' | 'linkedin' | 'email' | 'telegram';
export type ProjectCategory = // Content ids and the category values a project uses are generated from the
| "software-engineering" // structure documents by scripts/generate-content-types.ts (spec-v5): the union
| "logistics" // is exactly the document, so a record delete cannot leave a stale member and a
| "ai-ml" // text entry for it is a tsc error. Type-only re-export — erased at emit, no
| "computer-vision" // runtime import.
| "architecture" export type {
| "experiment"; ExperienceId,
PhilosophyId,
// Stable id unions (spec-v4 §3.1). Text dictionaries are type-safe only against ProjectCategory,
// closed unions: adding a content item means adding a union member, a structure ProjectId,
// record, and its Vietnamese text — tsc catches a missing text entry, the SkillGroupId,
// validator (src/i18n/validate.ts) catches id mismatches across documents. } from './content-ids';
// SkillGroupId and PhilosophyId are internal keys and never appear in URLs.
export type ProjectId =
| 'iot-dws-integration'
| 'awb-detection';
export type ExperienceId =
| 'open-to-work'
| 'relax-gap'
| 'lazada-senior-swe'
| 'nexts-founder'
| 'sap-senior-swe';
export type SkillGroupId =
| 'software-engineering'
| 'system-architecture'
| 'ai-ml'
| 'infrastructure'
| 'engineering-practices';
export type PhilosophyId =
| 'build-for-the-real-problem'
| 'think-in-systems'
| 'measure-impact'
| 'keep-learning'
| 'business-domain-knowledge-is-a-key-of-success';
// Page manifests (spec-v4-data-organization §5): one per route plus the // Page manifests (spec-v4-data-organization §5): one per route plus the
// synthetic resume consumer. A manifest claims which joined records a page // synthetic resume consumer. A manifest claims which joined records a page