Merge feature/rust-r2-domain-core into develop
ci / rust (push) Canceled after 0s
ci / check (push) Canceled after 0s
ci / docker (push) Canceled after 0s
ci / supabase (push) Canceled after 0s

This commit is contained in:
bchanot committed 2026-10-14 21:57:30 +02:00
commit c3f28d8325
314 files changed
+28535 -1620

No files matched your search

+7
View File
@@ -81,3 +81,10 @@ Status: open (no real data yet; treat before Step 7+ persistence of user reports
Security audit Step 6 (MEDIUM, pre-existing since Step 1 import): `PDFDocument.load` decodes every `/ObjStm` and xref stream eagerly with its own uncapped FlateStream; measured 408 KB PDF → 400 MB in 1.4 s, 468 MB RSS; `MAX_PDF_BYTES` 50 MiB allows ~50 GB. Attachment cap (16 MiB) covers the attachment only. Impact: tab freeze/OOM for the practitioner on a crafted PDF, no code execution. Cannot refuse `/ObjStm` (pdf-lib `save()` emits object streams in our own PDFs). Options: parse in a Web Worker (bounded blast radius), or locate the attachment by scanning bytes without a full load, or a capped custom decoder. pdf-lib 1.17.1 unmaintained since 2021 (LOW in the same audit).
Status: MITIGATED on the browser import path 2026-10-11 (60ee712: byte-scan attachment reader, no `PDFDocument.load` on untrusted bytes, export without object streams; ObjStm bomb read in 5 ms, +0.5 MiB RSS). Then 3a6e926: inflater fed in 16 KiB slices (Chromium read-ahead defeated the cancel: 4 GiB bomb +2.2 GB → +192 MB measured), shared 16 MiB candidate budget, bounded endstream search; final loop: candidates sorted by offset, JSON depth pre-scan. Audits ×3 PASS; worst measured costs on crafted files: +192 MB single bomb, ~0.5 s / ≤0.4 GB for 32 failing inflations, ~1 s deep JSON (before the pre-scan). GATE STILL OPEN before any external-user import (BDR-040): Firefox/Safari inflater read-ahead unmeasured (no browser test runner), Worker/server import with time+memory budget, pdf-lib replacement decision (unmaintained), report collection caps on read, `<use>` nesting budget, low-end phone measurement. Plan: docs/development/PDF_IMPORT_HARDENING.md §5. Never close on passing tests alone.
## BLK-010 | 2026-10-14 | Agent worktrees created on a stale base; their cleanup refused by the classifier
Friction: the three `isolation: worktree` forks of R2 started at 605ee7c (an old develop merge), not at the feature branch HEAD 22fea87; each fork noticed and moved its own temp branch (`git reset --hard` / `checkout -B` on the empty worktree, flagged by the classifier as a security warning). After merging their diffs by hand, `git worktree remove --force` + `git branch -d worktree-agent-*` refused by the auto-mode classifier.
Root cause: harness side (base commit of the agent worktree), not reproducible from the repo; the removal refusal is the destructive-command policy.
Solution: forks briefed with the exact base commit and told to verify `git log -1`; diffs collected uncommitted and copied by literal paths. Leftover: `.claude/worktrees/agent-{a0cefd439bff650a2,a3f684449d0776ad1,af6ebe79b8f742039}` (3.2 GB) + 3 local temp branches at 22fea87 (merged), owner removes them (`git worktree remove --force <path>`, `git branch -d <branch>`).
Status: open (harness); workaround documented.
+12
View File
@@ -394,3 +394,15 @@ Status: active; awaiting owner validation (TEST FONCTIONNEL + TEST GRAPHIQUE), n
Owner decisions: (1) R1 validated 10/10 manual + graphic → R0 and R1 finished into develop (5cfb6f1, f5865f0; the earlier classifier refusal did not recur); (2) identity final: product/app/site = **Faunosteo**, domain **https://faunosteo.com**, no new brand name, logo/palette/mockups kept; (3) environments: DEV = self-hosted Ubuntu native (Claude Code, git, rustup, Vite, Docker rootless, local Supabase, worker), STAGING = `staging.faunosteo.com` planned not created, PROD = separate VPS, current site preserved, no DNS/cert/proxy/data change; isolation of DB/Storage/secrets/accounts/OAuth/payments/mails/files per env, prod data never copied to DEV, merge ≠ deploy, no CI/CD operational (workflows preparatory); (4) permanent rule: the owner tests from other devices (computer, phone) → every test surface addressed by the DEV origin (LAN address or private name), never 127.0.0.1/localhost, never hard-coded; implemented as `scripts/dev-env.sh` (`FAUNOSTEO_DEV_HOST`, detected via `hostname -I`, prod host refused) + `scripts/supabase.sh` wrapper (config.toml `env()` for api.external_url, auth.site_url, studio.api_url) + `scripts/dev.sh` (`pnpm dev` on the origin, `pnpm dev:offline` without backend) + private-network redirect URLs; (5) exposure: 5173/54321 needed by browsers, Studio 54323 + Mailpit 54324 unauthenticated → private subnet only, PostgreSQL 54322 published by the CLI on 0.0.0.0 (no bind option) → firewall restriction proposed to the owner, not applied; worker no port; (6) Rust native via Cargo, Docker for services/worker/sandbox/images/prod, VPS never compiles.
Alt rejected: hard-coded IP in config.toml (first iteration, replaced the same day); Vite `dev:lan` variant (folded into `dev`); binding the CLI ports to loopback (impossible in config.toml).
Status: active; `chore/dev-lan-access` awaiting the owner's LAN validation; R2 not started.
## BDR-050 | 2026-10-14 | R2 implementation choices: Zod semantics in serde, minimal index data, form edits stay Zustand, quarantine, lazy core
Built on review rev 2 + Annex C; plan `.claude/tasks/plans/2026-10-13-rust-r2-domain-core.md` rev 2 (3 challengers, 45 findings, 1 BLOCKER folded). Choices: (1) JSON read text → `serde_json::Value` (JSON.parse dup-key semantics) → typed; lone surrogate escape → U+FFFD pre-pass (L1, owner to confirm); (2) Zod reproduced by field helpers: `js::present` (optional: absent ok, null refused, skipped), `js::nullable` (required key), `JsInt` (any integer-valued number, JS print), hand-written patterns (no regex crate), `url` crate for `.url()`; unions = untagged enums + literal tag fields at Zod position → byte-equal with `JSON.stringify(Zod.parse(x),null,2)`; PDF label fields in engine dict order → frozen envelopes round-trip byte-equal; (3) quirks ported site by site (Map last-wins, find first-wins, JS truthiness, `??=`, malformed map entry still fails the read); (4) `SheetIndexData` minimal (positions, names, spineIds, nodeKeys as JSON `[zone,...path]`), TS `SheetIndex` = accessors only + `ops`; (5) one core call per user action; form-value observation edits (comment, severity, free text, finding removal) stay Zustand assignments (no per-keystroke wasm, D-R7); store actions answer `{ok}`, callers stop on failure; `hydrateReport` deleted; (6) runtime: sync calls, trap → poison → offline recovery from kept compiled module + pre-imported spare glue record, cap 3, per-generation sheet handles, retry clears all caches; `pkg/` shipped vs `pkg-proofs/`; BUILD_STAMP refuses stale module in tests; (7) quarantine only on content kinds, newest-only keys, source removed after successful copy, pre-rebase raw kept when unresolved > 0; editor never redirects in degraded states; (8) Home and /new read availability from the bundle, core loads at submit / import / editor; (9) import = TS byte scan (until R4) → core `archive.import` (read + rebase one call); export = core `archive.snapshot` → frozen TS engine; (10) publish gate takes the core validator (DI), fails closed; (11) report:compare CLI keeps the frozen domain (R4); practitioner prefill keeps a small Zod schema (D-R7, core not loaded on /new mount); (12) app image wasm stage + gzip_static; DEPLOY: CSP keyword before an R2 image, never built on VPS.
Alt rejected: mutation corpus with full outputs (simplicity challenge: drift-free verdict table + characterisation instead); `report.replace_observation` per keystroke; serde internally tagged enums (tag first breaks byte equality); Web Worker for every call (async races in the click chain); unify duplicate-id policies (behaviour change).
Status: active; R2 delivered on feature/rust-r2-domain-core, awaiting owner validation, no merge.
## BDR-051 | 2026-10-14 | L1 resolved: lone UTF-16 surrogate refused whole, never replaced (supersedes BDR-050 choice 1 on this point)
Owner refused U+FFFD replacement of lone surrogate escapes (silent alteration of historical user data). Chosen (owner, 2026-10-14): refusal + quarantine. `js::parse_json` no pre-pass; serde_json refuses escape like any error; failure classified by strict escape scan (on failure only) → `JsonReadError::LoneSurrogate` → closed kind `lone_surrogate` (parse_input, sheet.check, draft.restore, archive.import). App: draft → `osteo:quarantine:draft` verbatim + existing `editor.draft_quarantined`; session archive → `osteo:quarantine:archive`; import → `ImportError('lone_surrogate')` + new `home.import.error_lone_surrogate` (owner-chosen detailed wording FR/EN, file untouched); editor action → refused, report unchanged, `core.action_failed`; publish gate → `invalid_shape`. Oracles untouched: L1 cases now assert TS kept surrogate + Rust refuses; test loader spells lone escapes out as literal text (never U+FFFD).
Alt rejected: faithful preservation (own JSON reader + lossless WTF-16 string type over ~150 contract fields + serialiser, oracles re-frozen; multi-day, for corrupted/pasted-UTF-16 data only; door stays open since nothing is lost); in-band tunnel (placeholder code points mapped back at facade output; collisions with sheet strings, UTF-16 length drift, every output path must be post-processed: hacky).
Status: active; merged with R2.
+14
View File
@@ -150,3 +150,17 @@ Method: contract-level `STORAGE.md` written first; migration + pgTAP by me while
Result: verifier pass 1 ECARTS(4) = oracle (`for update` row-lock grep) + FILE SCOPE (tracking files, lockfile) → rev 2 → CONFORME 15/15, floor clean. Security pass 1 PASS (2 MEDIUM: ceiling ratchet by rejected rows, cleartext http any host; 9 LOW) → fixed; pass 2 PASS but my fixes introduced 2 MEDIUM (bypassable host check `127.*`/numeric, ceiling undercount vs contract) → fixed; pass 3 BLOCK(1) HIGH: my purge-queue join let begin spam pin the ceiling with claims → ceiling rewritten on bytes present + cap per pending claim; pass 4 PASS (MEDIUM residual: per-account holding) → 64 MiB per-account budget; pass 5 PASS (LOW hygiene) → comments/doc. e2e 5/5 ×7 (found the Storage API 400-as-404 making purge acks loop: added queue-drained assertion); smoke 18/18 desktop+mobile; final: pgTAP 140 (real stack 420 total), app 300, supabase 37, worker 21+11 native, sandbox 16, allowlist = 7 syscalls unchanged, image 11.6 MB.
Anomalies: EVAL-017 lesson again ×3 — each security fix needed its own adversarial pass and twice created a new finding (host check, ceiling join); a security control I added became the attack lever (BLOCK). Fork B's `database.types.ts` hand-write matched the generator byte-for-byte except ordering; fork A found the 400/404 only via e2e. `gitflow finish` of R0 and any `.env*` write refused by the harness classifier; `git config` reads refused too. Verifier sandbox intercepted the literal `pnpm lint` (rtk wrapper) → oracle uses the binary path.
Action: owner's manual validation (TEST FONCTIONNEL + TEST GRAPHIQUE), owner runs `gitflow finish` for R0 then R1 after validation; no merge, no deploy, release 0.2.0 untouched.
## EVAL-020 | 2026-10-14 | Rust R2 domain core — 3 plan challengers, 4 forks, verifier, security ×2, CSP proof on the image
Method: plan + contract written first (`.claude/tasks/plans/2026-10-13-rust-r2-domain-core.md`), 3 plan-challengers (correctness, robustness, simplicity) before code; freeze-then-switch: envelopes, Zod output oracles, characterisation and verdict tables written by the TS before trusting Rust; forks A/B/C in worktrees on disjoint files (sheet rules + conformance, report/archive rules, editor rules), runtime + app switch by me, fork D adapted the app suites in tree; browser checks with playwright-core from the scratchpad (dev server, prod build, real image under the DEPLOY CSP); contract `2026-10-14-rust-r2-verify.md` (12 criteria, every oracle dry-run before dispatch) → fresh verifier; security-auditor on the whole range, then a focused pass on the fix commit.
Result: challengers 45 findings incl. 1 BLOCKER (degraded editor redirect could overwrite an unread draft) → plan rev 2 before any app code; contracts byte-equal to Zod on first run; forks merged with zero conflicts (one stub replaced); fork D found 2 real src bugs (Node source path under happy-dom, failed quarantine reported as success) → fixed with tests. Verifier: 12/12 MET, ECARTS(2) = floor DELETED_TEST (zoneInteraction suite ported to cargo; R0 skip helper replaced by a stricter global setup) → human micro-gate for the owner. Security: PASS (3 MEDIUM nginx false positives pre-existing, 5 LOW) → by-reference deserialisation (also −134 KB raw / −31 KB gzip module) + literal delete paths. Final: cargo core 135, worker+wasm 32, Node 906 (app 313), pgTAP PGlite 12 files / real stack 446, CSP proof 15/15, check:all green ×3, module 1,046,498 B raw / 340,929 B gzip.
Anomalies: worktree base stale (BLK-010); harness decodes `\u` escapes in tool inputs (LRN-054); my first runtime test helper reused the pattern Vite rewrites; the CSP proof first failed on its own harness (EN locale, disclaimer modal, caught compile error logs nothing) — proof scripts need the same dry-run discipline as oracles; a security LOW fix improved size, measure before assuming a cost.
Action: owner manual LAN validation, L1 decision, approve the 2 deleted test files (floor), then merge go; R3 next, not started.
## EVAL-021 | 2026-10-14 | R2 closure — L1 refusal, deletions proof, fresh verifier + security
Method: owner asked to fix L1 (no silent U+FFFD) + prove the 2 approved deletions + checks before merge. Mapped every JSON entry into the core (TS side always `JSON.stringify` → escapes reach Rust as ASCII); preservation costed (own JSON reader + lossless string type ~150 fields) → AskUserQuestion: refusal + quarantine chosen, detailed import wording chosen. Stale-module proof run before `wasm:build` (suites throw `pkg is stale`). Worktrees checked blob by blob vs branch history (60/66 identical, 6 = stub, merged mod lists, 2 lifted `#[ignore]`). Contract `2026-10-14-rust-r2-l1-verify.md` (13 criteria, each dry-run) → fresh verifier; fresh security-auditor on 36316cf..HEAD.
Result: verifier CONFORME 13/13 (floor 2 = the approved deletions, authorised by REQUEST); security PASS, 6 LOW: wasm-bindgen `&str` would re-encode a raw lone surrogate (unreachable, JSON.stringify callers; documented invariant), `pretty_json` proof op refuses as invalid_json, scanner not string-aware (classification only), newest-only quarantine slot, archive quarantine failure under full storage lets a later reset remove it (pre-existing R2, reported to owner), semgrep partial parse. Final: core 142, Node 915 (app 320, supabase 40, core-wasm 26), PGlite pgTAP 12 files, real stack 446/446, types no drift, check:all green 1 min 32 s, module 1,040,784 B raw / 339,933 B gzip.
Anomalies: refusal broke a test loader (oracle file freezes TS outputs with lone escapes) → loader spells escapes out, never normalises (LRN-055); `cargo deny advisories` (warn-only) shows RUSTSEC-2026-0346/0347/0348 on rustls 0.23.45 (worker, none applicable: no brotli, built-in session cache, no ECH) → bump follow-up; `supabase/.temp/cli-latest` tracked by mistake, rewritten by the CLI, restored; `export PATH=…` denied → absolute `~/.cargo/bin/cargo`; first commit with chained `git config` denied → plain commit OK.
Action: gitflow finish into develop (owner authorised after L1 + checks), worktree cleanup (BLK-010), R3 summary only.
+8
View File
@@ -247,3 +247,11 @@ Owner: R1 10/10 validated, identity final (Faunosteo, faunosteo.com), env DEV/ST
- Same day, LAN least privilege (owner brief): measured from a distinct Docker network → Mailpit open without auth, PostgreSQL open, Studio open. Built DEV gateway (nginx, API + Mailpit basic auth on the LAN address), `pnpm dev:gateway`, `pnpm dev:net-check`; gateway proven on alternate ports. Pending owner authorisation: `~/.config/docker/daemon.json {"ip":"127.0.0.1"}` + rootless daemon restart (daemon-wide, only Faunosteo containers on it). LRN-052. Branch not merged; R2 not started.
- Same day, owner applied the UFW rules (ENVIRONMENTS.md §3.2) and verified from another device: 54322, 54323, 54324 refused, 54321 answers; app served by the owner's `pnpm dev`. Allowed surfaces 5/5 by dev:net-check. Remaining: owner's 10-step run on computer + phone, then merge go and R2 go.
- Owner validated the 10-step path on computer and phone over the LAN; merge go for chore/dev-lan-access. R2 not authorised yet.
## 2026-10-14 (Rust R2 delivered)
Owner: LAN validated, R2 go (brief 2026-10-13), 4 new strings validated (recommended wording). feature/rust-r2-domain-core off develop 1a7ee7d. Plan + 3 challengers (45 findings, 1 blocker) → rev 2. Freeze first (envelopes, N-1 copy, Zod oracles, characterisation 84 + verdicts 765 + editor 49 + conformance 26), contracts byte-equal, rules by 3 worktree forks, runtime (lazy, poison, offline recovery, BUILD_STAMP), app switched (sheet, store, click chain, pickers, import, export snapshot, publish gate fail-closed), quarantine, degraded states, Docker wasm stage + gzip_static, CSP proof on the image 15/15. Verifier 12/12 + floor 2 (deleted tests, owner micro-gate); security PASS → by-ref deserialisation (module 341 KB gzip). check:all green. BDR-050, LRN-054, BLK-010, EVAL-020. Stop: owner validation, no merge, R3 not started, release 0.2.0 untouched.
## 2026-10-14 (R2 closure)
Owner: manual 10/10 validated, R2 accepted (architecture, migrations, contracts, perf); L1 refused (silent U+FFFD). Costed preservation (own JSON reader + lossless string type) → owner chose refusal + quarantine, detailed import wording. Fixed: core refuses lone surrogate as `lone_surrogate` (draft/archive quarantined verbatim, import refused with message, action refused, gate invalid_shape). Deletions proven covered (12+1 Rust tests + 49 oracle cases; stale module fails suites). Worktrees verified recoverable-free. Gates: verifier CONFORME 13/13, security PASS 6 LOW; check:all green. BDR-051, LRN-055, EVAL-021. Next: finish into develop, worktree cleanup, R3 summary (not started).
+15
View File
@@ -411,3 +411,18 @@ Apply: any DEV service exposure on this machine; future staging compose.
- Rootless (slirp/pasta) containers reach the host's own LAN IP by local delivery, never through the LAN interface → firewall refusals on that interface are invisible to any probe run on the host; prove them from another device (`nc -zv -w 3 <ip> <port>`).
- Lesson: an "it should apply" assumption about a third-party tool's binding must be tested before handing a procedure to the owner (I flagged it as a hypothesis, but the owner still spent a daemon restart on it).
Apply: any exposure work on this machine; staging compose (bind explicitly there).
## LRN-054 | 2026-10-14 | Porting Zod to serde without drift; wasm in Vite; agent and harness traps
- serde silently widens Zod: a missing `Option` field defaults to None (use `deserialize_with` to make a nullable key required), `null` reads as None for an optional (use a `present` helper refusing null), `u32` refuses `2.0` that `.int()` accepts (JsInt over f64), internally tagged enums print the tag first (untagged enum + literal tag field at the schema position keeps Zod order). Zod drops a `__proto__` key in `z.record`; JS regex `$` = end of input; `.min/.max` count UTF-16. Prove with byte equality against `JSON.stringify(Schema.parse(x),null,2)` on real documents, a characterisation set frozen from the old functions, and a verdict table run by Zod once.
- Vite: `import x from 'pkg/glue.js?url'` emits the wasm-bindgen glue as an asset (no bundling); `import(`${url}?instance=${n}`)` gives a fresh module record in dev (`/@fs/…`) and build; works under CSP `script-src 'self' 'wasm-unsafe-eval'`. In happy-dom suites Vite rewrites `new URL(rel, import.meta.url)` into `/@fs/…` → Node readFile fails: build paths from `fileURLToPath(import.meta.url)`.
- A caught `WebAssembly.compile` CSP refusal logs nothing in the console: read the `securitypolicyviolation` event (`blockedURI` = `wasm-eval`). Headless Chromium defaults to en-US: set the page locale before asserting French strings. The DEPLOY CSP also refuses the footer's external credit logo (img-src).
- This harness decodes `\uXXXX` in tool inputs (heredocs, Write): build escape sequences with python `chr(92)`.
- `isolation: worktree` forks started at an old commit (605ee7c, not HEAD): each fork had to move its temp branch; brief forks to check `git log -1` first. `git worktree remove` / `git branch -d` on those temp branches refused by the auto-mode classifier → leftover worktrees (3.2 GB) for the owner to remove.
- Forks with full context + disjoint file ownership + "no commit, I collect the diff" merged with zero conflicts (one deliberate stub replaced).
Apply: R3/R4/R5 ports (same oracle stack), any wasm loaded by Vite, any agent fan-out.
## LRN-055 | 2026-10-14 | Lossy normalisation pre-pass hides user-data alteration; classify parser refusal instead
Context: R2 rewrote lone surrogate escapes to U+FFFD before serde_json so JS-era texts still parsed (L1). Owner refused: silent change of historical data. Fix: drop pre-pass; serde_json already refuses; scan text only after failure to name kind (zero cost on valid input, exact refusal kind for UI message + quarantine). Trap found by fix: oracle file freezing TS outputs carried lone escapes → whole-file parse failed; test loader must spell escapes out as literal text (evidence kept), never re-normalise. Also: `u32::from_str_radix` accepts leading `+` → escape scanner checks hex digits explicitly.
Apply: any reader of user data (R3 SVG, R4 PDF reader, R5 pipeline) → refuse with closed kind + keep original, never repair silently; a leniency step needs explicit owner decision and declared-difference test.
+18
View File
@@ -164,6 +164,24 @@ feat/findings-tree-v2 merged (FindingsTreePicker tracked in HEAD); all work belo
- [ ] R0.11 follow-ups for the CI/CD step (owner): ci.yml push/PR triggers stay live, so registering a runner starts PR builds at once (keep, or switch to workflow_dispatch until then); `actions/*@v4` mutable tags (Step 27); advisories cadence while no nightly runs (`cargo deny check advisories` is warn-only in check:all); `--remap-path-prefix` if native and builder wasm must match byte for byte
- [x] R1 = Step 8 worker in Rust (delivered 2026-10-13 on feature/step-08-files-foundation, see Step 8 block; awaiting owner validation): decode child dispatched before any thread, empty env, RLIMIT_AS/CPU, traced seccomp allowlist, `image` + `moxcms` + `libwebp-sys` in the child, parent RIFF-header check only, 512 KiB output cap, per-stage deadlines, service key
- [ ] R2 domain core (before Step 9): sheet/report/archive contracts, `SheetHandle` + `SheetIndexData`, reducers, Finding builder, vertebra selection, publish gate; wasm facade (JSON strings, ts-rs types, poison + reinstantiate, lazy init); app switched; 3 envelopes frozen first; N-1 reader test; draft quarantine; conformance fixtures + generated pgTAP; `packages/domain` frozen for engine/pipeline
- plan + contract: `.claude/tasks/plans/2026-10-13-rust-r2-domain-core.md` (rev 2 after 3 challenges, 45 findings folded); branch `feature/rust-r2-domain-core`; owner wording of the 4 new strings validated 2026-10-13
- [x] R2.0 freeze: 3 archive envelopes (demo, v2full, v2unresolved; FR, no logos, fixed time) + verbatim N-1 Zod copy (`packages/core-wasm/tests/n-1`) (3114d67); Zod output oracles of the reference documents (`crates/core/tests/oracles`)
- [x] R2.0b characterisation frozen from the TS: 84 report/archive cases + 765 Zod verdicts (fork B), 49 editor cases (fork C), 26 conformance fixtures (fork A), horse-slice JSON
- [x] R2.1 Rust contracts (ee07008): byte-equal to Zod output on draft + legacy sheets, demo report; the 3 frozen envelopes round-trip byte-equal
- [x] R2.2 Rust rules (0c47d0f, 21906c4): integrity rules, check, create, index data, read/migrate (612 leaves), rebase, snapshot, layered read, session restore/import; pgTAP 011 generated (PGlite 12/12, real 446/446)
- [x] R2.3 editor rules (3639c87) + facade ops (6c0533c)
- [x] R2.4 runtime (343d6f4): lazy, poison, offline recovery, per-generation handles, cap 3, retry, pkg/pkg-proofs, BUILD_STAMP; browser-checked dev + build; measurements (794dfd9)
- [x] R2.5 app switch (74fcb37) + publish gate fail-closed (6891f9e); app 313/313 on the real core (fork D adapted 17 files, 24 new tests, found 2 src bugs fixed)
- [x] R2.6 image + serving (7be94d4): wasm stage, gzip_static 372 KB served, CSP proof on the image 15/15 (Chromium only; no Firefox/WebKit build here), check:all green 2 min 17 s
- [x] R2.7 docs (8e8c58e: RUST.md §8, CLAUDE.md, WORKSPACE, TEST_STRATEGY, packages/README, DEPLOY, CHANGELOG), verifier 12/12 + floor ECARTS(2) (deleted tests, owner micro-gate), security PASS ×2 (follow-ups e49009e), memory BDR-050 LRN-054 BLK-010 EVAL-020; STOP (no merge)
- [x] R2 owner points (2026-10-14): manual LAN validation 10/10 + graphics accepted; L1 decided (refusal + quarantine, BDR-051); 2 deleted test files approved (coverage proven); worktree cleanup authorised after checks; merge go after L1
- [x] R2 closure (owner brief 2026-10-14)
- [x] L1.1 core: `parse_json` never rewrites; refusal classified (`JsonReadError::LoneSurrogate`, strict hex scan, on failure only); kind `lone_surrogate` from parse_input, sheet.check, draft.restore, archive.import (20d03cf)
- [x] L1.2 app: quarantine on `lone_surrogate`, `ImportError('lone_surrogate')` + `home.import.error_lone_surrogate` FR/EN (detailed wording), publish gate → `invalid_shape` (da8a037); dead `isCoreBuilt` removed (5020954)
- [x] L1.3 tests: js scanner/parse, session draft/archive/import + normal text, facade kind, characterisation L1 + Zod verdict = explicit refusal (oracles untouched, loader spells escapes out), store quarantine verbatim, editor action refused report unchanged, import kind, real-module call, gate
- [x] L1.4 checks: rust:check, stale-module refusal shown, wasm:build, Node 915, PGlite 12 files, real stack 446/446, types no drift, check:all green; verifier CONFORME 13/13, security PASS (6 LOW)
- [x] L1.5 docs (RUST.md 8.6/8.7, PDF-FORMAT, CHANGELOG) + memory BDR-051, LRN-055, EVAL-021, journal
- [ ] R2 follow-ups: Firefox/WebKit CSP run (no browser build here; owner's manual LAN run covers its browsers), import in a Web Worker + PDF import hardening gate (R4, PDF_IMPORT_HARDENING.md §5), React error boundary (not decided), base images by digest (Step 27), wording of the storage-full degraded notice, CSP refuses the footer's external credit logo (RUST.md 8.8), no CI/CD runner on the forge (workflows prepared, never executed), rustls 0.23.45 advisories RUSTSEC-2026-0346/0347/0348 (worker; not applicable: no brotli, built-in session cache, no ECH) → `cargo update -p rustls` ≥ 0.23.46 + worker:test + e2e:avatar, unreadable session archive under full storage removed by a later reset (security LOW, decision needed), `supabase/.temp/cli-latest` tracked by mistake (untrack + ignore), wasm-bindgen boundary invariant (JSON.stringify callers only, RUST.md 8.7)
- [ ] R3 anatomy core: tree, one sanitiser, serialiser, layer renderer, `compose_view_svg`; app canvas switched; composed views frozen as trees first
- [ ] R4 pdf core: reader (Web Worker, BLK-009 browser measurements) + writer (`pdf-writer`, Std14 AFM, draw log; lines/rects/colours golden frozen with the TS engine first, D-R2) + `report-compare` tool; `packages/pdf` deleted; N-1 scanner reads R4 PDFs
- [ ] R5 curation pipeline + importer + upload tool: seed golden regenerated once (new `documentSha256`, D-R5), `packages/anatomy` + `packages/domain` deleted, docs map; all before Step 13
@@ -0,0 +1,57 @@
# CONTRACT — R2 closure: L1 lone UTF-16 surrogates refused, never replaced
- date: 2026-10-14 | flow: ad-hoc fix on the R2 branch, verifier gate | branch: feature/rust-r2-domain-core
- status: dispatched after the code, test and doc commits
- spec: owner brief 2026-10-14 §2 (L1) + §3 (deletions) + answers: approach = refusal + quarantine (not preservation), import message = detailed wording; BDR-051 in `.claude/memory/decisions.md`; `docs/development/RUST.md` §8.7 item 1
- diff range: 36316cf..HEAD (run every CHECK from the repository root; `. scripts/rust-env.sh` first for cargo)
## REQUEST (IMMUTABLE)
Do not accept the silent transformation of an isolated UTF-16 surrogate into U+FFFD when historical data is read. Preserve user data integrity strictly: faithful preservation where possible, otherwise controlled refusal or quarantine of the data concerned, with the original content kept and an explicit message. Never delete or silently transform unreadable historical data. Add the non-regression tests needed, covering JSON strings with a lone surrogate and normal data. (Owner chose refusal + quarantine; preservation would need an architecture change.) Also approved: deletion of the old `zoneInteraction` suite and of the helper that skipped tests without the wasm module, provided the behaviours stay covered and the checks fail when an essential Rust feature becomes unavailable; no oracle needed by R3/R4 removed. No GUI change, no deploy.
## ACCEPTANCE CRITERIA
1. No replacement of lone surrogates remains anywhere in the code.
CHECK: grep -rn "replace_lone_surrogates" crates packages apps --include=*.rs --include=*.ts | wc -l; grep -c 'push_str("\\\\uFFFD")' crates/core/src/domain/js.rs
EXPECT: 0 / 0
2. The native Rust gate is green.
CHECK: bash scripts/rust-check.sh > /tmp/l1-verify-rust.log 2>&1; echo "exit $?"
EXPECT: exit 0
3. The core carries at least 142 passing tests, none failing.
CHECK: . scripts/rust-env.sh && cargo test -p faunosteo-core 2>&1 | grep "test result" | awk '{s+=$4; f+=$6} END {print s, f}'
EXPECT: first number ≥ 142, second 0
4. Every core entry that reads JSON text names the refusal `lone_surrogate` (operation inputs and sheet.check through the `From<JsonReadError>` impl, draft restore and archive import through their own variants).
CHECK: grep -c '"lone_surrogate"' crates/core/src/ops.rs crates/core/src/facade.rs; grep -c "LoneSurrogate" crates/core/src/domain/session.rs
EXPECT: ops.rs:2 facade.rs:2 / 4
5. The application treats the kind as unreadable draft content (quarantine), maps it on import to its own error and message in both dictionaries, and the publish gate reads it as content.
CHECK: grep -c "'lone_surrogate'" apps/app/src/state/reportStore.ts apps/app/src/pdf/import.ts apps/app/src/app/routes/HomeRoute.tsx packages/supabase/src/anatomical-sheets.ts; printf "%s/%s\n" $(grep -c "'home.import.error_lone_surrogate'" apps/app/src/i18n/fr.ts) $(grep -c "'home.import.error_lone_surrogate'" apps/app/src/i18n/en.ts)
EXPECT: reportStore.ts:1 import.ts:3 HomeRoute.tsx:1 anatomical-sheets.ts:1 / 1/1
6. The Node suites pass on the rebuilt module, with the new cases (app 320, supabase 40, core-wasm 26, domain 262).
CHECK: bash scripts/wasm-build.sh > /dev/null 2>&1; for p in app supabase core-wasm domain; do ./node_modules/.bin/pnpm --filter @faunosteo/$p exec vitest run 2>&1 | grep -E "^ +Tests "; done
EXPECT: Tests 320 passed (320) / Tests 40 passed (40) / Tests 26 passed (26) / Tests 262 passed (262)
7. No oracle, frozen fixture, N-1 copy, golden or seed file changed in the range.
CHECK: git diff --stat 36316cf..HEAD -- crates/core/tests/oracles apps/app/tests/fixtures packages/domain/tests/fixtures packages/core-wasm/tests/n-1 supabase/seed packages/pdf/tests packages/anatomy/tests | wc -l
EXPECT: 0
8. The tests cover a lone surrogate (high, low, in a key, in a v2 and a v3 report, in a draft, an archive, an attachment, an operation input, a sheet document) and normal data (pairs, literal backslash-u text, a genuine U+FFFD) and assert the original text is kept.
CHECK: grep -cE "fn (a_draft_with_a_lone|an_archive_with_a_lone|an_attachment_with_a_lone|normal_text_with_pairs)" crates/core/tests/archive_rules.rs; grep -cE "fn (lone_surrogate_escapes_are_found|a_lone_surrogate_refuses|normal_text_reads_unchanged)" crates/core/src/domain/js.rs; grep -c "lone surrogate" apps/app/tests/unit/state.quarantine.test.ts apps/app/tests/unit/pdf.import.test.ts packages/supabase/tests/anatomical-sheets.test.ts packages/core-wasm/tests/facade.test.ts
EXPECT: 4 / 3 / each file ≥ 1
9. A missing or stale wasm module fails the suites instead of skipping them, and no core suite is conditionally skipped.
CHECK: grep -c "stale' : 'missing'" packages/core-wasm/tests/global-setup.ts; grep -l "core-wasm/tests/global-setup.ts" apps/app/vitest.config.ts packages/supabase/vitest.config.ts packages/core-wasm/vitest.config.ts | wc -l; grep -rn "skipIf\|runIf\|isCoreBuilt" apps/app/tests packages/core-wasm/tests packages/core-wasm/src packages/supabase/tests --include=*.ts | grep -v "e2e/" | wc -l
EXPECT: 1 / 2 (core-wasm references it as `tests/global-setup.ts`) / 0
10. The deleted TypeScript editor cases keep a same-named Rust test each.
CHECK: for n in opens_the_detail_view_for_the_trigger_even_without_an_active_observation only_activates_a_fallback_observation_when_none_is_active always_opens_the_vertebra_picker_on_a_spine_zone routes_bilateral_zones_through_the_side_picker_or_clears_both_sides toggle_zone_adds_a_zone_with_snapshots_then_removes_it ensure_zone_keeps_an_existing_zone_and_reports_its_index add_sides_appends_only_the_missing_sides_and_never_removes_one remove_zone_at_removes_one_zone_by_index_and_keeps_findings detail_view_zones_are_distinct_from_main_view_zones_with_the_same_id collects_vertebrae_across_spine_zones_the_priority_zone_first replaces_per_region_prunes_emptied_zones_and_spawns_zones_for_new_regions keeps_non_spine_zones_untouched_and_ignores_unknown_regions; do grep -c "fn $n" crates/core/tests/editor_rules.rs; done | sort | uniq -c
EXPECT: 12 1
11. No interface component, style or signed-in screen changed; HomeRoute gains only the two lines of the new case.
CHECK: git diff --stat 36316cf..HEAD -- apps/app/src/components apps/app/src/styles apps/app/src/app/routes/app apps/app/src/app/routes/auth | wc -l; git diff 36316cf..HEAD -- apps/app/src/app/routes/HomeRoute.tsx | grep -c "^[+-][^+-]"
EXPECT: 0 / 2
12. Documentation states the owner's decision and the refusal paths.
CHECK: grep -c "owner decision 2026-10-14, BDR-051" docs/development/RUST.md; grep -c "Lone UTF-16 surrogates refused, never altered" CHANGELOG.md; grep -c "lone_surrogate" docs/PDF-FORMAT.md
EXPECT: 1 / 1 / 1
13. The whole pre-merge gate passes.
CHECK: bash scripts/check-all.sh > /tmp/l1-verify-all.log 2>&1; echo "exit $?"; grep -c "== all checks passed" /tmp/l1-verify-all.log
EXPECT: exit 0 / 1
## CLARIFICATIONS
- The editor test list has 13 TypeScript cases; "toggles plain zones; the ten bilateral annotations and the 18 others split as the sheet says" maps to `toggles_plain_zones_and_splits_the_observable_annotations_as_the_sheet_says` (renamed: 28 is not the draft's count), hence 12 exact names in criterion 10.
- `crates/core/tests/common/mod.rs::oracle_file` writes each lone escape of an oracle file out as literal text for the test loader only: the oracle files are frozen TypeScript evidence, not user data, and their raw text is still what the L1 test reads.
- The RustSec advisories stage of `check-all.sh` is warn-only by design (RUST.md); its rustls findings predate this range.
## FILE SCOPE
crates/core/**, packages/domain/tests/r2-characterisation.test.ts, apps/app/src/{app/routes/HomeRoute.tsx,core/sheetOps.ts,i18n/fr.ts,i18n/en.ts,pdf/import.ts,state/reportStore.ts}, apps/app/tests/unit/{state.quarantine.test.ts,pdf.import.test.ts,routes.HomeRoute.import.test.tsx}, packages/supabase/src/anatomical-sheets.ts, packages/supabase/tests/anatomical-sheets.test.ts, packages/core-wasm/src/node.ts, packages/core-wasm/tests/facade.test.ts, docs/development/RUST.md, docs/PDF-FORMAT.md, CHANGELOG.md, .claude/tasks/**, .claude/memory/**
@@ -0,0 +1,49 @@
# CONTRACT — Rust R2: domain core in Rust, used by the application
- date: 2026-10-14 | flow: orchestrator + 4 forks (3 worktrees + 1 in tree), plan challenges ×3, verifier gate | branch: feature/rust-r2-domain-core (off develop 1a7ee7d)
- status: dispatched after the implementation, test and doc commits
- spec: `.claude/tasks/plans/2026-10-13-rust-r2-domain-core.md` (plan + revision 2 §5, which wins), `docs/development/RUST_ARCHITECTURE_REVIEW.md` VI.2 R2 row, VI.3, VI.4, owner brief 2026-10-13 (R2 go: §2 scope, §3 compatibility, §5 runtime, §6 CSP and measures, §7 no UI redesign, §9 tests, §12 exclusions)
- diff range: 1a7ee7d..HEAD (run every CHECK from the repository root; `. scripts/rust-env.sh` first for cargo)
## REQUEST (IMMUTABLE)
Migrate the existing domain core of Faunosteo to Rust and switch the application to it, with no business behaviour change without a separate decision: sheet / report / archive contracts, SheetHandle and index, observation reducers, finding construction, vertebra selection, publish checks, related transformations and validations, in crates/core and the wasm facade; consumers switched; React, DOM, forms and Supabase services stay in their layers. Preserve Report v3, v2 PDF imports, autonomous archives, observations, findings, vertebrae, annotations, sheet versions, unresolved content, FR/EN, old data; freeze the three archive envelopes first; keep a permanent N-1 reader test; JSON rules (absent optionals, nullable, number format) conformant; no silent loss. Lazy wasm, explicit instantiation failures, no reuse after a trap, degraded behaviour when unavailable. CSP with 'wasm-unsafe-eval' only; measure size, init, op times, page impact, memory; no wasm on pages that do not need it. No UI redesign (four new strings validated by the owner). Out: R3, R4, R5, Step 9, CI/CD, deploy, release 0.2.0, merge into develop.
## ACCEPTANCE CRITERIA
1. The native Rust gate is green (fmt, clippy -D warnings, tests, ts-rs export, cargo deny).
CHECK: bash scripts/rust-check.sh > /tmp/r2-verify-rust.log 2>&1; echo "exit $?"
EXPECT: exit 0
2. The core carries at least 135 passing tests (contracts, rules, oracles, conformance).
CHECK: . scripts/rust-env.sh && cargo test -p faunosteo-core 2>&1 | grep "test result" | awk '{s+=$4; f+=$6} END {print s, f}'
EXPECT: 135 0 (first number ≥ 135, second 0)
3. The application sources no longer import the TypeScript domain, and no domain rule or the deleted service is reachable from them by name.
CHECK: grep -rln "@faunosteo/domain" apps/app/src | wc -l; grep -rnE "decideZoneClick|collectVertebrae|buildSheetIndex|buildSheetSnapshot|rebaseReportOnSheet|readReportDocument|readArchiveDocument|zoneInteraction" apps/app/src | wc -l; test -e apps/app/src/services/zoneInteraction.ts; echo $?
EXPECT: 0 / 0 / 1
4. The application suite passes on the real core (313 tests), including the four new R2 suites.
CHECK: bash scripts/wasm-build.sh > /dev/null 2>&1; ./node_modules/.bin/pnpm --filter @faunosteo/app exec vitest run 2>&1 | grep -E "^ +Tests "; ls apps/app/tests/unit/ | grep -cE "n-1.reader|state.quarantine|routes.EditorRoute.degraded|state.coreFailures"
EXPECT: Tests 313 passed (313) / 4
5. The Step 6 goldens, the seed and the other packages' fixtures are untouched by R2, and the three frozen archive envelopes are unchanged since their freeze commit.
CHECK: git diff --stat 1a7ee7d..HEAD -- apps/app/tests/fixtures/goldens/step6 supabase/seed packages/domain/tests/fixtures packages/pdf/tests packages/anatomy/tests | wc -l; git diff --stat 3114d67..HEAD -- apps/app/tests/fixtures/goldens/r2 | wc -l
EXPECT: 0 / 0
6. The shipped module carries no trap export and stays under the 600 KB compressed budget.
CHECK: grep -cE "panic_for_test|recurse_for_test" packages/core-wasm/pkg/faunosteo_wasm.d.ts; gzip -9 -c packages/core-wasm/pkg/faunosteo_wasm_bg.wasm | wc -c
EXPECT: 0 / a number ≤ 600000
7. No auth, account, shell or entry module references the core runtime (the module is only loaded from the sheet pages).
CHECK: grep -rl "@/core/" apps/app/src/app/routes/auth apps/app/src/app/routes/app apps/app/src/components/shell apps/app/src/components/account apps/app/src/app/App.tsx apps/app/src/main.tsx | wc -l
EXPECT: 0
8. Only the content failure kinds set a draft aside, and the core-wasm suite proves the runtime (lazy load, trap, recovery, handle rebuild, cap, retry, size).
CHECK: grep -c "outcome.kind !== 'invalid' && outcome.kind !== 'unsupported_version'" apps/app/src/state/reportStore.ts; ./node_modules/.bin/pnpm --filter @faunosteo/core-wasm exec vitest run 2>&1 | grep -E "^ +Tests "
EXPECT: 1 / Tests 25 passed (25)
9. The publish gate fails closed and runs on the real core; the SQL suite (incl. the generated conformance file 011) passes on PGlite.
CHECK: grep -c "refuses publication when the validator cannot run" packages/supabase/tests/anatomical-sheets.test.ts; ./node_modules/.bin/pnpm --filter @faunosteo/supabase exec vitest run 2>&1 | grep -E "^ +Tests "; ./node_modules/.bin/pnpm --filter @faunosteo/supabase exec vitest run tests/db/pgtap.test.ts 2>&1 | grep -E "^ +Tests "
EXPECT: 1 / Tests 39 passed (39) / Tests 12 passed (12)
10. The four validated strings exist in both dictionaries.
CHECK: for k in sheet.core_unavailable sheet.core_retry core.action_failed editor.draft_quarantined home.import.error_core_unavailable; do printf "%s/%s " $(grep -c "'$k'" apps/app/src/i18n/fr.ts) $(grep -c "'$k'" apps/app/src/i18n/en.ts); done
EXPECT: 1/1 1/1 1/1 1/1 1/1
11. Documentation records the migration (RUST.md §8, DEPLOY.md R2 notes, CHANGELOG).
CHECK: grep -c "^## 8. R2" docs/development/RUST.md; grep -c "From R2 on" DEPLOY.md; grep -c "Rust R2" CHANGELOG.md
EXPECT: 1 / 1 / 1
12. The whole pre-merge gate passes.
CHECK: bash scripts/check-all.sh > /tmp/r2-verify-all.log 2>&1; echo "exit $?"; grep -c "== all checks passed" /tmp/r2-verify-all.log
EXPECT: exit 0 / 1
## FILE SCOPE
crates/core/**, crates/wasm/**, Cargo.toml, Cargo.lock, packages/core-wasm/**, packages/supabase/{src/anatomical-sheets.ts,src/index.ts,package.json,tests/anatomical-sheets.test.ts,vitest.config.ts}, packages/domain/tests/r2-*.test.ts, apps/app/{src,tests,scripts,eslint.config.js,vitest.config.ts,package.json}, supabase/tests/011_sheet_conformance.sql, scripts/{wasm-build.sh,wasm-stamp.mjs}, Dockerfile, docker/nginx.conf, docker/csp-proof/app-image.{sh,mjs}, .gitignore, .dockerignore, .prettierignore, pnpm-lock.yaml, docs/development/{RUST,WORKSPACE,TEST_STRATEGY}.md, packages/README.md, CLAUDE.md, DEPLOY.md, CHANGELOG.md, .claude/tasks/** (plan, TODO, this contract), .claude/memory/** (registries).
@@ -0,0 +1,113 @@
# PLAN — Rust R2: domain core (contracts, rules, sheet handle, reducers) + app switch
- date: 2026-10-13 | branch: `feature/rust-r2-domain-core` (off develop 1a7ee7d)
- spec: `docs/development/RUST_ARCHITECTURE_REVIEW.md` (rev 2 + Annex C), rows II.2 / VI.2 R2 / VI.3 R2 / VI.4, decisions D-R11, D-R12 (gated functions ported, behaviour preserved), D-R13; owner brief 2026-10-13 (R2 go)
- out of scope: R3 (sanitiser, layer renderer, compose), R4 (PDF reader byte scan, writer, report-compare CLI), R5 (pipeline, importer, upload tool, `packages/domain` deletion), Step 9, CI/CD, deploy, release 0.2.0, any graphic change
- stop: after R2 delivery; no merge into develop before the owner's validation
## 0. Facts this plan rests on (inventory 2026-10-13)
- `packages/domain` (2,298 lines, 9 test files): sheet schema (strict Zod), 21 integrity rules, `createEmptySheetDocument`, `buildSheetIndex` (10 closures over Maps, last duplicate wins), report v3 / v2 (strip Zod), migration map, `migrateReportV2ToV3`, `readReportDocument`, `rebaseReportOnSheet`, archive snapshot (`buildSheetSnapshot`, `assertSnapshot` with caps, `snapshotIndexSource`), envelope v1 (`readArchiveDocument`, `ReportArchiveEnvelopeSchema`), branding, labels (25 keys).
- Consumers of `packages/domain` after R2: `packages/pdf` (engine, R4), `packages/anatomy` (pipeline + render, R3/R5), `apps/app/scripts` (`report:compare`, R4), N-1 test fixtures. The app `src/` stops importing it (VI.4).
- App logic to move: `services/zoneInteraction.ts` (213 lines: click decision + 7 reducers + `collectVertebrae` / `syncVertebrae`), `FindingsTreePicker.toggleLeaf` (Finding builder), `VertebraPicker` toggle / all / none, `reportStore` rules (`newReport`, `emptyObservation`, add / remove / move / replace), `persistence` parsing (draft via `readReportDocument`, archive via `ReportArchiveEnvelopeSchema`), `sheets/provider` parsing, `pdf/import.ts` layered read (via engine `readReportArchive` = byte scan + `readArchiveDocument`), `pdf/export.ts` `buildSheetSnapshot`, `packages/supabase` publish gate (`assertPublishable`).
- Display helpers kept in TypeScript (review II.2 class C): `zoneLabel`, `describeZone`, `zoneTrees`, `unresolvedFindings`, import message lines, `isIdentityComplete`, `pickLabel`, `FreeTextFindingInput` trimming (form glue), identity / conclusion / recommendations / next-appointment setters (Zustand assignments of form values; no validation exists today, adding one is a behaviour change: deviation from the review's "set_* validation", stated).
- Routes are static imports; `HomeRoute` and `NewReportRoute` call `useSheet` today (the sheet bundle loads on `/`).
- The engine's `readAttachedDocument` returns `JSON.parse` output after a depth pre-scan capped at 64; `readReportArchive` = that + `readArchiveDocument` + error mapping (`incompatible_version` when a numeric unknown version, else `no_attachment`).
- Zod 3.25.76 semantics to reproduce: object output in schema key order; `.optional()` = absent ok, `null` rejected, absent stays absent; `.nullable()` = key required unless `.default(null)`; `.strict()` rejects unknown keys, others strip; `.int()` = `Number.isInteger` (accepts `2.0`, `1e20`); `.min/.max` on strings count UTF-16 units; `.url()` = `new URL()` succeeds; `.uuid()` = Zod regex; JS regex `$` = end of input; discriminated unions dispatch on the tag.
- R0 facts kept: `serde_json` `preserve_order` + `float_roundtrip`, `js_number` formatter, panic = abort on wasm32, an instance is unusable after a trap, a fresh instance needs a fresh glue module record (cache-busting import).
## 1. Decisions of this plan (internal; trade-offs stated)
| # | Decision | Why / alternative rejected |
|---|---|---|
| P1 | Every JSON input is read `text → serde_json::Value → typed`. Before parsing, a pre-pass rewrites `\uD800`–`\uDFFF` escapes that are not a valid surrogate pair to `�` (JSON.parse keeps lone surrogates, serde_json refuses them). Recursion limit 128 (drafts and bundles < 20 deep; archive JSON is pre-scanned at 64 by the TS scanner). | Value-first gives JSON.parse duplicate-key semantics (last value, first position) and lets one parse feed both the layered reader and the typed structs. Refusing lone surrogates would lose a whole report that TypeScript accepts; replacing them is the smallest divergence (leniency decision L1, pinned by a fixture, reported). |
| P2 | Typed structs use serde derive plus field helpers that reproduce Zod: `opt` (absent ok, `null` refused, skipped when `None`), `nullable` (key required, `null` ok), `nullable_default` (absent → `null`), `deny_unknown_fields` exactly where Zod is `.strict()`. Integers are `JsInt` (any finite number with an integer value, kept as f64, printed by `js_number`). Constrained strings are newtypes checked by hand (UTF-16 length, the id / region / colour / sha256 / base64 / uuid / branding-URL patterns). `.url()` = `url` crate parse (WHATWG, as `new URL`), size measured; no `regex` crate. | Serde's implicit `None` for a missing `Option` and its `null`-as-`None` would silently widen what Zod accepts. f64 integers keep `1e20` or `2.0` accepted and printed as JavaScript does. |
| P3 | Discriminated unions (views, annotations, geometry, next appointment, image asset) are untagged enums whose variant structs carry a literal tag field at the Zod schema position (annotations and views: `kind` after the common fields; geometry, next appointment, image asset: tag first). Every struct declares its fields in Zod schema order. | Zod parse output order = schema order; serde's internally tagged enums would print the tag first and break byte equality with `JSON.stringify(ZodSchema.parse(x), null, 2)`, which is the strongest serialisation oracle available. D-R11 (struct order) holds. |
| P4 | Behaviour is ported site by site, quirks included: index maps last-duplicate-wins (as `new Map`), `viewsById` first-wins in the rules, `find` first-wins for `spineAnnotation` and tree paths, JS truthiness (`detailSourceId ""` → main view, `vertebrae: []` kept, `requiresVetReferral: false` dropped), `??=` on rebase labels, `unsupported_envelope` keeping the report origin, a malformed map entry failing the read (no new "never throws" behaviour). | Owner rule: no business behaviour change without a decision. Unifying policies is a later decision, not a side effect. |
| P5 | `SheetHandle` (wasm-bindgen struct) owns the loaded sheet: status, ref, species, schema version, normalized document, assets, asset hashes, migration map and the Rust index. `handle.index_data()` returns `SheetIndexData` once: normalized document, `viewById` / `annotationById` / `findingZoneById` / `regionByCode` (positions, last wins), `annotationsByView` (positions, document order), `spine[region][view]` (position, first wins), `spineIds`, `names[annotationId]`, `nodeKeys` (paths reachable by first-wins walk). The app's `SheetIndex` becomes a class over that data with today's method names (accessors only, `Object.hasOwn`), plus `ops` = the sheet-bound core calls. The handle does not run the integrity rules at load (today's behaviour); a missing main view is a load failure. | ~14 modules keep calling `sheet.annotation(id)` etc., no wasm call in a render, no rule in TypeScript. The canvas keeps the TS renderer (R3) on the normalized document and the TS asset record. |
| P6 | One core call per user action. `zone.click` returns the decision and, when the observation changes, the new observation, plus what the UI needs (`sidesPresent` for the laterality picker, `zoneIndex`). The vertebra picker's initial selection (`collectVertebrae`) is computed when the picker opens (click or chip), never in render. Vertebra grid display (`count`, `count_range`, extended state) stays React. | Review III.3 rule 1 (no call in a render path). |
| P7 | Store: every report entering the store passes the core (`report.new`, draft restore, import, `hydrateReport`), every observation write passes `report.replace_observation` (shape-checked, stripped), list rules are core calls (`add` / `remove` / `move` observation). Field assignments of form values stay Zustand (see §0). A failed core call leaves the state unchanged and raises the `core.action_failed` alert. `hydrateReport` now parses (the "stores as is" characterisation test changes by design, stated). | "Rust parser = single entry" (review I.2); one-line delegations. |
| P8 | Lazy core: `useSheet` (editor, new report) and the import action load it; `HomeRoute` gets the sheet availability from the bundle without the core and loads the core only when a file is chosen; `/login`, `/app/*`, Mon compte never reference it. The glue JS and the `.wasm` are emitted as Vite assets (`?url`), never bundled into a route chunk, fetched on first need. | Owner: no wasm on pages that do not need it. |
| P9 | Runtime: synchronous calls after `await ready()`. A `WebAssembly.RuntimeError` poisons the instance: the failing call returns `{ok:false, kind:'internal'}`, a fresh instance is created in the background (cache-busting dynamic import of the glue asset URL + new `WebAssembly` instance), sheet handles are rebuilt lazily from their retained source text, calls made meanwhile return `core_unavailable`. A load failure (fetch, CSP, compile) gives `core_unavailable` with `retry()` evicting the cached promise. | Review III.3 rules 5 and 6; R0 proof (no reuse after a trap). Async calls everywhere would reintroduce the double-click races the click chain avoids with `getState()`. |
| P10 | Two wasm builds: `packages/core-wasm/pkg/` (shipped, no `proofs` feature) and `pkg-proofs/` (trap exports, tests only). | R0 follow-up "drop --features proofs at R2"; the trap test still needs a trap. |
| P11 | Import = engine byte scan (`readAttachedDocument`, TS, frozen until R4) → `JSON.stringify` → core `archive.import` (layered read + rebase in one call) → the same `ImportError` mapping. Export = core `archive.snapshot` → frozen TS engine (still asserts and writes). | D-R12 go; R4 owns the scanner and the writer. |
| P12 | Draft quarantine: an unreadable `osteo:draft` or `osteo:archive` moves to `osteo:quarantine` (JSON list of `{key, at, raw}`, newest last, cap 10) before anything overwrites it; the draft case raises the `editor.draft_quarantined` alert. | VI.3 R2 row; today's silent drop is a loss. |
| P13 | Publish gate: `publishSheetVersion(client, versionId, validate)` takes the core validator (dependency injection); conformance fixtures `crates/core/tests/conformance/*.json` (document, Rust issues with paths, SQL codes) run in cargo and in a generated `supabase/tests/011_sheet_conformance.sql`; a cargo drift test regenerates and compares the SQL file. | Review III.4. |
| P14 | N-1 reader: the Zod schemas shipped at 1a7ee7d copied verbatim under `packages/core-wasm/tests/n-1/` (frozen, survives R5); a vitest parses every Rust-written report, draft, snapshot and envelope fixture with them. | Review III.3 rule 7, VI.3. |
| P15 | Parity corpus: a TS generator mutates small valid bases (report v3, report v2, horse-slice document, snapshot, branding, labels, envelope, migration map) field by field (delete, `null`, wrong type, empty, unknown key, `2.0`, `-1`, `1e20`, long strings at the caps) and records Zod's outcome (accepted output text or refused); committed under `crates/core/tests/parity/`; cargo asserts the same outcome and byte-equal output; a vitest drift test re-runs Zod on it while `packages/domain` exists. | "Freeze with the old code, then switch" without a dual-run harness. |
| P16 | `apps/app/src` imports nothing from `@faunosteo/domain` (ESLint `no-restricted-imports`); `pickLabel` moves to `apps/app/src/i18n/pickLabel.ts`; types come from `@faunosteo/core-wasm` (ts-rs). The `apps/app` package keeps the dependency for `scripts/` (R4). | VI.4. |
| P17 | App image: wasm stage (`rust:1.99.0-bookworm`, wasm target, `wasm-bindgen-cli` at the `Cargo.lock` version, BuildKit cache mounts) before the Node stage; nginx serves a precompressed `.wasm.gz` (`gzip_static`) when the module is present, else `gzip on` for `application/wasm` (decided on the image's `nginx -V`). Size budget test: served module ≤ 600 KB gzip. | D-R13; the VPS never builds (DEPLOY.md note). |
| P18 | CSP proof on the real image: headless Chromium behind an nginx with the DEPLOY.md headers runs the editor path (new report, zone click, picker, export, import); a variant without `'wasm-unsafe-eval'` shows the degraded state while `/login` stays usable. | VI.2 R2 end criteria. |
Visible strings, wording validated by the owner 2026-10-13 (the recommended options):
- `sheet.core_unavailable`: « Le moteur de calcul de Faunosteo n'a pas pu être chargé. Vos données de session sont conservées. » / "Faunosteo's computation engine could not be loaded. Your session data is kept."; `sheet.core_retry`: « Réessayer » / "Retry" (editor and new-report degraded notice).
- `core.action_failed` (alert): « Cette action n'a pas pu être appliquée. Réessayez ; votre bilan n'a pas été modifié. » / "This action could not be applied. Try again; your report was not changed."
- `editor.draft_quarantined` (alert): « Le brouillon de cet onglet n'a pas pu être relu par cette version de Faunosteo. Il a été mis de côté, pas supprimé. » / "This tab's draft could not be read by this version of Faunosteo. It was set aside, not deleted."
- `home.import.error_core_unavailable` (import error line): « Le moteur de lecture n'a pas pu être chargé. Réessayez l'import. » / "The reading engine could not be loaded. Try the import again."
## 2. Core operations (facade `call(op, json)` and `SheetHandle.call(op, json)`)
Envelope unchanged: `{"ok":true,"value":…}` | `{"ok":false,"kind":…,"detail":…}`. Kinds: `invalid_json`, `invalid_shape`, `unknown_op`, `internal`, plus per-op kinds below.
Free ops:
- `sheet.check` (document) → `{issues: SheetIssue[], publishable}`; `invalid_shape` when the strict schema refuses.
- `sheet.create_empty` ({species_id, name}) → document.
- `report.new` ({draft, sheet: SheetRef, id, createdAt, observationId}) → Report (draft observations kept, else one empty observation with `observationId`).
- `report.add_observation` ({report, id}) → Report; `report.remove_observation` ({report, index}) → Report; `report.move_observation` ({report, index, direction: 'up' | 'down'}) → Report (no-op at the ends); `report.replace_observation` ({report, index, observation}) → Report (`invalid_shape` when the observation does not parse).
- `vertebra.select` ({selection, action: {kind:'toggle', region, index} | {kind:'all', region, count} | {kind:'none', region}}) → Vertebra[].
- `archive.parse_envelope` (envelope JSON) → envelope (full v1 schema, shape tier, as `ReportArchiveEnvelopeSchema`).
Sheet ops (`SheetHandle`):
- constructor `SheetHandle.load(bundleJson)` → handle | error kind `invalid_sheet`; `index_data()` → `SheetIndexData`.
- `draft.restore` ({draft: string, archive: envelope | null}) → `{report, rebase: RebaseOutcome}`; kinds `unsupported_version {found}`, `invalid`.
- `archive.import` (attachment data) → `{read: ArchiveReadOutcome, rebase: RebaseOutcome}`; kinds `incompatible_version {found}` (numeric unknown version), `no_attachment` (anything else).
- `archive.snapshot` ({report}) → SheetSnapshot.
- `report.rebase` ({report, archived: snapshot | null}) → RebaseOutcome.
- `zone.click` ({observation: Observation | null, annotationId}) → `{kind: 'ignore' | 'open_view' | 'activate_fallback' | 'open_vertebra_picker' | 'open_laterality_picker' | 'remove_both_sides' | 'toggle', viewId?, observation?, zoneIndex?, sidesPresent?}`.
- `zone.add_sides` ({observation, annotationId, sides}) → Observation; `zone.remove_at` ({observation, index}) → Observation.
- `vertebra.initial` ({observation, zoneIndex}) → Vertebra[]; `vertebra.sync` ({observation, selection, viewId}) → Observation.
- `finding.toggle` ({observation, findingZoneId, path, side?}) → Observation (adds the built finding with snapshots and the vet flag, or removes the matching one).
## 3. Phases (one commit or more each; checkpoints reported when a consumer switches)
- **R2.0 Freeze (TS, before any switch)**: the three archive envelopes (`demo`, `v2full`, `v2unresolved`, fr, fixed `exportedAt`) and their bare reports exported by the current path, committed as goldens; N-1 schema copy; parity corpus generator + corpus; `horse-slice.ts` and `mini-sheet.ts` converted to JSON fixtures; characterisation of the click chain and store outputs that no test pins (exact objects).
- **R2.1 Contracts in Rust**: `domain/js.rs` (JsInt, UTF-16 lengths, patterns, own-key semantics, surrogate pre-pass), sheet schema, report v2 / v3 / identity / migration map, snapshot / branding / labels / envelope structs, ts-rs export; parity corpus green; byte equality with `JSON.stringify(Zod.parse(x), null, 2)` on the seed draft, demo report, v2 fixtures.
- **R2.2 Rules in Rust**: 21 rules + `check`, `create_empty`, index + `SheetIndexData`, `readReportDocument` + migration (612-leaf suite), rebase (exact objects), snapshot build / assert (caps, depth), envelope layered read (decision table); suites ported from `packages/domain/tests` with their exact expectations; conformance fixtures + generated pgTAP + drift test.
- **R2.3 Editor rules in Rust**: zone click + reducers (13-case suite + characterisation), finding toggle, vertebra initial / sync / select, report ops.
- **R2.4 Facade + runtime**: `crates/wasm` (`call`, `SheetHandle`, no proofs in the shipped build), `packages/core-wasm` runtime (lazy, poison, re-instantiate, retry, Node and browser sources, typed client), the trap / load-failure / handle-rebuild tests, size test.
- **R2.5 App switch**: provider + `useSheet` (+ degraded state), `SheetIndex` class, store + persistence + quarantine, click chain + pickers + findings picker, import / export, Home lazy core, publish gate, ESLint restriction, `pickLabel` move, codemod of type imports; deletion of `services/zoneInteraction.ts`, `services/sheetIndex.ts` re-exports and the data-building code in components; app suites green with their assertions (renamed calls only, each changed assertion listed).
- **R2.6 Images and serving**: Dockerfile wasm stage, `.dockerignore`, nginx compression, `check:all` stages (two wasm builds), CSP headless proof on the image, measurements (raw / gzip size, instantiate time, op timings, page-load impact, memory).
- **R2.7 Docs and gates**: RUST.md R2 section (migrated components, deleted TS, exceptions, measurements, census), CLAUDE.md, WORKSPACE.md, TEST_STRATEGY.md, packages/README.md, DEPLOY.md note, CHANGELOG; verifier + security gates; memory; owner manual procedure on the LAN.
## 4. Oracles (end criteria, review VI.2 R2 row)
1. Domain suites ported to cargo with exact expectations (validate code + path lists, migrate incl. 612 leaves, rebase exact objects, envelope decision table, branding / labels, snapshot caps); parity corpus 100 % equal.
2. App service / store / component / route suites pass on the core with their assertions; changed assertions listed one by one.
3. The three frozen envelopes: the Rust-path export parses with the frozen N-1 Zod schemas and is semantically equal (deep equal) to the frozen one; bytes differ only by key order (D-R11).
4. The 39 step6 goldens and the seed golden untouched (`git diff --stat` on their dirs empty).
5. `pnpm build` with the wasm; the module is not referenced by the auth / account chunks; served module ≤ 600 KB gzip.
6. App image boots under the production CSP headers in headless Chromium (editor path works); without `'wasm-unsafe-eval'` the editor shows the degraded state and `/login` works.
7. A deliberate trap (proofs build) re-instantiates and the next call succeeds with a rebuilt handle.
8. `pnpm check:all` green; `pnpm db:test` on the real stack with the generated pgTAP file; verifier CONFORME; security PASS.
9. Grep census: no `@faunosteo/domain` import under `apps/app/src`; no `decideZoneClick` / `syncVertebrae` / `buildSheetIndex` / `buildSheetSnapshot` / `rebaseReportOnSheet` / `readReportDocument` reachable from `apps/app/src`.
10. Owner manual FR / EN flow on the LAN (procedure delivered).
## 5. Revision 2 (2026-10-14, after three plan challenges: correctness CONCERNS(2), robustness FATAL(7) incl. 1 BLOCKER, simplicity CONCERNS(3); 45 findings)
Supersedes the rows of §1–§4 it names.
- **P7 replaced** (all three lenses): only core-built observations and reports enter the store through the core (`report.new`, draft restore, import, the reducers' outputs). Form-value edits of an observation (comment, severity, free text, finding removal by identity) stay Zustand assignments, like the identity and text setters. `report.replace_observation` is dropped. Store actions that call the core return `{ ok }`; callers (`NewReportRoute`, `HomeRoute`, the click chain) stop on failure (no navigation, no picker). `hydrateReport` is deleted (test-only seam; tests seed with `hydrateImport` or `setState`).
- **Editor degraded state (robustness BLOCKER 1, correctness 11)**: `useSheet` gets `core_unavailable` and `invalid_sheet` states; `EditorRoute` never redirects in those states, renders the notice + retry, and never restores or overwrites `osteo:draft` while the core has not read it. Test: reload `/editor` with the core failing, draft intact.
- **Runtime (robustness 2, 3, 9, 10)**: every sheet op resolves the handle through the runtime with an instance generation; calls into a poisoned glue record are refused (including `free`). The compiled `WebAssembly.Module` is kept; one spare glue record is pre-imported after a successful load so a re-instantiation needs no network; at most 3 re-instantiations per page, then `core_unavailable` ("reload"). `retry()` clears the runtime, `useSheet` and provider caches. A vitest `globalSetup` fails (never skips) when `pkg/` or `pkg-proofs/` is missing or its build stamp (hash of `crates/**` + `Cargo.lock`, written by `scripts/wasm-build.sh`) differs from the tree. The trap → re-instantiate → next call test also runs once in headless Chromium on a build linked to `pkg-proofs` (best effort; recorded if not obtainable).
- **Quarantine (robustness 4, 5, 16; simplicity 13; correctness 10)**: only the content kinds (`invalid`, `unsupported_version`) quarantine; any other kind leaves the keys untouched and shows the degraded state. Raw text goes to `osteo:quarantine:draft` / `osteo:quarantine:archive` (newest only); the source key is removed only after the quarantine write succeeded; a draft rebased with unresolved items keeps its raw pre-rebase text in `osteo:quarantine:draft-pre-rebase`. Paths that never read the draft (New report / Import from Home after a reload) keep today's semantics (a new session replaces the tab draft). No recovery UI at R2 (stated residual).
- **SheetIndexData minimal (simplicity 3, correctness 3)**: `mainViewId` (first `main` view by position), `viewById`, `annotationById`, `findingZoneById` (positions, last wins), `names[annotationId]`, `spineIds` (last-wins annotation, observable with a region), `nodeKeys` keyed by the JSON text of `[zoneId, ...path]` (collision-free) reachable by the first-wins walk on the last-wins zone, plus the normalized document. No `annotationsByView`, `spine`, `regionByCode` (no TS reader after the switch). `regions()` reads the document.
- **Ops (simplicity 4, correctness 4, 8, 13)**: exposed only with a TS caller: `sheet.check` (publish gate), `report.new`, `report.add_observation`, `report.remove_observation`, `report.move_observation`, `vertebra.select` (called in the tap handler, never in a state updater), sheet ops `draft.restore` ({draft: string, archive: string | null} → report, rebase, parsed archive or `archiveRejected`), `archive.import`, `archive.snapshot`, `zone.click` (returns the initial vertebra selection for `open_vertebra_picker`), `zone.add_sides`, `zone.remove_at`, `vertebra.initial` (chip path), `vertebra.sync`, `finding.toggle` (takes the clicked leaf's position among its siblings; parents walked first-wins as `findNode`). `sheet.create_empty`, `report.rebase`, `archive.parse_envelope` are Rust functions with cargo tests, no op. The failure envelope gains an optional numeric `found` (js_number).
- **Oracles (simplicity 2, correctness 1, 5, 6, 7, 12)**: the full mutation corpus is dropped. Instead: (a) Zod output oracles of the reference documents (`crates/core/tests/oracles`, done: draft and legacy sheets, demo v3, v2 fixtures, migration map, byte-equal); (b) a characterisation set frozen from the TS functions for the quirks (`detailSourceId: ""`, `requiresVetReferral: false`, `vertebrae: []`, `collectVertebrae` concatenated-key collision, `syncVertebrae` region order and second spine zone, rebase `??=`, malformed map entry, numeric literals `3.0` / `1e0`, lone surrogate lowercase escapes); (c) a table of hostile inputs per constraint site with Zod's accept/refuse verdict (vitest writes it with `MAKE_R2_ORACLES=1`, cargo asserts it); (d) type-level equality of ts-rs types against `z.output` per contract (vitest `expectTypeOf`); the golden-report helper switches to the core migration for the Rust run; the publish-gate tests use the real Node core. Oracle 9 reworded: "not imported by `apps/app/src`" (the engine keeps its TS index and reader until R4).
- **Fail-closed publish gate (robustness 17)**: `publishSheetVersion(client, versionId, validate)`, `validate` required; anything but `{ok: true, value: {publishable: true}}` throws before the RPC; test with a failing core.
- **Pages (simplicity 11)**: Home and `/new` read the sheet availability from the bundle without the core; the core loads at `/new` submit, on an import file pick, and in the editor.
- **Display glue accepted (simplicity 12)**: `VertebraPicker` `has` and the grid extent, `FindingsTreePicker` `matches` / `isLeafSelected` / `countSelectedUnder`, `ObservationCard` `zoneTrees` / `unresolvedFindings` / `describeZone`, import message lines: render-time predicates over core data, listed in the RUST.md census.
- **Docker / serving (robustness 12, 14, 15, 13; simplicity 9, 10)**: `packages/core-wasm/package.json` in the manifest COPY list; `pkg-proofs/` git- and docker-ignored; wasm-bindgen runs in the same RUN as the cache-mounted cargo build; the wasm-bindgen version shares the builder's `ARG` line, `scripts/wasm-build.sh` keeps the `Cargo.lock` guard; a check that the shipped `pkg/faunosteo_wasm.d.ts` has no proof export. CSP proof = `docker/csp-proof` extended to the app image: with the keyword the editor loads and one zone click works; without it the editor shows the degraded state and `/login` works; network-level assertion that `/login` and `/app/account` request neither the glue nor the `.wasm`; Firefox and WebKit too when their Playwright builds are present (else recorded). DEPLOY.md: R2+ images are never built on the VPS; the CSP must carry `'wasm-unsafe-eval'` before an R2 image is deployed.
- **Kept, with reason**: the N-1 verbatim copy (already committed; permanent, survives R5); `vertebra.select` in the core (review II.2 class A, owner listed "Sélection vertébrale"); one gate for R2 with an owner-facing checkpoint report after R2.4 (no stop: the owner asked to stop after R2).
- **Interim risks stated (robustness 8, 11)**: the import reads up to the 16 MiB attachment in the long-lived main instance until R4 moves it to a Worker; no React error boundary is added (no UI change at R2), every core entry point catches.
- **Owner decision to confirm at delivery (correctness 9)**: L1, a lone UTF-16 surrogate escape in a draft or an archive becomes U+FFFD instead of refusing the document.
- `pickLabel` → the existing `apps/app/src/i18n/pickLocaleLabel.ts` (object overload), no new copy (simplicity 6). `mini-sheet.ts` conversion dropped (R3/R5, simplicity 8). `url` crate size measured at R2.4 against the budget (simplicity 14).
+1
View File
@@ -20,5 +20,6 @@ docs/
logos/
target/
packages/core-wasm/pkg/
packages/core-wasm/pkg-proofs/
docker/dev-gateway/htpasswd
docker/dev-gateway/mailpit-password
+1
View File
@@ -63,6 +63,7 @@ supabase/.temp/
# Rust workspace (R0): build output and the generated browser module
target/
packages/core-wasm/pkg/
packages/core-wasm/pkg-proofs/
# DEV gateway credentials (generated by scripts/dev-gateway.sh)
docker/dev-gateway/htpasswd
+8
View File
@@ -0,0 +1,8 @@
# Byte-exact oracles and generated fixtures: their tests compare bytes, never reformat them.
crates/core/tests/oracles/
crates/core/tests/conformance/
crates/core/tests/fixtures/
apps/app/tests/fixtures/goldens/
packages/core-wasm/types/
packages/core-wasm/pkg/
packages/core-wasm/pkg-proofs/
+8
View File
@@ -6,6 +6,14 @@ Versions follow [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Changed (Rust R2, domain core, 2026-10-14)
- **The application's domain rules run in Rust** (`crates/core`, through the wasm facade and `@faunosteo/core-wasm`): sheet, report and archive contracts with the Zod semantics reproduced, the 21 sheet integrity rules and the publish check, the sheet index, the v2 → v3 migration, the rebase on the loaded sheet, the sheet snapshot, the layered archive reading, the editor's click chain and reducers, the findings and vertebra rules, report creation and the observation list operations. Consumers switched: the editor, the pickers, the store, the draft restore, the PDF import (after the engine's byte scan) and export (snapshot), the Supabase publish gate (fails closed). The module (340 KB gzip) loads only on the sheet pages; sign-in, the `/app` space and Home never request it. Without `'wasm-unsafe-eval'` in the CSP the editor shows a degraded notice with a retry and leaves the session's draft untouched (DEPLOY.md: set the keyword before deploying an R2 image; R2 images are never built on the VPS).
- **Session data never dropped silently**: an unreadable draft or archive is set aside under `osteo:quarantine:*` with a notice; a draft rebased with unresolved items keeps its raw text.
- Behaviour differences, declared in `docs/development/RUST.md` §8.7: drafts and attachments written in contract order (values unchanged, the previous build reads them, D-R11); typed errors on inputs the interface never produced.
- **Lone UTF-16 surrogates refused, never altered** (L1, owner decision): a draft, archive or attachment whose JSON escapes a lone surrogate is no longer read with U+FFFD in its place. The draft or archive is set aside verbatim under its quarantine key with the existing notice; a PDF import is refused with a new message (malformed text, file not modified); an editor action is refused and the report left as it was.
- Proofs: contracts byte-equal to the Zod output on the reference documents, the three archive envelopes frozen before the switch and deep-equal after, 924 cases and verdicts frozen from the TypeScript, permanent N-1 reader test, generated pgTAP conformance file (real stack 446/446), CSP proof on the real image. No interface, archive format, database or graphic change; release 0.2.0 untouched.
### Changed (development environment, 2026-10-13)
- **DEV on the private network** — the owner tests from other devices: the DEV origin (the machine's LAN address, `FAUNOSTEO_DEV_HOST`, detected or set) lives in `scripts/dev-env.sh`; `pnpm dev` serves the app on that origin wired to the local stack, `pnpm dev:offline` keeps the local tool alone; every Supabase CLI call goes through `scripts/supabase.sh` so `config.toml` (API external URL for the mail links, site URL, Studio API URL via `env()`) follows the origin; private-network redirect URLs for the PKCE links. Identity recorded: Faunosteo, https://faunosteo.com; environments DEV / STAGING / PROD and the exposure table in `docs/development/ENVIRONMENTS.md`.
+48 -31
View File
@@ -35,6 +35,12 @@ routes stay unauthenticated. Step 8 (= Rust R1) added the files foundation: the
the Rust worker `crates/worker` (keyed job loop + keyless sandboxed decode child)
producing 512 × 512 WebP avatars, a deferred purge queue, and the profile photo in
Mon compte, the sidebar, the drawer and the top bar (`docs/development/STORAGE.md`).
Rust R2 moved the application's domain rules into `crates/core` (sheet, report and
archive contracts, integrity rules, sheet index, migration, rebase, snapshot, layered
archive reading, editor reducers, findings and vertebra rules, report operations),
reached through the wasm facade and `packages/core-wasm`, loaded lazily by the sheet
pages only (`docs/development/RUST.md` §8); `packages/domain` is frozen for the PDF
engine, the pipeline and the compare CLI.
MVP species: equine only. Open-source MIT.
---
@@ -198,10 +204,10 @@ faunosteo/
│ ├─ auth/{validation,redirects,useAuthFailureMessage}.ts ← Zod schemas (i18n keys), safe next path, failure phrasing
│ ├─ account/{validation,useProfileForm}.ts ← account section schemas + one-save form hook
│ ├─ config/env.ts ← runtime config resolution
│ ├─ sheets/{provider,useSheet}.ts ← SheetProvider interface, bundled implementation, per-species hook
│ ├─ sheets/{provider,useSheet}.ts ← raw bundled payload; useSheet loads it into the core (ready / none / core_unavailable / invalid_sheet + retry), useSheetAvailability without the core
│ ├─ core/{runtime,sheetOps,reportOps}.ts ← the page's CoreRuntime (Vite asset URLs, lazy), typed sheet-bound and free core operations
│ ├─ services/
│ │ ├─ sheetIndex.ts ← read-only lookups over the loaded sheet (ids, never labels)
│ │ ├─ zoneInteraction.ts ← pure click decision + observation reducers (zones, sides, vertebrae)
│ │ ├─ sheetIndex.ts ← SheetIndex class: reads the core's SheetIndexData (ids, never labels) + `ops`
│ │ └─ localeSync.ts ← profiles.locale ↔ localeStore (account wins on sign-in)
│ ├─ i18n/
│ │ ├─ types.ts ← Locale type + Dict type
@@ -210,7 +216,7 @@ faunosteo/
│ │ └─ useT.ts ← useT() hook (reads localeStore)
│ ├─ state/
│ │ ├─ authStore.ts ← session, user, profile, roles, recovery flag (onAuthStateChange)
│ │ ├─ reportStore.ts ← Zustand store (Report v3) + persistence.ts (sessionStorage adapter, v2 draft migration)
│ │ ├─ reportStore.ts ← Zustand store (Report v3, core-built reports, actions answer { ok }) + persistence.ts (raw texts, quarantine keys)
│ │ ├─ localeStore.ts ← locale Zustand store (persisted to localStorage)
│ │ └─ practitionerCache.ts ← localStorage prefill
│ ├─ anatomy/drawing.ts ← sanitised asset + generated annotation layer → inline <svg> per view
@@ -271,15 +277,15 @@ faunosteo/
│ │ └─ draft/ ← GENERATED working revision: document, cleaned horse.svg, sheet-ref, report-migration-map, CHANGELOG, REVIEW-REPORT, review/*.svg, equine_draft.sql
│ └─ tests/*.sql ← pgTAP: allowed + denied paths per policy
├─ packages/README.md ← shared packages index
├─ packages/core-wasm/ ← @faunosteo/core-wasm: loader of the browser module (pkg/ built, git-ignored), ts-rs types (committed), R0 proofs (panic, serialisation, size)
├─ packages/core-wasm/ ← @faunosteo/core-wasm: CoreRuntime (lazy, poison, recovery) + Node source, pkg/ shipped and pkg-proofs/ (built, git-ignored, BUILD_STAMP), ts-rs types (committed), frozen N-1 reader (tests/n-1), tests
├─ crates/ ← Rust workspace (Cargo.toml, rust-toolchain.toml, deny.toml, clippy.toml, .cargo/config.toml at the root)
│ ├─ core/ ← faunosteo-core: contracts (report types), js_number + JS pretty formatter, facade `call(op, json)`; no I/O, no clock (lint-enforced)
│ ├─ wasm/ ← faunosteo-wasm: wasm-bindgen facade (core_version, call, R0 trap proofs)
│ ├─ core/ ← faunosteo-core: domain/{js,sheet,report,archive,editor,session} (contracts and rules), ops.rs + facade.rs (`call`, `call_with_sheet`), json (JS number printing); tests/{oracles,conformance,fixtures} frozen from the TypeScript; no I/O, no clock (lint-enforced)
│ ├─ wasm/ ← faunosteo-wasm: wasm-bindgen facade (core_version, call, SheetHandle; trap exports in the proofs build only)
│ └─ worker/ ← faunosteo-worker: plain main; `decode` sandboxed child (rlimits, seccomp allowlist, image → libwebp), parent Spawner + RIFF check; R1 `run` loop: config, log (JSON lines, allowlist), keys, backend trait + http (ureq, PostgREST rpc + Storage objects), job, sweep, watchdog; Dockerfile, scripts/derive-seccomp.sh
├─ scripts/{rust-env,rust-check,wasm-build,check-all,avatar-e2e}.sh ← native Rust gate, wasm build, the pre-merge gate (`pnpm check:all`), the real-stack avatar e2e
├─ scripts/{rust-env,rust-check,wasm-build,check-all,avatar-e2e}.sh, wasm-stamp.mjs ← native Rust gate, wasm build (pkg + pkg-proofs + stamp), the pre-merge gate (`pnpm check:all`), the real-stack avatar e2e
├─ scripts/{dev-env,supabase,dev}.sh ← the DEV origin (LAN address) in one place; CLI wrapper; `pnpm dev` on that origin
├─ docker-compose.yml ← `app` service; `worker` service under the `worker` profile (read-only, cap_drop ALL, external Supabase network, `.env.worker`)
├─ docker/rust-builder.Dockerfile, rust-run.sh, csp-proof/ ← reproducible Rust builder (alternative) + the CSP proof
├─ docker/rust-builder.Dockerfile, rust-run.sh, csp-proof/ ← reproducible Rust builder (alternative) + the CSP proofs (R0 module, R2 app image: app-image.sh)
├─ .gitea/workflows/ci.yml ← PREPARED, never executed (no runner): rust job (builder image, scripts/rust-check.sh, types drift, wasm), install, typecheck, test, lint, build, docker (app + worker test stage + runtime)
├─ .gitea/workflows/{rust-advisories,release-images}.yml ← nightly RustSec advisories; manual digest-tagged image publication (no deploy)
├─ .claude/{tasks/TODO.md,memory/,audits/}
@@ -299,20 +305,22 @@ User interaction
→ Zustand store (reportStore)
→ Components read store via selectors (no prop drilling)
Sheet loading
→ useSheet(speciesId) → SheetProvider (bundled: virtual:faunosteo-sheet, SHEET_BUNDLE=draft)
→ Zod-validated document + assets + migration map → buildSheetIndex()
Sheet loading (Rust core, RUST.md §8)
→ useSheet(speciesId) → SheetProvider (bundled: virtual:faunosteo-sheet, SHEET_BUNDLE=draft) → raw payload
→ coreRuntime().ready() (lazy; core_unavailable + retry on failure) → SheetHandle(payload): strict parse of the
document and migration map, index → index_data → SheetIndex (tables only) + ops (sheet-bound core calls)
SVG interaction
→ AnatomyCanvas builds the view: sanitised asset + renderAnnotationLayer() (markers from the document)
→ delegated click on [data-anno-id] → decideZoneClick() (services/zoneInteraction, pure)
→ AnatomyCanvas builds the view: sanitised asset + renderAnnotationLayer() (markers from the document; TS until R3)
→ delegated click on [data-anno-id] → sheet.ops.zoneClick(observation, id) (one core call: decision + new observation)
→ open_view → DetailModal (same drawing, view_box crop, or the view's own asset)
→ open_vertebra_picker / open_laterality_picker → pickers → reducers (ensureZone, addSides, syncVertebrae)
→ toggle / remove_both_sides → updateObservation() in store
→ open_vertebra_picker (initial selection from the core) / open_laterality_picker (sides present) → pickers
→ vertebra.select per tap, vertebra.sync / zone.add_sides on confirm → updateObservation() in store
→ toggle / remove_both_sides → the core's observation → updateObservation(); findings picker → finding.toggle
PDF export (app side: apps/app/src/pdf, engine: packages/pdf)
→ exportReportToPdf(report, index, { locale })
→ buildSheetSnapshot(index.sheet, report) + loadBranding() (4 logos bundled at build time, no network) + defaultPdfLabels
→ index.ops.snapshot(report) (core: archive.snapshot) + loadBranding() (4 logos bundled at build time, no network) + defaultPdfLabels
→ exportReportArchive({ report, sheet, branding, labels, locale, rasterizer: browserRasterizer, exportedAt })
assertSnapshot (caps, integrity, sheet invariant) → fonts (WinAnsi StandardFonts, safeText guard)
→ per observation: composeHighlightedViewSvg (xmldom: sanitise allowlist → composeViewSvg highlight) → rasterizer → page
@@ -321,11 +329,11 @@ PDF export (app side: apps/app/src/pdf, engine: packages/pdf)
→ exportFromEnvelope(envelope, …) re-exports an archive from its own snapshot, branding and labels (no sheet)
PDF import
→ importReportFromPdf(bytes, migrationMap) → readReportArchive (engine)
→ byte scan for the EmbeddedFile stream (no pdf-lib parse on untrusted bytes, BLK-009): named osteo-report* first,
capped native inflation → layered reading: report (v3 as is, v2 migrated, else incompatible_version),
envelope metadata tolerant, snapshot/branding/labels strict → archive kept or snapshotRejected (closed reason)
→ rebaseReportOnSheet(report, index, archivedSnapshot) when the loaded sheet differs (unresolved flags, labels kept)
→ readAttachment(bytes) → engine byte scan for the EmbeddedFile stream (TS until R4; no pdf-lib parse on untrusted
bytes, BLK-009): named osteo-report* first, capped native inflation, JSON depth pre-scan
→ loadSheetIndex (core loads here) → importAttachment(data, index) → core archive.import: layered reading (report:
v3 as is, v2 migrated, else incompatible_version; envelope metadata tolerant, snapshot/branding/labels strict →
archive kept or snapshotRejected) + rebase on the loaded sheet (unresolved flags, labels kept), one call
→ hydrateImport({ report, archive }) → one alert (archive_ok / snapshot_rejected / rebased / migrated) → navigate /editor
Identity (Step 7, docs/development/IDENTITY.md)
@@ -395,9 +403,14 @@ Database (Supabase)
and annotations); no graphic redesign without prior validation
### Schemas
- `packages/domain/src/report/*.ts` are the report data contracts (v3 current, v2 input only); never change
without bumping the version on a breaking change (additive optional fields keep it)
- All user-provided data goes through Zod parse before hitting the store
- The data contracts live in Rust since R2 (`crates/core/src/domain/{sheet,report,archive}`, Zod semantics
reproduced: strict where Zod was strict, optional absent, nullable required, Zod schema field order);
`packages/domain` is frozen (no new logic) for the PDF engine, the pipeline and the compare CLI until R4/R5,
and its Zod copy under `packages/core-wasm/tests/n-1` is the permanent N-1 reader. Never change a contract
without bumping the version on a breaking change (additive optional fields keep it); a change touches the
Rust struct, the regenerated ts-rs types and the N-1 test
- Every report entering the store comes from the core (new report, draft restore, import, reducer outputs);
form values are plain assignments (D-R7)
- Report version 3: zones by `(annotationId, viewId)`, findings by `(findingZoneId, path)`, severities
`mild|moderate|severe`, `sheet` reference; v2 is migrated through `report-migration-map.json`
(`migrateReportV2ToV3`, never throws on content, `unresolved: true` marks what the sheet no longer holds);
@@ -406,7 +419,7 @@ Database (Supabase)
### Stores
- No direct store mutation outside Zustand actions
- No business logic in components — delegate to store actions
- sessionStorage keys: osteo:draft (auto-saved on every change, v3; a v2 draft is migrated and a stale draft rebased on restore once the sheet is loaded) and osteo:archive (the imported archive envelope, written only on import / new report / reset, never on edits)
- sessionStorage keys: osteo:draft (auto-saved on every change, v3; a v2 draft is migrated and a stale draft rebased on restore once the sheet is loaded, by the core) and osteo:archive (the imported archive envelope, written only on import / new report / reset, never on edits); osteo:quarantine:{draft,archive} (an unreadable text set aside, newest only, never dropped) and osteo:quarantine:draft-pre-rebase (the raw draft of a rebase that flagged items)
- localStorage key: osteo:lastPractitioner (practitioner prefill cache)
### PDF
@@ -497,8 +510,10 @@ Database (Supabase)
## Rust by default (rule adopted 2026-10-12, BDR-043)
Study and roadmap: `docs/development/RUST_ARCHITECTURE_REVIEW.md` (awaiting
the owner's validation before any implementation; release 0.2.0 unaffected).
Study and roadmap: `docs/development/RUST_ARCHITECTURE_REVIEW.md` (validated with
the amendments of Annex C). Done: R0, R1 (worker), R2 (domain core used by the app,
`docs/development/RUST.md` §8). Next: R3 (anatomy core), R4 (PDF core), R5
(pipeline); release 0.2.0 unaffected.
- Any logic that can run in Rust with no significant loss (features, UX,
graphics, data compatibility, security, reliability, useful performance,
@@ -554,12 +569,14 @@ the owner's validation before any implementation; release 0.2.0 unaffected).
## Workflow expectations
- Run `pnpm typecheck && pnpm test:run` before every commit.
- Domain schema changes (`packages/domain/src/report/*.ts`) require updating all callers + bumping version if breaking.
- Run `pnpm typecheck && pnpm test:run` before every commit; after any change under `crates/core` or `crates/wasm`,
`pnpm wasm:build` first (the suites refuse a missing or stale module: BUILD_STAMP).
- Contract changes (`crates/core/src/domain`) require the ts-rs types regenerated and committed, all callers updated,
the N-1 reader test green, and a version bump if breaking. `apps/app/src` never imports `@faunosteo/domain` (ESLint).
- Annotation rendering changes require updating docs/ANNOTATION-RENDERING.md first.
- Never modify the legacy sources under `supabase/seed/anatomical-sheets/equine/legacy-sources/` — they are the
importer's input (the user's historical files).
- Ask before any change to `readReportArchive`, `readArchiveDocument`, `readAttachedDocument` or `rebaseReportOnSheet` — they handle user data; archive readers never drop a schema version (envelope v1, Report v2/v3, sheet document v2).
- Ask before any change to `readReportArchive`, `readArchiveDocument`, `readAttachedDocument` or `rebaseReportOnSheet`, and to their Rust ports (`crates/core/src/domain/{archive/read,report/rebase,report/read,session}.rs`) — they handle user data; archive readers never drop a schema version (envelope v1, Report v2/v3, sheet document v2).
- Import never parses untrusted PDF object graphs: the attachment is located by byte scan and inflated under the 16 MiB cap (BLK-009). Opening the import to external users is gated by `docs/development/PDF_IMPORT_HARDENING.md` §5 (BDR-040).
- After PDF roundtrip tests fail: check attachment bytes, then the layered reader (report first, envelope metadata, snapshot/branding/labels), then DecompressionStream inflation. Goldens under `apps/app/tests/fixtures/goldens/step6` are never regenerated without a user decision.
- Node 24 / pnpm 10.13.1: `corepack enable` or `corepack pnpm`; never a global install.
Generated
+1
View File
@@ -189,6 +189,7 @@ dependencies = [
"serde",
"serde_json",
"ts-rs",
"url",
]
[[package]]
+3 -1
View File
@@ -21,7 +21,9 @@ serde = { version = "1.0.229", features = ["derive"] }
# float_roundtrip: the default parser is a fast path that can be one ULP off (found by the R0
# proof: 1715.4285714285713 came back as 1715.428571428571); JavaScript parses correctly.
serde_json = { version = "1.0.154", features = ["preserve_order", "float_roundtrip"] }
ts-rs = { version = "12.0", features = ["serde-compat"] }
ts-rs = { version = "12.0", features = ["serde-compat", "no-serde-warnings"] }
# Zod `.url()` is `new URL()`: the WHATWG parser of the url crate reproduces it (R2 plan P2).
url = "2.5.8"
# The CLI in docker/rust-builder.Dockerfile must be this exact version.
wasm-bindgen = "=0.2.129"
image = { version = "0.25.10", default-features = false, features = ["jpeg", "png", "webp"] }
+23 -7
View File
@@ -608,6 +608,13 @@ builds. The procedure below is prepared and documented now; it replaces
this way is deployed, after a separate validation**. Until then the live
deployment keeps building on the VPS as documented above.
**From R2 on (`feature/rust-r2-domain-core`), the application image
compiles the Rust core** (Dockerfile stage `wasm`: the Rust toolchain and
`wasm-bindgen-cli` in a builder stage). Such an image is never built on the
VPS (1 vCPU, 1 GB): it is built on the development machine or a runner and
pulled by digest, with the CSP of the next section in place first. The live
deployment, built from `main` before R2, is not affected.
1. Build and publish: run the manual workflow `release-images`
(`.gitea/workflows/release-images.yml`, `workflow_dispatch`, never on
push) on the forge. Prerequisite not met yet: no runner, registry or
@@ -634,14 +641,23 @@ working with the read-only token.
### WebAssembly and the CSP (from R2 on)
The application does not load the Rust core module before plan R2. When it
does, the two `Content-Security-Policy` headers of this file (nginx and
Caddy options) must carry `'wasm-unsafe-eval'` in `script-src`:
From R2 the application loads the Rust core module in the sheet pages (the
editor, the new-report submit, the PDF import). Before an R2 image is
deployed, the two `Content-Security-Policy` headers of this file (nginx and
Caddy options above) must carry `'wasm-unsafe-eval'` in `script-src`; the
examples above still show the header of the live, pre-R2 deployment:
```text
script-src 'self' 'wasm-unsafe-eval';
```
Without the keyword an R2 image stays usable but degraded: the sign-in and
account pages work, the editor shows "Le moteur de calcul de Faunosteo n'a
pas pu être chargé" with a retry, and the tab's draft is left untouched
(proven on the image by `docker/csp-proof/app-image.sh`,
`docs/development/RUST.md` §8.5). The keyword adds nothing for a pre-R2
image, so it can be set on the proxy before the switch.
Proven at R0 under the production nginx image and headers with headless
Chrome for Testing 156 (`docker/csp-proof/run.sh`, result in
`docs/development/RUST.md` §5): with `script-src 'self'` the browser refuses
@@ -651,10 +667,10 @@ the module instantiates. `'wasm-unsafe-eval'` allows WebAssembly compilation
only, never `eval` or inline scripts (the proof's inline variant was still
blocked). Browser floor for the keyword: Chrome 97, Firefox 102, Safari 16
(the Vite 7 baseline). The `.wasm` file is served as `application/wasm` by
`nginx:1.31-alpine` out of the box; at R2 `docker/nginx.conf` gains
`gzip_static on;` for a precompressed `.wasm.gz` (or `gzip_types
application/wasm`) and the served, compressed size is what the D-R13 budget
counts.
`nginx:1.31-alpine` out of the box; since R2 the image precompresses it and
`docker/nginx.conf` serves the `.wasm.gz` with `gzip_static on;` (372 KB
served for 1.18 MB raw, D-R13 budget 600 KB). A proxy in front must pass
`Content-Encoding` through and keep the `application/wasm` type.
---
+29 -1
View File
@@ -1,3 +1,28 @@
# ---- stage 0: wasm --------------------------------------------------
# The Rust core compiled to the browser module (R2). Same toolchain and wasm-bindgen CLI
# as docker/rust-builder.Dockerfile (keep the two ARG lines equal); scripts/wasm-build.sh
# refuses a CLI that differs from the wasm-bindgen crate in Cargo.lock. The production VPS
# never builds this image: it pulls it by digest (DEPLOY.md).
FROM rust:1.99.0-bookworm AS wasm
ARG WASM_BINDGEN_VERSION=0.2.129
RUN rustup target add wasm32-unknown-unknown \
&& rustup component add rustfmt clippy \
&& cargo install wasm-bindgen-cli --version "${WASM_BINDGEN_VERSION}" --locked \
&& rm -rf /usr/local/cargo/registry
WORKDIR /w
COPY rust-toolchain.toml Cargo.toml Cargo.lock ./
COPY .cargo .cargo
COPY crates crates
COPY scripts/rust-env.sh scripts/wasm-build.sh scripts/
# The build and wasm-bindgen run in one RUN: the cache-mounted target never reaches the
# layer, the generated packages/core-wasm/pkg does.
RUN --mount=type=cache,target=/usr/local/cargo/registry \
--mount=type=cache,target=/w/target \
WASM_BUILD_SHIPPED_ONLY=1 bash scripts/wasm-build.sh
# ---- stage 1: builder -----------------------------------------------
# Node 24 LTS (Node 20 reached end-of-life on 2026-04-30). pnpm pinned to the
# same version as package.json "packageManager"; pnpm 11 needs Node >= 22.13
@@ -15,6 +40,7 @@ COPY packages/domain/package.json packages/domain/
COPY packages/anatomy/package.json packages/anatomy/
COPY packages/pdf/package.json packages/pdf/
COPY packages/supabase/package.json packages/supabase/
COPY packages/core-wasm/package.json packages/core-wasm/
RUN pnpm install --frozen-lockfile
@@ -25,13 +51,15 @@ RUN pnpm install --frozen-lockfile
ARG SHEET_BUNDLE=none
ENV SHEET_BUNDLE=$SHEET_BUNDLE
COPY . .
COPY --from=wasm /w/packages/core-wasm/pkg packages/core-wasm/pkg
RUN pnpm --filter @faunosteo/app build
# ---- stage 2: runner ------------------------------------------------
FROM nginx:1.31-alpine AS runner
# Copy built static assets
# Copy built static assets; the core module is served precompressed (gzip_static)
COPY --from=builder /app/apps/app/dist /usr/share/nginx/html
RUN gzip -9 -k /usr/share/nginx/html/assets/*.wasm
# Copy custom nginx config and entrypoint
COPY docker/nginx.conf /etc/nginx/conf.d/default.conf
+20
View File
@@ -38,4 +38,24 @@ export default tseslint.config(
],
},
},
{
// R2: the application's rules run in the Rust core; its contracts come from
// @faunosteo/core-wasm. The TypeScript domain stays frozen for the PDF engine, the
// pipeline and scripts/ until R4/R5 (RUST_ARCHITECTURE_REVIEW VI.4).
files: ['src/**/*.{ts,tsx}'],
rules: {
'no-restricted-imports': [
'error',
{
paths: [
{
name: '@faunosteo/domain',
message: 'Use @faunosteo/core-wasm (types) and the core operations.',
},
],
patterns: ['@faunosteo/domain/*'],
},
],
},
},
)
+1
View File
@@ -16,6 +16,7 @@
},
"dependencies": {
"@faunosteo/anatomy": "workspace:*",
"@faunosteo/core-wasm": "workspace:*",
"@faunosteo/domain": "workspace:*",
"@faunosteo/pdf": "workspace:*",
"@faunosteo/supabase": "workspace:*",
+8 -14
View File
@@ -27,8 +27,7 @@ import {
MAX_PDF_BYTES,
readAttachedDocument,
} from '@faunosteo/pdf'
import { parseBundledSheet } from '../src/sheets/provider'
import { buildSheetIndex, type SheetIndex } from '../src/services/sheetIndex'
import { compareSheetIndex, type CompareSheetIndex } from './compare/sheet'
import {
compareReport,
diffLines,
@@ -47,20 +46,15 @@ const SEED_DIR = resolve(
/** pnpm runs the script from apps/app; paths are typed from the caller's folder. */
const CWD = process.env.INIT_CWD ?? process.cwd()
function loadSheet(): SheetIndex {
function loadSheet(): CompareSheetIndex {
const json = (name: string) =>
JSON.parse(readFileSync(join(SEED_DIR, name), 'utf8')) as never
// The comparison needs the document and the map, not the drawings.
return buildSheetIndex(
parseBundledSheet({
status: 'draft',
ref: json('sheet-ref.json'),
document: json('document.json'),
migrationMap: json('report-migration-map.json'),
assets: {},
assetHashes: {},
}),
)
return compareSheetIndex({
ref: json('sheet-ref.json'),
document: json('document.json'),
migrationMap: json('report-migration-map.json'),
})
}
/** A folder stands for its PDFs; any other argument stays one entry. */
@@ -79,7 +73,7 @@ function expandArg(arg: string): string[] {
async function compareFile(
path: string,
sheet: SheetIndex,
sheet: CompareSheetIndex,
args: CliArgs,
): Promise<Comparison> {
const st = statSync(path)
+2 -1
View File
@@ -1,4 +1,5 @@
import {
pickLabel,
ReportV2Schema,
findingPathKey,
type ArchiveReadOutcome,
@@ -9,7 +10,7 @@ import {
type ReportZone,
} from '@faunosteo/domain'
import type { Locale } from '../../src/i18n/types'
import { pickLabel, type SheetIndex } from '../../src/services/sheetIndex'
import type { CompareSheetIndex as SheetIndex } from './sheet'
/**
* Pure comparison of a report document found in a PDF with its v3 reading:
+45
View File
@@ -0,0 +1,45 @@
import {
AnatomicalSheetDocumentSchema,
buildSheetIndex,
ReportMigrationMapSchema,
type AnatomicalSheetDocument,
type ReportMigrationMap,
type SheetIndex,
type SheetRef,
} from '@faunosteo/domain'
/**
* The reference sheet as the archive check tool reads it: the frozen TypeScript domain
* (Zod schemas and index), as the application did before R2. The tool moves to the Rust
* core with the PDF reader at R4 (RUST_ARCHITECTURE_REVIEW VI.4); until then it keeps its
* own reading, independent of the application's core runtime.
*/
export interface CompareSheet {
status: 'draft' | 'published'
ref: SheetRef
document: AnatomicalSheetDocument
assets: Readonly<Record<string, string>>
migrationMap: ReportMigrationMap
}
export type CompareSheetIndex = SheetIndex<CompareSheet>
/** The seed files of the reference sheet, parsed and indexed. */
export function compareSheetIndex(seed: {
ref: { sheet_id: string; version_id: string | null; document_sha256: string }
document: unknown
migrationMap: unknown
}): CompareSheetIndex {
return buildSheetIndex({
status: 'draft',
ref: {
sheetId: seed.ref.sheet_id,
versionId: seed.ref.version_id,
documentSha256: seed.ref.document_sha256,
},
document: AnatomicalSheetDocumentSchema.parse(seed.document),
assets: {},
migrationMap: ReportMigrationMapSchema.parse(seed.migrationMap),
})
}
+1 -1
View File
@@ -3,7 +3,7 @@ import {
renderAnnotationLayer,
viewBoxOf,
} from '@faunosteo/anatomy/render'
import type { SheetView } from '@faunosteo/domain'
import type { SheetView } from '@faunosteo/core-wasm/types'
import type { SheetIndex } from '@/services/sheetIndex'
/**
+103 -58
View File
@@ -3,7 +3,10 @@ import { useNavigate } from 'react-router-dom'
import AnatomyCanvas from '@/components/canvas/AnatomyCanvas'
import DetailModal from '@/components/canvas/DetailModal'
import ObservationList from '@/components/observation/ObservationList'
import ObservationPickers from '@/components/observation/ObservationPickers'
import ObservationPickers, {
type LateralTarget,
type VertebraTarget,
} from '@/components/observation/ObservationPickers'
import ConclusionPanel from '@/components/report/ConclusionPanel'
import ReportHeader from '@/components/report/ReportHeader'
import EditInfosDialog, {
@@ -11,25 +14,22 @@ import EditInfosDialog, {
type Identity,
} from '@/components/report/EditInfosDialog'
import DisclaimerDialog from '@/components/report/DisclaimerDialog'
import CoreUnavailable from '@/components/report/CoreUnavailable'
import Button from '@/components/ui/Button'
import { useReportStore } from '@/state/reportStore'
import {
useReportStore,
type ActionResult,
type RestoreResult,
} from '@/state/reportStore'
import { writeCachedPractitioner } from '@/state/practitionerCache'
import { useLocaleStore } from '@/state/localeStore'
import { useSheet } from '@/sheets/useSheet'
import { pickLabel, type SheetIndex } from '@/services/sheetIndex'
import {
decideZoneClick,
ensureZone,
refOf,
removeAllSides,
removeZoneAt,
toggleZone,
type ZoneRef,
} from '@/services/zoneInteraction'
import type { SheetIndex } from '@/services/sheetIndex'
import { pickLabel } from '@/i18n/pickLocaleLabel'
import type { ViewStates } from '@/anatomy/drawing'
import { exportReportToPdf } from '@/pdf/export'
import type { ExportWarning } from '@faunosteo/pdf'
import type { RebaseOutcome } from '@faunosteo/domain'
import type { RebaseOutcome } from '@faunosteo/core-wasm/types'
import { useT } from '@/i18n/useT'
import { DEFAULT_SPECIES_ID } from './NewReportRoute'
@@ -45,6 +45,19 @@ function unresolvedCountOf(outcome: RebaseOutcome): number {
return outcome.unresolvedZones + outcome.unresolvedFindings
}
/** The alert of a restore, if any: a rebase on another sheet or a draft set aside. */
function restoreAlert(
result: RestoreResult,
t: ReturnType<typeof useT>,
): string | null {
if (result.kind === 'quarantined') return t('editor.draft_quarantined')
if (result.kind === 'restored' && result.rebase.rebased) {
const count = String(unresolvedCountOf(result.rebase))
return t('editor.draft_rebased').replace('{count}', count)
}
return null
}
/** Editor on the reference sheet: wires the canvas, the pickers and the store. */
export default function EditorRoute() {
const navigate = useNavigate()
@@ -56,8 +69,14 @@ export default function EditorRoute() {
const sheet = useSheet(report?.animal.speciesId ?? DEFAULT_SPECIES_ID)
const [detailViewId, setDetailViewId] = useState<string | null>(null)
const [vertebraTarget, setVertebraTarget] = useState<number | null>(null)
const [lateralTarget, setLateralTarget] = useState<ZoneRef | null>(null)
const [vertebraTarget, setVertebraTarget] = useState<VertebraTarget | null>(
null,
)
const [lateralTarget, setLateralTarget] = useState<LateralTarget | null>(
null,
)
// The core failed while reading the draft: stay here, keep the draft, offer a retry.
const [restoreFailed, setRestoreFailed] = useState(false)
const [disclaimer, setDisclaimer] = useState<string | null>(null)
const [exporting, setExporting] = useState(false)
const [editDraft, setEditDraft] = useState<Identity | null>(null)
@@ -69,15 +88,24 @@ export default function EditorRoute() {
}, [])
// No report in memory: restore the per-tab draft once the sheet is known.
// A draft rebased on another sheet is announced with its unresolved count.
// A draft rebased on another sheet is announced with its unresolved count,
// an unreadable one is set aside. While the core cannot run, nothing is
// read or written and the page stays on the degraded notice (no redirect).
useEffect(() => {
if (report) return
if (sheet.status === 'core_unavailable' || sheet.status === 'invalid_sheet')
return
if (sheet.status === 'ready') {
const outcome = store.restoreDraft(sheet.index)
if (outcome?.rebased && !rebaseAlerted.current) {
const result = store.restoreDraft(sheet.index)
// Nothing could be read or set aside: stay, keep the draft where it is.
if (result?.kind === 'core_unavailable' || result?.kind === 'unreadable_kept') {
setRestoreFailed(true)
return
}
const alert = result ? restoreAlert(result, t) : null
if (alert && !rebaseAlerted.current) {
rebaseAlerted.current = true
const count = String(unresolvedCountOf(outcome))
window.alert(t('editor.draft_rebased').replace('{count}', count))
window.alert(alert)
}
}
if (sheet.status !== 'loading' && !useReportStore.getState().report)
@@ -111,42 +139,56 @@ export default function EditorRoute() {
if (sheet.status !== 'ready' || !report) return
const activeObs =
activeIndex >= 0 ? report.observations[activeIndex] : undefined
const index = sheet.index
const annotation = index.annotation(annotationId)
const decision = decideZoneClick(annotation, activeObs)
if (!annotation) return
switch (decision.kind) {
case 'ignore':
return
const outcome = sheet.index.ops.zoneClick(activeObs ?? null, annotationId)
if (!outcome.ok) return window.alert(t('core.action_failed'))
const click = outcome.value
if (click.observation) store.updateObservation(activeIndex, click.observation)
switch (click.kind) {
case 'open_view':
return setDetailViewId(decision.viewId)
return setDetailViewId(click.viewId ?? null)
case 'activate_fallback':
return store.setActiveObservation(report.observations.length - 1)
case 'open_vertebra_picker': {
const { observation, index: zoneIndex } = ensureZone(
activeObs!,
annotation,
)
store.updateObservation(activeIndex, observation)
return setVertebraTarget(zoneIndex)
}
case 'open_vertebra_picker':
return setVertebraTarget({
zoneIndex: click.zoneIndex ?? 0,
initial: click.vertebrae ?? [],
})
case 'open_laterality_picker':
return setLateralTarget(refOf(annotation))
case 'remove_both_sides':
return store.updateObservation(
activeIndex,
removeAllSides(activeObs!, refOf(annotation)),
)
case 'toggle':
return store.updateObservation(
activeIndex,
toggleZone(activeObs!, annotation),
)
return setLateralTarget({
annotationId,
sidesPresent: click.sidesPresent ?? [],
})
default:
return
}
},
[sheet, store],
[sheet, store, t],
)
/** A store action the core ran: the practitioner hears about a failure. */
const guarded = useCallback(
(result: ActionResult) => {
if (!result.ok) window.alert(t('core.action_failed'))
},
[t],
)
/** The vertebra picker opened from a zone chip: the core computes its selection. */
function openVertebraPicker(index: SheetIndex, zoneIndex: number) {
if (!activeObs) return
const outcome = index.ops.vertebraInitial(activeObs, zoneIndex)
if (!outcome.ok) return window.alert(t('core.action_failed'))
setVertebraTarget({ zoneIndex, initial: outcome.value })
}
function removeZone(index: SheetIndex, i: number, zoneIndex: number) {
const obs = report?.observations[i]
if (!obs) return
const outcome = index.ops.removeZoneAt(obs, zoneIndex)
if (outcome.ok) store.updateObservation(i, outcome.value)
else window.alert(t('core.action_failed'))
}
function acknowledgeDisclaimer() {
sessionStorage?.setItem(DISCLAIMER_FLAG, '1')
setDisclaimer(null)
@@ -190,6 +232,12 @@ export default function EditorRoute() {
}
}
if (sheet.status === 'core_unavailable' || sheet.status === 'invalid_sheet') {
return <CoreUnavailable onRetry={sheet.retry} />
}
if (restoreFailed) {
return <CoreUnavailable onRetry={() => window.location.reload()} />
}
if (!report) return null
if (sheet.status === 'loading') {
return (
@@ -218,7 +266,7 @@ export default function EditorRoute() {
<section className="border border-[var(--color-border)] rounded-2xl bg-[var(--color-surface)] overflow-hidden max-h-[55vh] lg:max-h-none flex flex-col">
<AnatomyCanvas
index={index}
viewId={index.mainView.id}
viewId={index.mainViewId}
states={states}
onZoneClick={onZoneClick}
className="flex-1"
@@ -241,19 +289,16 @@ export default function EditorRoute() {
onToggle={(i) =>
store.setActiveObservation(activeIndex === i ? -1 : i)
}
onAdd={store.addObservation}
onDelete={store.removeObservation}
onMoveUp={store.moveObservationUp}
onMoveDown={store.moveObservationDown}
onAdd={() => guarded(store.addObservation())}
onDelete={(i) => guarded(store.removeObservation(i))}
onMoveUp={(i) => guarded(store.moveObservationUp(i))}
onMoveDown={(i) => guarded(store.moveObservationDown(i))}
sheet={index}
onChange={store.updateObservation}
onOpenVertebraPicker={(_i, zoneIndex) =>
setVertebraTarget(zoneIndex)
openVertebraPicker(index, zoneIndex)
}
onRemoveZone={(i, zoneIndex) => {
const obs = report.observations[i]
if (obs) store.updateObservation(i, removeZoneAt(obs, zoneIndex))
}}
onRemoveZone={(i, zoneIndex) => removeZone(index, i, zoneIndex)}
/>
<ConclusionPanel
conclusion={report.conclusion}
+23 -17
View File
@@ -1,18 +1,21 @@
import { useNavigate } from 'react-router-dom'
import { useRef, useState } from 'react'
import {
rebaseReportOnSheet,
type ArchiveReadOutcome,
type RebaseOutcome,
} from '@faunosteo/domain'
import type {
ArchiveReadOutcome,
RebaseOutcome,
} from '@faunosteo/core-wasm/types'
import AppHeader from '@/components/brand/AppHeader'
import HomeSpaceLink from '@/components/brand/HomeSpaceLink'
import Button from '@/components/ui/Button'
import Card from '@/components/ui/Card'
import { importReportFromPdf, ImportError, MAX_PDF_BYTES } from '@/pdf/import'
import {
importAttachment,
ImportError,
MAX_PDF_BYTES,
readAttachment,
} from '@/pdf/import'
import { useReportStore } from '@/state/reportStore'
import { useSheet } from '@/sheets/useSheet'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadSheetIndex, useSheetAvailability } from '@/sheets/useSheet'
import { DEFAULT_SPECIES_ID } from './NewReportRoute'
import { useT } from '@/i18n/useT'
@@ -100,6 +103,10 @@ function importErrorMessage(err: unknown, t: Translate): string {
return t('home.import.error_attachment_stripped')
case 'no_attachment':
return t('home.import.error_no_attachment')
case 'lone_surrogate':
return t('home.import.error_lone_surrogate')
case 'core_unavailable':
return t('home.import.error_core_unavailable')
}
}
@@ -107,22 +114,21 @@ export default function HomeRoute() {
const navigate = useNavigate()
const fileRef = useRef<HTMLInputElement | null>(null)
const hydrateImport = useReportStore((s) => s.hydrateImport)
const sheet = useSheet(DEFAULT_SPECIES_ID)
// The page only needs to know a sheet exists; the core loads when a file is picked.
const sheet = useSheetAvailability(DEFAULT_SPECIES_ID)
const [error, setError] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
const t = useT()
/** Read, rebase onto the loaded sheet, open; the editor always works on that sheet. */
async function importFile(file: File, index: SheetIndex) {
async function importFile(file: File) {
// The engine refuses the same size; checking first keeps a huge file out of memory.
if (file.size > MAX_PDF_BYTES) throw new ImportError('invalid_pdf')
const bytes = new Uint8Array(await file.arrayBuffer())
const outcome = await importReportFromPdf(bytes, index.sheet.migrationMap)
const rebase = rebaseReportOnSheet(
outcome.report,
index,
outcome.archive?.sheetSnapshot ?? null,
)
const attachment = await readAttachment(bytes)
const index = await loadSheetIndex(DEFAULT_SPECIES_ID)
if (!index) throw new ImportError('core_unavailable')
const { read: outcome, rebase } = importAttachment(attachment, index)
hydrateImport({ report: rebase.report, archive: outcome.archive })
const lines = importMessages(outcome, rebase, t)
if (lines.length > 0) window.alert(lines.join('\n\n'))
@@ -135,7 +141,7 @@ export default function HomeRoute() {
setBusy(true)
setError(null)
try {
await importFile(file, sheet.index)
await importFile(file)
} catch (err) {
setError(importErrorMessage(err, t))
} finally {
+16 -9
View File
@@ -1,6 +1,6 @@
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import type { Animal, Owner, Practitioner } from '@faunosteo/domain'
import type { Animal, Owner, Practitioner } from '@faunosteo/core-wasm/types'
import PractitionerForm from '@/components/report/PractitionerForm'
import AnimalForm from '@/components/report/AnimalForm'
import AppHeader from '@/components/brand/AppHeader'
@@ -13,7 +13,8 @@ import {
writeCachedPractitioner,
} from '@/state/practitionerCache'
import { useReportStore } from '@/state/reportStore'
import { useSheet } from '@/sheets/useSheet'
import { useSheetAvailability } from '@/sheets/useSheet'
import { coreRuntime } from '@/core/runtime'
import { useT } from '@/i18n/useT'
/** The one species this build ships a sheet for. */
@@ -23,7 +24,8 @@ export default function NewReportRoute() {
const navigate = useNavigate()
const initReport = useReportStore((s) => s.initReport)
const t = useT()
const sheet = useSheet(DEFAULT_SPECIES_ID)
// The form needs the sheet's reference and name only; the core loads on submit.
const sheet = useSheetAvailability(DEFAULT_SPECIES_ID)
const [practitioner, setPractitioner] = useState<Practitioner>({ name: '' })
const [animal, setAnimal] = useState<Animal>({
@@ -44,10 +46,14 @@ export default function NewReportRoute() {
owner.name.trim() &&
sheet.status === 'ready'
function submit() {
async function submit() {
if (!canSubmit || sheet.status !== 'ready') return
writeCachedPractitioner(practitioner)
initReport(
if (!(await coreRuntime().ready())) {
window.alert(t('sheet.core_unavailable'))
return
}
const created = initReport(
{
date,
practitioner,
@@ -57,9 +63,10 @@ export default function NewReportRoute() {
conclusion: '',
recommendations: '',
},
sheet.index.sheet.ref,
sheet.sheet.ref,
)
navigate('/editor')
if (created.ok) navigate('/editor')
else window.alert(t('core.action_failed'))
}
return (
@@ -91,8 +98,8 @@ export default function NewReportRoute() {
sheet.status === 'ready'
? [
{
id: sheet.index.sheet.speciesId,
name: sheet.index.sheet.document.name,
id: sheet.sheet.speciesId,
name: sheet.sheet.name,
},
]
: [
@@ -7,9 +7,9 @@ import type {
FindingZone,
LateralSide,
LocalizedOptionalText,
} from '@faunosteo/domain'
} from '@faunosteo/core-wasm/types'
import Button from '@/components/ui/Button'
import { pickLabel } from '@/services/sheetIndex'
import { pickLabel } from '@/i18n/pickLocaleLabel'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
import type { Locale } from '@/i18n/types'
@@ -25,7 +25,11 @@ export interface FindingsTreePickerProps {
zone: FindingZone
side?: LateralSide
selected: Finding[]
onChange: (next: Finding[]) => void
/**
* A leaf was ticked or unticked: its path and its position among the siblings shown.
* The parent has the core build or remove the finding (R2).
*/
onToggle: (leafPath: string[], leafPosition: number) => void
}
function isLeaf(node: TreeNode): boolean {
@@ -69,13 +73,14 @@ function descriptionOf(node: TreeNode, locale: Locale): string | undefined {
/**
* Drill-down picker over one finding zone of the sheet. A finding is keyed
* by `(findingZoneId, path, side)`; labels are snapshotted at selection.
* by `(findingZoneId, path, side)`; the core snapshots its labels when it
* builds it. The selection predicates below only decide what is shown.
*/
export default function FindingsTreePicker({
zone,
side,
selected,
onChange,
onToggle,
}: FindingsTreePickerProps) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
@@ -125,25 +130,6 @@ export default function FindingsTreePicker({
selected.filter((f) => matches(f) && pathStartsWith(f.path, nodePath))
.length
function toggleLeaf(leafPath: string[], leaf: TreeNode) {
if (isLeafSelected(leafPath)) {
onChange(
selected.filter((f) => !(matches(f) && samePath(f.path, leafPath))),
)
return
}
const next: Finding = {
findingZoneId: zone.id,
path: leafPath,
labelFrSnapshot: leaf.name.fr,
labelEnSnapshot: leaf.name.en,
}
if ('requires_vet_referral' in leaf && leaf.requires_vet_referral)
next.requiresVetReferral = true
if (side) next.side = side
onChange([...selected, next])
}
const focusedDescription = focusedNode && descriptionOf(focusedNode, locale)
return (
@@ -202,7 +188,7 @@ export default function FindingsTreePicker({
{t('findings.no_options')}
</li>
) : (
currentNodes.map((node) => {
currentNodes.map((node, position) => {
const nodePath = [...path, node.id]
const nodeLabel = pickLabel(node.name, locale)
const nodeDesc = descriptionOf(node, locale)
@@ -215,7 +201,7 @@ export default function FindingsTreePicker({
<input
type="checkbox"
checked={isLeafSelected(nodePath)}
onChange={() => toggleLeaf(nodePath, node)}
onChange={() => onToggle(nodePath, position)}
className="mt-1 accent-[var(--color-accent)]"
aria-label={nodeLabel}
/>
@@ -1,6 +1,6 @@
import Dialog from '@/components/ui/Dialog'
import Button from '@/components/ui/Button'
import type { LateralSide } from '@faunosteo/domain'
import type { LateralSide } from '@faunosteo/core-wasm/types'
import { useT } from '@/i18n/useT'
export interface LateralityPickerProps {
@@ -5,7 +5,7 @@ import type {
LateralSide,
Observation,
ReportZone,
} from '@faunosteo/domain'
} from '@faunosteo/core-wasm/types'
import { AnimatePresence, motion } from 'motion/react'
import Card from '@/components/ui/Card'
import Badge from '@/components/ui/Badge'
@@ -15,7 +15,8 @@ import Textarea from '@/components/ui/Textarea'
import FindingsTreePicker from './FindingsTreePicker'
import FreeTextFindingInput from './FreeTextFindingInput'
import SeveritySelector from './SeveritySelector'
import { isObservable, pickLabel, type SheetIndex } from '@/services/sheetIndex'
import { isObservable, type SheetIndex } from '@/services/sheetIndex'
import { pickLabel } from '@/i18n/pickLocaleLabel'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
import type { Locale } from '@/i18n/types'
@@ -96,7 +97,7 @@ function unresolvedFindings(
sheet: SheetIndex,
): Finding[] {
return observation.findings.filter(
(f) => !sheet.nodeAt(f.findingZoneId, f.path),
(f) => !sheet.hasNode(f.findingZoneId, f.path),
)
}
@@ -152,6 +153,23 @@ export default function ObservationCard({
event.stopPropagation()
fn()
}
/** The core builds or removes the finding of the clicked leaf (R2). */
function toggleFinding(
findingZoneId: string,
side: LateralSide | undefined,
path: string[],
leafPosition: number,
) {
const outcome = sheet.ops.toggleFinding({
observation,
findingZoneId,
path,
leafPosition,
...(side ? { side } : {}),
})
if (outcome.ok) onChange(outcome.value)
else window.alert(t('core.action_failed'))
}
const removeFinding = (target: Finding) =>
onChange({
...observation,
@@ -379,11 +397,8 @@ export default function ObservationCard({
zone={zone}
side={side}
selected={observation.findings}
onChange={(next) =>
onChange({
...observation,
findings: next,
})
onToggle={(path, leafPosition) =>
toggleFinding(zone.id, side, path, leafPosition)
}
/>
</div>
@@ -1,4 +1,4 @@
import type { Observation } from '@faunosteo/domain'
import type { Observation } from '@faunosteo/core-wasm/types'
import ObservationCard from './ObservationCard'
import Button from '@/components/ui/Button'
import type { SheetIndex } from '@/services/sheetIndex'
@@ -1,29 +1,39 @@
import type { LateralSide, Observation } from '@faunosteo/domain'
import type {
LateralSide,
Observation,
Vertebra,
} from '@faunosteo/core-wasm/types'
import VertebraPicker from '@/components/observation/VertebraPicker'
import LateralityPicker from '@/components/observation/LateralityPicker'
import { useReportStore } from '@/state/reportStore'
import { useLocaleStore } from '@/state/localeStore'
import { isObservable, pickLabel, type SheetIndex } from '@/services/sheetIndex'
import {
addSides,
collectVertebrae,
sidesPresent,
syncVertebrae,
type ZoneRef,
} from '@/services/zoneInteraction'
import { isObservable, type SheetIndex } from '@/services/sheetIndex'
import { pickLabel } from '@/i18n/pickLocaleLabel'
import { useT } from '@/i18n/useT'
/** The zone the vertebra picker edits, with its initial selection (computed on open). */
export interface VertebraTarget {
zoneIndex: number
initial: Vertebra[]
}
/** The bilateral annotation the laterality picker records sides for. */
export interface LateralTarget {
annotationId: string
sidesPresent: LateralSide[]
}
export interface ObservationPickersProps {
sheet: SheetIndex
activeIndex: number
activeObs: Observation | undefined
vertebraTarget: number | null
lateralTarget: ZoneRef | null
vertebraTarget: VertebraTarget | null
lateralTarget: LateralTarget | null
onCloseVertebra: () => void
onCloseLateral: () => void
}
/** Vertebra and laterality pickers of the active observation. */
/** Vertebra and laterality pickers of the active observation; the core applies the result. */
export default function ObservationPickers({
sheet,
activeIndex,
@@ -37,12 +47,25 @@ export default function ObservationPickers({
const locale = useLocaleStore((s) => s.locale)
const updateObservation = useReportStore((s) => s.updateObservation)
const vertebraZone =
vertebraTarget !== null ? activeObs?.zones[vertebraTarget] : undefined
vertebraTarget !== null
? activeObs?.zones[vertebraTarget.zoneIndex]
: undefined
const vertebraAnnotation =
vertebraZone && sheet.annotation(vertebraZone.annotationId)
const lateralAnnotation =
lateralTarget && sheet.annotation(lateralTarget.annotationId)
/** Applies a core-built observation to the fresh active one; alerts on failure. */
function apply(
run: (fresh: Observation) => ReturnType<SheetIndex['ops']['addSides']>,
) {
const fresh = useReportStore.getState().report?.observations[activeIndex]
if (!fresh) return
const outcome = run(fresh)
if (outcome.ok) updateObservation(activeIndex, outcome.value)
else window.alert(t('core.action_failed'))
}
return (
<>
{vertebraTarget !== null &&
@@ -53,17 +76,12 @@ export default function ObservationPickers({
open
onClose={onCloseVertebra}
onConfirm={(vertebrae) => {
const fresh =
useReportStore.getState().report?.observations[activeIndex]
if (fresh) {
updateObservation(
activeIndex,
syncVertebrae(fresh, vertebrae, sheet, vertebraZone.viewId),
)
}
apply((fresh) =>
sheet.ops.syncVertebrae(fresh, vertebrae, vertebraZone.viewId),
)
onCloseVertebra()
}}
initial={collectVertebrae(activeObs, sheet, vertebraTarget)}
initial={vertebraTarget.initial}
regions={sheet.regions()}
title={`${t('vertebra.title_prefix')}${pickLabel(vertebraAnnotation.name, locale)}`}
initialRegion={
@@ -77,15 +95,11 @@ export default function ObservationPickers({
open
onClose={onCloseLateral}
title={pickLabel(sheet.name(lateralAnnotation), locale)}
existingSides={sidesPresent(activeObs, lateralTarget)}
existingSides={lateralTarget.sidesPresent}
onSelect={(sides: LateralSide[]) => {
const fresh =
useReportStore.getState().report?.observations[activeIndex]
if (fresh)
updateObservation(
activeIndex,
addSides(fresh, lateralAnnotation, sides),
)
apply((fresh) =>
sheet.ops.addSides(fresh, lateralTarget.annotationId, sides),
)
onCloseLateral()
}}
/>
@@ -1,4 +1,4 @@
import type { Severity } from '@faunosteo/domain'
import type { Severity } from '@faunosteo/core-wasm/types'
import { useT } from '@/i18n/useT'
export interface SeveritySelectorProps {
@@ -1,9 +1,14 @@
import { useState } from 'react'
import type { Vertebra, VertebralRegion } from '@faunosteo/domain'
import type {
Vertebra,
VertebraAction,
VertebralRegion,
} from '@faunosteo/core-wasm/types'
import Dialog from '@/components/ui/Dialog'
import Button from '@/components/ui/Button'
import Chip from '@/components/ui/Chip'
import { pickLabel } from '@/services/sheetIndex'
import { pickLabel } from '@/i18n/pickLocaleLabel'
import { reportOps } from '@/core/reportOps'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
@@ -26,6 +31,8 @@ const sameVertebra = (a: Vertebra, r: string, i: number) =>
* Picks vertebrae across every region of the sheet. A region shows its
* usual count; when the sheet documents a wider range (D6), one control
* extends the grid to the documented maximum. Nothing horse-specific here.
* The selection rules (tap, check all, uncheck all) run in the core; the
* grid extent and the chip state are display.
*/
export default function VertebraPicker({
open,
@@ -57,19 +64,17 @@ export default function VertebraPicker({
const has = (r: string, i: number) =>
selected.some((v) => sameVertebra(v, r, i))
const toggle = (r: string, i: number) =>
setSelected((cur) =>
has(r, i)
? cur.filter((v) => !sameVertebra(v, r, i))
: [...cur, { region: r, index: i }],
)
const all = (r: string, n: number) =>
setSelected((cur) => [
...cur.filter((v) => v.region !== r),
...Array.from({ length: n }, (_, k) => ({ region: r, index: k + 1 })),
])
const none = (r: string) =>
setSelected((cur) => cur.filter((v) => v.region !== r))
/** One tap, applied by the core to the selection the picker shows (R2). */
const apply = (action: VertebraAction) => {
const outcome = reportOps.selectVertebrae(selected, action)
if (outcome.ok) setSelected(outcome.value)
else window.alert(t('core.action_failed'))
}
const toggle = (region: string, index: number) =>
apply({ kind: 'toggle', region, index })
const all = (region: string, count: number) =>
apply({ kind: 'all', region, count })
const none = (region: string) => apply({ kind: 'none', region })
return (
<Dialog open={open} onClose={onClose} title={title} size="lg">
@@ -1,8 +1,8 @@
import type { Animal, LocalizedText, Owner } from '@faunosteo/domain'
import type { Animal, LocalizedText, Owner } from '@faunosteo/core-wasm/types'
import Label from '@/components/ui/Label'
import Input from '@/components/ui/Input'
import Select from '@/components/ui/Select'
import { pickLabel } from '@/services/sheetIndex'
import { pickLabel } from '@/i18n/pickLocaleLabel'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
@@ -1,4 +1,4 @@
import type { Report } from '@faunosteo/domain'
import type { Report } from '@faunosteo/core-wasm/types'
import Label from '@/components/ui/Label'
import Textarea from '@/components/ui/Textarea'
import NextAppointmentPicker from './NextAppointmentPicker'
@@ -0,0 +1,21 @@
import Button from '@/components/ui/Button'
import Notice from '@/components/ui/Notice'
import { useT } from '@/i18n/useT'
export interface CoreUnavailableProps {
onRetry: () => void
}
/**
* Degraded state of the sheet pages when the core module cannot run (CSP, network, an old
* browser, a refused sheet): the session data stays where it is, the practitioner retries.
*/
export default function CoreUnavailable({ onRetry }: CoreUnavailableProps) {
const t = useT()
return (
<main className="p-6 space-y-3 max-w-xl">
<Notice tone="error">{t('sheet.core_unavailable')}</Notice>
<Button onClick={onRetry}>{t('sheet.core_retry')}</Button>
</main>
)
}
@@ -1,5 +1,5 @@
import type { ComponentProps } from 'react'
import type { Animal, Owner, Practitioner } from '@faunosteo/domain'
import type { Animal, Owner, Practitioner } from '@faunosteo/core-wasm/types'
import Button from '@/components/ui/Button'
import Dialog from '@/components/ui/Dialog'
import PractitionerForm from '@/components/report/PractitionerForm'
@@ -1,4 +1,4 @@
import type { Report } from '@faunosteo/domain'
import type { Report } from '@faunosteo/core-wasm/types'
import Input from '@/components/ui/Input'
import Label from '@/components/ui/Label'
import { useT } from '@/i18n/useT'
@@ -1,4 +1,4 @@
import type { Practitioner } from '@faunosteo/domain'
import type { Practitioner } from '@faunosteo/core-wasm/types'
import Label from '@/components/ui/Label'
import Input from '@/components/ui/Input'
import { useT } from '@/i18n/useT'
@@ -1,4 +1,4 @@
import type { Report } from '@faunosteo/domain'
import type { Report } from '@faunosteo/core-wasm/types'
import AppHeader from '@/components/brand/AppHeader'
import Button from '@/components/ui/Button'
import { formatDate } from '@/lib/dates'
+47
View File
@@ -0,0 +1,47 @@
import type { CoreOutcome } from '@faunosteo/core-wasm'
import type {
MoveDirection,
NewReportDraft,
Report,
SheetRef,
Vertebra,
VertebraAction,
} from '@faunosteo/core-wasm/types'
import { coreRuntime } from './runtime'
/**
* The report rules that need no sheet (R2): creation and the observation list operations
* of the store, the vertebra picker's selection. Ids and time come from the caller.
*/
function run<T>(op: string, input: unknown): CoreOutcome<T> {
return coreRuntime().call<T>(op, JSON.stringify(input))
}
export interface NewReportInput {
draft: NewReportDraft
sheet: SheetRef
id: string
createdAt: string
/** Id of the empty observation a draft without any starts with. */
observationId: string
}
export const reportOps = {
newReport: (input: NewReportInput): CoreOutcome<Report> =>
run('report.new', input),
addObservation: (report: Report, id: string): CoreOutcome<Report> =>
run('report.add_observation', { report, id }),
removeObservation: (report: Report, index: number): CoreOutcome<Report> =>
run('report.remove_observation', { report, index }),
moveObservation: (
report: Report,
index: number,
direction: MoveDirection,
): CoreOutcome<Report> =>
run('report.move_observation', { report, index, direction }),
selectVertebrae: (
selection: readonly Vertebra[],
action: VertebraAction,
): CoreOutcome<Vertebra[]> => run('vertebra.select', { selection, action }),
}
+46
View File
@@ -0,0 +1,46 @@
import glueUrl from '@faunosteo/core-wasm/pkg/faunosteo_wasm.js?url'
import wasmUrl from '@faunosteo/core-wasm/pkg/faunosteo_wasm_bg.wasm?url'
import {
CoreRuntime,
type CoreSource,
type GlueModule,
} from '@faunosteo/core-wasm'
/**
* The application's core runtime (Rust compiled to WebAssembly, R2). Vite emits the glue
* and the `.wasm` as hashed assets that no route chunk imports: nothing is fetched until a
* sheet path or an import asks `ready()` (review III.3 rule 6). The production CSP must
* carry `'wasm-unsafe-eval'` (DEPLOY.md); without it the load fails and the editor shows
* the degraded state.
*/
async function compileModule(): Promise<WebAssembly.Module> {
const response = await fetch(wasmUrl)
if (!response.ok) throw new Error(`core module HTTP ${response.status}`)
try {
// Needs `Content-Type: application/wasm`; any other type falls back to bytes.
return await WebAssembly.compileStreaming(response.clone())
} catch {
return WebAssembly.compile(await response.arrayBuffer())
}
}
const browserSource: CoreSource = {
compile: compileModule,
// A distinct query per instance gives a new glue module record (R0 finding).
importGlue: (instance) =>
import(/* @vite-ignore */ `${glueUrl}?instance=${instance}`) as Promise<GlueModule>,
}
let runtime: CoreRuntime | null = null
/** The page's runtime, created on first use. */
export function coreRuntime(): CoreRuntime {
runtime ??= new CoreRuntime(browserSource)
return runtime
}
/** Test seam: run the application on another runtime (the Node source in vitest). */
export function setCoreRuntime(next: CoreRuntime): void {
runtime = next
}
+96
View File
@@ -0,0 +1,96 @@
import type { CoreOutcome, SheetSession } from '@faunosteo/core-wasm'
import type {
ArchiveImport,
DraftRestore,
LateralSide,
Observation,
Report,
SheetSnapshot,
Vertebra,
ZoneClick,
} from '@faunosteo/core-wasm/types'
/**
* The sheet-bound rules of the editor, run by the core on the session's sheet (R2): one
* call per user action or load, never in a render. Each returns the core's outcome; the
* caller stops on `ok: false` (nothing is written, the action shows `core.action_failed`).
*/
export interface FindingToggle {
observation: Observation
findingZoneId: string
path: readonly string[]
/** Position of the clicked leaf among the siblings the picker rendered. */
leafPosition: number
side?: LateralSide
}
export class SheetOps {
constructor(private readonly session: SheetSession) {}
private run<T>(op: string, input: unknown): CoreOutcome<T> {
return this.session.call<T>(op, JSON.stringify(input))
}
/** What a click on an annotation does to the active observation (the whole click chain). */
zoneClick(
observation: Observation | null,
annotationId: string,
): CoreOutcome<ZoneClick> {
return this.run('zone.click', { observation, annotationId })
}
addSides(
observation: Observation,
annotationId: string,
sides: readonly LateralSide[],
): CoreOutcome<Observation> {
return this.run('zone.add_sides', { observation, annotationId, sides })
}
removeZoneAt(observation: Observation, index: number): CoreOutcome<Observation> {
return this.run('zone.remove_at', { observation, index })
}
/** The vertebra picker's initial selection, the zone at `index` first. */
vertebraInitial(
observation: Observation,
index: number,
): CoreOutcome<Vertebra[]> {
return this.run('vertebra.initial', { observation, index })
}
syncVertebrae(
observation: Observation,
selection: readonly Vertebra[],
viewId: string,
): CoreOutcome<Observation> {
return this.run('vertebra.sync', { observation, selection, viewId })
}
toggleFinding(toggle: FindingToggle): CoreOutcome<Observation> {
return this.run('finding.toggle', toggle)
}
/** Reads the tab's draft (and the archive kept beside it) and rebases it on this sheet. */
restoreDraft(
draft: string,
archive: string | null,
): CoreOutcome<DraftRestore> {
return this.run('draft.restore', { draft, archive })
}
/**
* Reads a PDF attachment (any supported shape, as the byte scan parsed it) and rebases
* it on this sheet. Failures: `incompatible_version` (with `found`), `no_attachment`,
* `lone_surrogate` (a text the core would alter: refused, never rewritten).
*/
importArchive(attachment: unknown): CoreOutcome<ArchiveImport> {
return this.run('archive.import', attachment)
}
/** The snapshot of this sheet an archive of `report` carries. */
snapshot(report: Report): CoreOutcome<SheetSnapshot> {
return this.run('archive.snapshot', { report })
}
}
+11
View File
@@ -24,6 +24,8 @@ export const en: Dict = {
'Reopen a previous report generated by this app to follow up.',
'home.import.cta': 'Choose a PDF',
'home.import.loading': 'Reading…',
'home.import.error_core_unavailable':
'The reading engine could not be loaded. Try the import again.',
'home.import.error_generic': 'Failed to read the PDF.',
'home.import.error_invalid_pdf': 'This file is not a readable PDF.',
'home.import.error_no_attachment':
@@ -50,6 +52,8 @@ export const en: Dict = {
"Report opened on the current sheet, which differs from the archive's. Items not found: {count} (kept with their labels).",
'home.import.error_attachment_stripped':
'This Faunosteo PDF lost its embedded data (attachment removed by a viewer or an optimiser). Use the original file.',
'home.import.error_lone_surrogate':
'This Faunosteo PDF contains malformed text that this version cannot read without altering it. Import refused; the file was not modified.',
'home.no_sheet.title': 'No anatomical sheet',
'home.no_sheet.description':
'This build of the application carries no anatomical sheet: no report can be created or imported.',
@@ -76,6 +80,8 @@ export const en: Dict = {
'PDF exported with missing elements: {items}. Check the browser console.',
'editor.draft_rebased':
'Draft restored on an anatomical sheet different from the one it was created on. Items not found: {count} (kept with their labels).',
'editor.draft_quarantined':
"This tab's draft could not be read by this version of Faunosteo. It was set aside, not deleted.",
'editor.edit_infos': 'Edit info',
'editor.edit_dialog_title': 'Edit information',
'editor.disclaimer_title': 'Legal scope of animal osteopathy',
@@ -152,6 +158,11 @@ export const en: Dict = {
'Anatomical sheet: reference draft, not medically validated',
'sheet.status.published': 'Official anatomical sheet',
'sheet.loading': 'Loading the anatomical sheet…',
'sheet.core_unavailable':
"Faunosteo's computation engine could not be loaded. Your session data is kept.",
'sheet.core_retry': 'Retry',
'core.action_failed':
'This action could not be applied. Try again; your report was not changed.',
// unresolved (migrated) data
'observation.unresolved_short': 'inherited',
+11
View File
@@ -26,6 +26,8 @@ export const fr: Dict = {
'Reprendre un bilan précédent généré par cette application pour effectuer un suivi.',
'home.import.cta': 'Choisir un PDF',
'home.import.loading': 'Lecture…',
'home.import.error_core_unavailable':
"Le moteur de lecture n'a pas pu être chargé. Réessayez l'import.",
'home.import.error_generic': 'Erreur de lecture du PDF.',
'home.import.error_invalid_pdf': "Ce fichier n'est pas un PDF lisible.",
'home.import.error_no_attachment':
@@ -52,6 +54,8 @@ export const fr: Dict = {
"Bilan ouvert sur la fiche actuelle, différente de celle de l'archive. Éléments non retrouvés : {count} (conservés avec leurs libellés).",
'home.import.error_attachment_stripped':
"Ce PDF Faunosteo a perdu ses données embarquées (pièce jointe supprimée par un lecteur ou un optimiseur). Utilisez le fichier d'origine.",
'home.import.error_lone_surrogate':
"Ce PDF Faunosteo contient un texte mal encodé que cette version ne peut pas relire sans l'altérer. Import refusé ; le fichier n'a pas été modifié.",
'home.no_sheet.title': 'Aucune fiche anatomique',
'home.no_sheet.description':
"Cette version de l'application n'embarque aucune fiche anatomique : aucun bilan ne peut être créé ni importé.",
@@ -82,6 +86,8 @@ export const fr: Dict = {
'PDF exporté avec des éléments manquants : {items}. Vérifiez la console du navigateur.',
'editor.draft_rebased':
'Brouillon restauré sur une fiche anatomique différente de celle où il a été créé. Éléments non retrouvés : {count} (conservés avec leurs libellés).',
'editor.draft_quarantined':
"Le brouillon de cet onglet n'a pas pu être relu par cette version de Faunosteo. Il a été mis de côté, pas supprimé.",
'editor.edit_infos': 'Modifier les infos',
'editor.edit_dialog_title': 'Modifier les informations',
'editor.disclaimer_title': "Périmètre légal de l'ostéopathie animale",
@@ -166,6 +172,11 @@ export const fr: Dict = {
'Fiche anatomique : brouillon de référence, non validé médicalement',
'sheet.status.published': 'Fiche anatomique officielle',
'sheet.loading': 'Chargement de la fiche anatomique…',
'sheet.core_unavailable':
"Le moteur de calcul de Faunosteo n'a pas pu être chargé. Vos données de session sont conservées.",
'sheet.core_retry': 'Réessayer',
'core.action_failed':
"Cette action n'a pas pu être appliquée. Réessayez ; votre bilan n'a pas été modifié.",
// unresolved (migrated) data
'observation.unresolved_short': 'hérité',
+8
View File
@@ -14,3 +14,11 @@ export function pickLocaleLabel(
if (locale === 'en') return en || fr || fallback
return fr || en || fallback
}
/** The same rule for a `{ fr, en }` label of the sheet or a snapshot ('' when absent). */
export function pickLabel(
text: { fr?: string; en?: string } | null | undefined,
locale: Locale,
): string {
return pickLocaleLabel(text?.fr, text?.en, locale)
}
+1 -1
View File
@@ -1,4 +1,4 @@
import type { Branding, ImageAsset } from '@faunosteo/domain'
import type { Branding, ImageAsset } from '@faunosteo/core-wasm/types'
import headerLogoDataUrl from '@/assets/brand/faunosteo-logo-horizontal-512.png?inline'
import footerLogoDataUrl from '@/assets/brand/faunosteo-horizontal-com-512.png?inline'
import poweredByLogoDataUrl from '@/assets/brand/zenquality-logo-fr.png?inline'
+13 -7
View File
@@ -1,7 +1,8 @@
import { buildSheetSnapshot, type Report } from '@faunosteo/domain'
import type { Report } from '@faunosteo/core-wasm/types'
import {
defaultPdfLabels,
exportReportArchive,
type ExportInput,
type ExportWarning,
} from '@faunosteo/pdf'
import type { Locale } from '@/i18n/types'
@@ -20,19 +21,24 @@ export interface PdfExportResult {
}
/**
* Exports the report as an archive PDF through the engine: the loaded sheet
* becomes the snapshot the pages are drawn from and the attachment carries,
* the branding comes from the bundled logos, the browser rasterises the
* views. Warnings are logged and returned for the caller to surface.
* Exports the report as an archive PDF through the engine: the core builds
* the snapshot of the loaded sheet the pages are drawn from and the
* attachment carries (R2), the branding comes from the bundled logos, the
* browser rasterises the views, the TypeScript engine writes the file (the
* writer moves to the core at R4). The core's report and snapshot are the
* same JSON contracts the engine's Zod types describe. Warnings are logged
* and returned for the caller to surface.
*/
export async function exportReportToPdf(
report: Report,
index: SheetIndex,
opts: PdfExportOptions,
): Promise<PdfExportResult> {
const snapshot = index.ops.snapshot(report)
if (!snapshot.ok) throw new Error(`snapshot failed: ${snapshot.kind}`)
const result = await exportReportArchive({
report,
sheet: buildSheetSnapshot(index.sheet, report),
report: report as ExportInput['report'],
sheet: snapshot.value as ExportInput['sheet'],
branding: await loadBranding(),
labels: defaultPdfLabels,
locale: opts.locale,
+52 -11
View File
@@ -1,13 +1,21 @@
import type { ArchiveReadOutcome, ReportMigrationMap } from '@faunosteo/domain'
import type { ArchiveImport } from '@faunosteo/core-wasm/types'
import {
ArchiveReadError,
readReportArchive,
readAttachedDocument,
type ArchiveReadErrorKind,
} from '@faunosteo/pdf'
import type { SheetIndex } from '@/services/sheetIndex'
export { MAX_PDF_BYTES } from '@faunosteo/pdf'
export type ImportErrorKind = ArchiveReadErrorKind
/**
* `lone_surrogate`: the attachment escapes a lone UTF-16 surrogate, which the
* core cannot read without altering it (L1): refused, the file untouched.
*/
export type ImportErrorKind =
| ArchiveReadErrorKind
| 'core_unavailable'
| 'lone_surrogate'
/**
* Localization-agnostic import error. Carries a kind discriminant + an
@@ -25,17 +33,13 @@ export class ImportError extends Error {
}
/**
* Reads a Faunosteo PDF back through the engine: the report (v3 as is, v2
* migrated through the sheet's map) and, when the file is a Step 6 archive,
* the validated envelope or the reason its snapshot was dropped. Engine
* Step 1, no core needed: the JSON a Faunosteo PDF carries, located by the
* engine's byte scan (BLK-009; the scanner moves to the core at R4). Engine
* failures become ImportError kinds, one to one.
*/
export async function importReportFromPdf(
pdfBytes: Uint8Array,
map: ReportMigrationMap,
): Promise<ArchiveReadOutcome> {
export async function readAttachment(pdfBytes: Uint8Array): Promise<unknown> {
try {
return await readReportArchive(pdfBytes, map)
return await readAttachedDocument(pdfBytes)
} catch (err) {
if (err instanceof ArchiveReadError) {
throw new ImportError(err.kind, err.foundVersion)
@@ -43,3 +47,40 @@ export async function importReportFromPdf(
throw err
}
}
/**
* Step 2, in the core on the loaded sheet: the layered reading of the
* attachment (report first, v2 migrated through the sheet's map, then the
* envelope kept or its snapshot dropped with a reason) and the rebase onto
* that sheet. An unknown numeric report version is `incompatible_version`,
* a text the core would alter `lone_surrogate`, any other unreadable content
* `no_attachment`, as the engine reported them.
*/
export function importAttachment(
attachment: unknown,
index: SheetIndex,
): ArchiveImport {
const outcome = index.ops.importArchive(attachment)
if (outcome.ok) return outcome.value
switch (outcome.kind) {
case 'incompatible_version':
throw new ImportError('incompatible_version', outcome.found ?? null)
case 'no_attachment':
throw new ImportError('no_attachment')
case 'lone_surrogate':
throw new ImportError('lone_surrogate')
case 'core_unavailable':
case 'internal':
throw new ImportError('core_unavailable')
default:
throw new Error(`import failed: ${outcome.kind}`)
}
}
/** Both steps on a sheet already loaded in the core. */
export async function importReportFromPdf(
pdfBytes: Uint8Array,
index: SheetIndex,
): Promise<ArchiveImport> {
return importAttachment(await readAttachment(pdfBytes), index)
}
+106 -8
View File
@@ -1,11 +1,109 @@
import type { SheetIndex as DomainSheetIndex } from '@faunosteo/domain'
import type { LoadedSheet } from '@/sheets/provider'
import type {
Annotation,
AnatomicalSheetDocument,
FindingZone,
LocalizedText,
ObservableAnnotation,
SheetIndexData,
SheetRef,
SheetStatus,
SheetView,
VertebralRegion,
} from '@faunosteo/core-wasm/types'
import type { SheetOps } from '@/core/sheetOps'
/**
* The sheet index lives in @faunosteo/domain since Step 6 (shared with the
* PDF engine). This shim keeps the app's import path and binds the index to
* the sheet the app loads, so `index.sheet` still carries the migration map.
* The loaded sheet as React reads it (R2). Every lookup table is computed once by the
* core (`SheetIndexData`): positions by id with the TypeScript `Map` semantics (last
* duplicate wins), names, spine ids and the finding paths that exist. This class only reads
* them, so no render calls the core; the sheet-bound rules go through `ops`.
*/
export { buildSheetIndex, isObservable, pickLabel } from '@faunosteo/domain'
export type { ObservableAnnotation } from '@faunosteo/domain'
export type SheetIndex = DomainSheetIndex<LoadedSheet>
export type { ObservableAnnotation }
/** What the screens read about the loaded sheet. */
export interface LoadedSheetView {
status: SheetStatus
ref: SheetRef
speciesId: string
schemaVersion: number
/** The document as the core parsed it (defaults filled in). */
document: AnatomicalSheetDocument
/** SVG text by `svg_asset_id` (the canvas draws them until R3). */
assets: Readonly<Record<string, string>>
}
function at<T>(
list: readonly T[],
positions: Readonly<Record<string, number>>,
id: string,
): T | undefined {
return Object.hasOwn(positions, id) ? list[positions[id]!] : undefined
}
export function isObservable(
a: Annotation | undefined,
): a is ObservableAnnotation {
return a !== undefined && a.kind !== 'detail_trigger'
}
export class SheetIndex {
readonly sheet: LoadedSheetView
/** The first `main` view of the document. */
readonly mainViewId: string
private readonly spine: ReadonlySet<string>
private readonly nodes: ReadonlySet<string>
constructor(
private readonly data: SheetIndexData,
assets: Readonly<Record<string, string>>,
readonly ops: SheetOps,
) {
const { document } = data
this.sheet = {
status: data.status,
ref: data.ref,
speciesId: data.speciesId,
schemaVersion: data.schemaVersion,
document,
assets,
}
this.mainViewId = data.mainViewId
this.spine = new Set(data.spineIds)
this.nodes = new Set(data.nodeKeys)
}
view(id: string): SheetView | undefined {
return at(this.data.document.views, this.data.viewById, id)
}
annotation(id: string): Annotation | undefined {
return at(this.data.document.annotations, this.data.annotationById, id)
}
findingZone(id: string): FindingZone | undefined {
return at(this.data.document.finding_zones, this.data.findingZoneById, id)
}
regions(): VertebralRegion[] {
return this.data.document.vertebral_config.regions
}
/** Whether an annotation opens the vertebra picker. */
isSpine(annotationId: string): boolean {
return this.spine.has(annotationId)
}
/** The name the sheet gives an annotation (a trigger: its own or its view's). */
name(annotation: Annotation): LocalizedText {
const names = this.data.names
return Object.hasOwn(names, annotation.id)
? names[annotation.id]!
: { fr: '', en: '' }
}
/** Whether the finding zone holds this category or node path. */
hasNode(zoneId: string, path: readonly string[]): boolean {
return this.nodes.has(JSON.stringify([zoneId, ...path]))
}
}
-213
View File
@@ -1,213 +0,0 @@
import type {
Annotation,
LateralSide,
Observation,
ReportZone,
Vertebra,
} from '@faunosteo/domain'
import { isObservable, type SheetIndex } from './sheetIndex'
/**
* Zone interaction rules of the report editor, pure: what a click on an
* annotation means for the active observation, and the observation
* reducers the route applies. The rules are the legacy ones (click chain
* of EditorRoute, BDR-019 vertebra sync), keyed by annotation ids.
*/
export interface ZoneRef {
annotationId: string
viewId: string
}
export type ZoneClickDecision =
| { kind: 'ignore' }
| { kind: 'open_view'; viewId: string }
| { kind: 'activate_fallback' }
| { kind: 'open_vertebra_picker' }
| { kind: 'open_laterality_picker' }
| { kind: 'remove_both_sides' }
| { kind: 'toggle' }
export function sameZone(zone: ReportZone, ref: ZoneRef): boolean {
return zone.annotationId === ref.annotationId && zone.viewId === ref.viewId
}
export function refOf(annotation: Annotation): ZoneRef {
return { annotationId: annotation.id, viewId: annotation.view_id }
}
export function sidesPresent(obs: Observation, ref: ZoneRef): LateralSide[] {
return obs.zones
.filter((z) => sameZone(z, ref) && z.side)
.map((z) => z.side as LateralSide)
}
/**
* Legacy click chain: detail trigger opens its view and is never added; no
* active observation → the click only activates one; spine zones always open
* the picker; bilateral zones go through the side picker, or clear both sides
* when both are set; anything else toggles.
*/
export function decideZoneClick(
annotation: Annotation | undefined,
active: Observation | undefined,
): ZoneClickDecision {
if (!annotation) return { kind: 'ignore' }
if (annotation.kind === 'detail_trigger') {
return { kind: 'open_view', viewId: annotation.opens_view_id }
}
if (!active) return { kind: 'activate_fallback' }
if (annotation.vertebral_region_code !== null) {
return { kind: 'open_vertebra_picker' }
}
if (annotation.laterality === 'bilateral') {
const sides = sidesPresent(active, refOf(annotation))
return sides.includes('left') && sides.includes('right')
? { kind: 'remove_both_sides' }
: { kind: 'open_laterality_picker' }
}
return { kind: 'toggle' }
}
function newZone(annotation: Annotation, side?: LateralSide): ReportZone {
const zone: ReportZone = refOf(annotation)
if (isObservable(annotation)) {
zone.labelFrSnapshot = annotation.name.fr
zone.labelEnSnapshot = annotation.name.en
}
if (side) zone.side = side
return zone
}
function withZones(obs: Observation, zones: ReportZone[]): Observation {
return { ...obs, zones }
}
/** Plain zone: added when absent, removed when present (no side). */
export function toggleZone(
obs: Observation,
annotation: Annotation,
): Observation {
const index = obs.zones.findIndex((z) => sameZone(z, refOf(annotation)))
if (index >= 0)
return withZones(
obs,
obs.zones.filter((_, i) => i !== index),
)
return withZones(obs, [...obs.zones, newZone(annotation)])
}
/** The zone exists after the call; returns its index. */
export function ensureZone(
obs: Observation,
annotation: Annotation,
): { observation: Observation; index: number } {
const index = obs.zones.findIndex((z) => sameZone(z, refOf(annotation)))
if (index >= 0) return { observation: obs, index }
const zones = [...obs.zones, newZone(annotation)]
return { observation: withZones(obs, zones), index: zones.length - 1 }
}
/** Appends the sides not present yet; never removes one (legacy semantics). */
export function addSides(
obs: Observation,
annotation: Annotation,
sides: readonly LateralSide[],
): Observation {
const present = sidesPresent(obs, refOf(annotation))
const added = sides
.filter((side) => !present.includes(side))
.map((side) => newZone(annotation, side))
return added.length === 0 ? obs : withZones(obs, [...obs.zones, ...added])
}
export function removeAllSides(obs: Observation, ref: ZoneRef): Observation {
return withZones(
obs,
obs.zones.filter((z) => !sameZone(z, ref)),
)
}
export function removeZoneAt(obs: Observation, index: number): Observation {
return withZones(
obs,
obs.zones.filter((_, i) => i !== index),
)
}
function isSpineZone(zone: ReportZone, index: SheetIndex): boolean {
return index.isSpine(zone.annotationId)
}
/**
* Vertebrae of every spine zone of the observation, the zone at `priority`
* first (the one the picker was opened from), without duplicates.
*/
export function collectVertebrae(
obs: Observation,
index: SheetIndex,
priority: number,
): Vertebra[] {
const ordered = [
...obs.zones.filter((_, i) => i === priority),
...obs.zones.filter((_, i) => i !== priority),
]
const seen = new Set<string>()
const out: Vertebra[] = []
for (const zone of ordered) {
if (!isSpineZone(zone, index)) continue
for (const v of zone.vertebrae ?? []) {
const key = `${v.region}${v.index}`
if (seen.has(key)) continue
seen.add(key)
out.push({ ...v })
}
}
return out
}
function regionOf(zone: ReportZone, index: SheetIndex): string | null {
const a = index.annotation(zone.annotationId)
return isObservable(a) ? a.vertebral_region_code : null
}
/**
* BDR-019: the picker edits every region at once. Per region the selection
* REPLACES the zone's vertebrae; a spine zone left without vertebrae is
* pruned; a region picked without a zone gets one on the view the picker
* was opened from (or the main view).
*/
export function syncVertebrae(
obs: Observation,
selection: readonly Vertebra[],
index: SheetIndex,
viewId: string,
): Observation {
const byRegion = new Map<string, Vertebra[]>()
for (const v of selection) {
const list = byRegion.get(v.region) ?? []
list.push({ ...v })
byRegion.set(v.region, list)
}
const kept: ReportZone[] = []
for (const zone of obs.zones) {
const region = isSpineZone(zone, index) ? regionOf(zone, index) : null
if (region === null) {
kept.push(zone)
continue
}
const picked = byRegion.get(region)
byRegion.delete(region)
if (!picked || picked.length === 0) continue
kept.push({ ...zone, vertebrae: picked })
}
for (const [region, picked] of byRegion) {
if (picked.length === 0) continue
const annotation =
index.spineAnnotation(region, viewId) ??
index.spineAnnotation(region, index.mainView.id)
if (!annotation) continue
kept.push({ ...newZone(annotation), vertebrae: picked })
}
return withZones(obs, kept)
}
+31 -38
View File
@@ -1,21 +1,17 @@
import {
AnatomicalSheetDocumentSchema,
ReportMigrationMapSchema,
type AnatomicalSheetDocument,
type ReportMigrationMap,
type SheetRef,
} from '@faunosteo/domain'
import type { LocalizedText, SheetRef } from '@faunosteo/core-wasm/types'
/**
* Where the application gets the anatomical sheet it works on. Step 5 ships
* one implementation, the sheet bundled at build time (virtual module, see
* vite/sheet-bundle.ts); the Supabase implementation of Step 13 sits behind
* the same interface. A loaded sheet is immutable for the session.
* the same interface. The payload is handed to the core as it is: the core
* parses the document and the migration map (R2). A loaded sheet is
* immutable for the session.
*/
export type SheetStatus = 'draft' | 'published'
/** Raw payload of the virtual module, validated here before use. */
/** Raw payload of the virtual module, parsed by the core (`SheetHandle`). */
export interface BundledSheetData {
status: SheetStatus
ref: {
@@ -32,56 +28,53 @@ export interface BundledSheetData {
assetHashes: Record<string, string>
}
export interface LoadedSheet {
status: SheetStatus
export interface SheetProvider {
/** The reference sheet payload of a species, or null when none is available. */
getReferenceSheet(speciesId: string): Promise<BundledSheetData | null>
}
/**
* What the pages that only offer to start or import a report show, read from the payload
* without the core: the reference a new report is stamped with and the species name.
*/
export interface SheetAvailability {
ref: SheetRef
speciesId: string
/** Document schema version of the sheet (`ref.schema_version`). */
schemaVersion: number
document: AnatomicalSheetDocument
/** SVG text by `svg_asset_id`. */
assets: Readonly<Record<string, string>>
/** sha256 by `svg_asset_id`; carried into a report archive as provenance. */
assetHashes: Readonly<Record<string, string>>
migrationMap: ReportMigrationMap
name: LocalizedText
}
export interface SheetProvider {
/** The reference sheet of a species, or null when none is available. */
getReferenceSheet(speciesId: string): Promise<LoadedSheet | null>
}
export function parseBundledSheet(data: BundledSheetData): LoadedSheet {
const document = AnatomicalSheetDocumentSchema.parse(data.document)
const migrationMap = ReportMigrationMapSchema.parse(data.migrationMap)
export function availabilityOf(data: BundledSheetData): SheetAvailability {
const document = data.document as { name: LocalizedText }
return {
status: data.status,
ref: {
sheetId: data.ref.sheet_id,
versionId: data.ref.version_id,
documentSha256: data.ref.document_sha256,
},
speciesId: data.ref.species_id,
schemaVersion: data.ref.schema_version,
document,
assets: data.assets,
assetHashes: data.assetHashes,
migrationMap,
name: document.name,
}
}
let cached: Promise<LoadedSheet | null> | null = null
let cached: Promise<BundledSheetData | null> | null = null
async function loadBundled(): Promise<LoadedSheet | null> {
async function loadBundled(): Promise<BundledSheetData | null> {
const mod = await import('virtual:faunosteo-sheet')
return mod.bundledSheet ? parseBundledSheet(mod.bundledSheet) : null
return mod.bundledSheet
}
export const bundledSheetProvider: SheetProvider = {
async getReferenceSheet(speciesId) {
cached ??= loadBundled()
const sheet = await cached
return sheet && sheet.speciesId === speciesId ? sheet : null
let sheet: BundledSheetData | null
try {
sheet = await cached
} catch (error) {
// A failed chunk load is not remembered: the next attempt fetches again.
cached = null
throw error
}
return sheet && sheet.ref.species_id === speciesId ? sheet : null
},
}
+105 -12
View File
@@ -1,20 +1,40 @@
import { useEffect, useState } from 'react'
import { buildSheetIndex, type SheetIndex } from '@/services/sheetIndex'
import { bundledSheetProvider, type SheetProvider } from './provider'
import type { SheetIndexData } from '@faunosteo/core-wasm/types'
import { coreRuntime } from '@/core/runtime'
import { SheetOps } from '@/core/sheetOps'
import { SheetIndex } from '@/services/sheetIndex'
import {
availabilityOf,
bundledSheetProvider,
type SheetAvailability,
type SheetProvider,
} from './provider'
/**
* The reference sheet of a species for the current session, loaded once
* through the provider and indexed. `none` means the build carries no sheet
* (production bundle without SHEET_BUNDLE=draft) or no sheet for the species.
* The reference sheet of a species for the current session. `useSheet` loads it into the
* core (the editor, the import): `none` means the build carries no sheet (production
* bundle without SHEET_BUNDLE=draft) or none for the species; `core_unavailable` means the
* module could not be loaded (CSP, network, old browser) and `invalid_sheet` that the
* bundled payload was refused, both with a `retry`. `useSheetAvailability` reads the
* payload alone, without the core, for the pages that only offer to start a report.
*/
export type SheetLoad =
| { status: 'none' }
| { status: 'ready'; index: SheetIndex }
| { status: 'core_unavailable' }
| { status: 'invalid_sheet' }
export type SheetState =
| { status: 'loading' }
| { status: 'none' }
| { status: 'ready'; index: SheetIndex }
| { status: 'core_unavailable'; retry: () => void }
| { status: 'invalid_sheet'; retry: () => void }
let provider: SheetProvider = bundledSheetProvider
const cache = new Map<string, Promise<SheetIndex | null>>()
/** Settled loads only (`ready`, `none`): a failure is never remembered. */
const cache = new Map<string, Promise<SheetLoad>>()
/** Test seam: swap the provider and forget loaded sheets. */
export function setSheetProvider(next: SheetProvider): void {
@@ -22,19 +42,48 @@ export function setSheetProvider(next: SheetProvider): void {
cache.clear()
}
export function loadSheetIndex(speciesId: string): Promise<SheetIndex | null> {
async function loadIntoCore(speciesId: string): Promise<SheetLoad> {
const bundle = await provider.getReferenceSheet(speciesId)
if (!bundle) return { status: 'none' }
if (!(await coreRuntime().ready())) return { status: 'core_unavailable' }
const session = coreRuntime().sheet(JSON.stringify(bundle))
const data = session.call<SheetIndexData>('index_data', '')
if (data.ok) {
const index = new SheetIndex(data.value, bundle.assets, new SheetOps(session))
return { status: 'ready', index }
}
return {
status: data.kind === 'invalid_sheet' ? 'invalid_sheet' : 'core_unavailable',
}
}
/** The species' sheet in the core; failures are retried on the next call. */
export function loadSheet(speciesId: string): Promise<SheetLoad> {
let pending = cache.get(speciesId)
if (!pending) {
pending = provider
.getReferenceSheet(speciesId)
.then((sheet) => (sheet ? buildSheetIndex(sheet) : null))
pending = loadIntoCore(speciesId).catch(
(): SheetLoad => ({ status: 'core_unavailable' }),
)
cache.set(speciesId, pending)
void pending.then((load) => {
const settled = load.status === 'ready' || load.status === 'none'
if (!settled) cache.delete(speciesId)
})
}
return pending
}
/** The ready index, or null (tests and callers that need the sheet or nothing). */
export async function loadSheetIndex(
speciesId: string,
): Promise<SheetIndex | null> {
const load = await loadSheet(speciesId)
return load.status === 'ready' ? load.index : null
}
export function useSheet(speciesId: string | undefined): SheetState {
const [state, setState] = useState<SheetState>({ status: 'loading' })
const [attempt, setAttempt] = useState(0)
useEffect(() => {
let cancelled = false
if (!speciesId) {
@@ -42,13 +91,57 @@ export function useSheet(speciesId: string | undefined): SheetState {
return
}
setState({ status: 'loading' })
loadSheetIndex(speciesId).then((index) => {
const retry = () => {
void coreRuntime()
.retry()
.finally(() => setAttempt((n) => n + 1))
}
void loadSheet(speciesId).then((load) => {
if (cancelled) return
setState(index ? { status: 'ready', index } : { status: 'none' })
if (load.status === 'ready' || load.status === 'none') setState(load)
else if (load.status === 'invalid_sheet') setState({ status: load.status, retry })
else setState({ status: 'core_unavailable', retry })
})
return () => {
cancelled = true
}
}, [speciesId, attempt])
return state
}
export type SheetAvailabilityState =
| { status: 'loading' }
| { status: 'none' }
| { status: 'ready'; sheet: SheetAvailability }
/** Whether the build carries a sheet for the species, without loading the core. */
export function useSheetAvailability(
speciesId: string | undefined,
): SheetAvailabilityState {
const [state, setState] = useState<SheetAvailabilityState>({
status: 'loading',
})
useEffect(() => {
let cancelled = false
if (!speciesId) {
setState({ status: 'none' })
return
}
void provider
.getReferenceSheet(speciesId)
.then((bundle) => {
if (cancelled) return
setState(
bundle
? { status: 'ready', sheet: availabilityOf(bundle) }
: { status: 'none' },
)
})
// A failed chunk load leaves the page loading, as before R2; a reload fetches again.
.catch(() => undefined)
return () => {
cancelled = true
}
}, [speciesId])
return state
}
+42 -32
View File
@@ -1,33 +1,39 @@
import {
readReportDocument,
ReportArchiveEnvelopeSchema,
type Report,
type ReportArchiveEnvelope,
type ReportMigrationMap,
} from '@faunosteo/domain'
import type { Report, ReportArchiveEnvelope } from '@faunosteo/core-wasm/types'
/**
* Where the session lives between renders. The report draft is mirrored on
* every change; the archive an import brought along (the envelope of a
* Step 6 PDF) is written only when the session starts or ends, so a stale
* draft can still be rebased with the labels of its original sheet. One
* implementation today (per-tab sessionStorage); the Supabase and outbox
* adapters of later steps implement the same interfaces.
* draft can still be rebased with the labels of its original sheet. The
* texts are read raw: the core parses them (R2), and a text the running
* build cannot read is set aside under a quarantine key instead of being
* dropped. One implementation today (per-tab sessionStorage); the Supabase
* and outbox adapters of later steps implement the same interfaces.
*/
export interface ReportPersistence {
load(map: ReportMigrationMap): Report | null
/** The raw draft text, null when there is none. */
loadText(): string | null
save(report: Report | null): void
}
export interface ArchivePersistence {
load(): ReportArchiveEnvelope | null
loadText(): string | null
save(archive: ReportArchiveEnvelope | null): void
}
export const DRAFT_KEY = 'osteo:draft'
export const ARCHIVE_KEY = 'osteo:archive'
/** Unreadable texts and the pre-rebase draft, newest only (R2 plan rev 2). */
export const QUARANTINE_KEYS = {
draft: 'osteo:quarantine:draft',
archive: 'osteo:quarantine:archive',
draftPreRebase: 'osteo:quarantine:draft-pre-rebase',
} as const
export type QuarantineSlot = keyof typeof QUARANTINE_KEYS
function storage(): Storage | null {
return typeof sessionStorage === 'undefined' ? null : sessionStorage
}
@@ -47,33 +53,37 @@ function writeOrRemove(key: string, value: unknown): void {
}
}
/**
* Copies `raw` into its quarantine slot, then removes `source` (when given)
* only if that copy succeeded: a full storage keeps the text where it was.
* Returns whether the text is now in quarantine.
*/
export function quarantine(
slot: QuarantineSlot,
raw: string,
source?: string,
): boolean {
const store = storage()
if (!store) return false
try {
store.setItem(QUARANTINE_KEYS[slot], raw)
} catch (err) {
if (import.meta.env.DEV) console.warn(`${slot} not set aside`, err)
return false
}
if (source) store.removeItem(source)
return true
}
export const sessionStoragePersistence: ReportPersistence = {
load(map) {
const raw = storage()?.getItem(DRAFT_KEY)
if (!raw) return null
try {
return readReportDocument(JSON.parse(raw), map).report
} catch (err) {
if (import.meta.env.DEV) console.warn('osteo:draft ignored', err)
return null
}
},
loadText: () => storage()?.getItem(DRAFT_KEY) ?? null,
save(report) {
writeOrRemove(DRAFT_KEY, report)
},
}
export const sessionStorageArchivePersistence: ArchivePersistence = {
load() {
const raw = storage()?.getItem(ARCHIVE_KEY)
if (!raw) return null
try {
const parsed = ReportArchiveEnvelopeSchema.safeParse(JSON.parse(raw))
return parsed.success ? parsed.data : null
} catch {
return null
}
},
loadText: () => storage()?.getItem(ARCHIVE_KEY) ?? null,
save(archive) {
writeOrRemove(ARCHIVE_KEY, archive)
},
+15 -2
View File
@@ -1,4 +1,17 @@
import { PractitionerSchema, type Practitioner } from '@faunosteo/domain'
import { z } from 'zod'
import type { Practitioner } from '@faunosteo/core-wasm/types'
/**
* Prefill of the practitioner form (D-R7: form validation stays TypeScript, the core is
* not loaded on the new-report page): the cached value is used only when it still has the
* shape of the report's practitioner (name required, the rest optional text).
*/
const CachedPractitionerSchema: z.ZodType<Practitioner> = z.object({
name: z.string().min(1),
cabinet: z.string().optional(),
contact: z.string().optional(),
siret: z.string().optional(),
})
const STORAGE_KEY = 'osteo:lastPractitioner'
@@ -8,7 +21,7 @@ export function readCachedPractitioner(): Practitioner | undefined {
if (!raw) return undefined
try {
const data = JSON.parse(raw)
const parsed = PractitionerSchema.safeParse(data)
const parsed = CachedPractitionerSchema.safeParse(data)
return parsed.success ? parsed.data : undefined
} catch {
return undefined
+160 -123
View File
@@ -1,21 +1,25 @@
import { create } from 'zustand'
import {
rebaseReportOnSheet,
REPORT_VERSION,
type Animal,
type NextAppointment,
type Observation,
type Owner,
type Practitioner,
type RebaseOutcome,
type Report,
type ReportArchiveEnvelope,
type SheetRef,
} from '@faunosteo/domain'
import type {
Animal,
NewReportDraft,
NextAppointment,
Observation,
Owner,
Practitioner,
RebaseOutcome,
Report,
ReportArchiveEnvelope,
SheetRef,
} from '@faunosteo/core-wasm/types'
import type { CoreOutcome } from '@faunosteo/core-wasm'
import { reportOps } from '@/core/reportOps'
import { generateId } from '@/lib/id'
import { nowIso } from '@/lib/dates'
import type { SheetIndex } from '@/services/sheetIndex'
import {
ARCHIVE_KEY,
DRAFT_KEY,
quarantine,
sessionStorageArchivePersistence,
sessionStoragePersistence,
type ArchivePersistence,
@@ -23,45 +27,60 @@ import {
} from './persistence'
/**
* In-memory report document (v3) and its editing actions. Observation-level
* zone rules live in services/zoneInteraction; the store only replaces
* documents. The per-tab draft is mirrored through the persistence adapter
* and restored once the sheet is known; a draft written on another revision
* of the sheet is rebased on restore. The archive an import brought along
* (STEP6 §14 "App session") is kept beside the report for later operations
* and written only when the session starts or ends.
* In-memory report document (v3) and its editing actions. Every report that
* enters the store comes from the core (R2): a new report, a restored draft,
* an import; the observation list rules (add, remove, move) run in the core
* too, and the editor's reducers hand back core-built observations. Form
* values (identity, texts, an observation's comment, severity or free
* findings) are plain assignments. An action whose core call fails changes
* nothing and answers `{ ok: false }`; the caller tells the practitioner.
* The per-tab draft is mirrored through the persistence adapter and restored
* once the sheet is known; the archive an import brought along is kept
* beside the report and written only when the session starts or ends.
*/
/** What a new report needs before the store stamps version, id and dates. */
export type NewReportDraft = Omit<
Report,
'version' | 'id' | 'createdAt' | 'sheet' | 'localAnnotations'
>
export type { NewReportDraft }
export interface ImportedSession {
report: Report
archive: ReportArchiveEnvelope | null
}
export interface ActionResult {
ok: boolean
}
/** What a draft restore did; `null` from the action when there was nothing to restore. */
export type RestoreResult =
| { kind: 'restored'; rebase: RebaseOutcome }
/** The draft is unreadable by this build: set aside, verbatim, under a quarantine key. */
| { kind: 'quarantined' }
/**
* The draft is unreadable but could not be set aside (storage full): it stays in
* `osteo:draft`, and the caller must not start anything that would overwrite it.
*/
| { kind: 'unreadable_kept' }
/** The core failed: nothing read, nothing written, the draft is where it was. */
| { kind: 'core_unavailable' }
export interface ReportStore {
report: Report | null
/** The envelope of the imported archive, as exported; null otherwise. */
archive: ReportArchiveEnvelope | null
activeObservationIndex: number
initReport: (draft: NewReportDraft, sheet: SheetRef) => void
hydrateReport: (report: Report) => void
/** Opens an imported report (already rebased) with its archive. */
initReport: (draft: NewReportDraft, sheet: SheetRef) => ActionResult
/** Opens an imported report (read and rebased by the core) with its archive. */
hydrateImport: (session: ImportedSession) => void
/**
* Restores the per-tab draft on the loaded sheet, rebasing it when it was
* written on another revision; a no-op when a report is already open.
* Returns the rebase outcome, null when nothing was restored.
* written on another revision; a no-op (null) when a report is already open
* or there is no draft.
*/
restoreDraft: (index: SheetIndex) => RebaseOutcome | null
addObservation: () => void
removeObservation: (index: number) => void
moveObservationUp: (index: number) => void
moveObservationDown: (index: number) => void
restoreDraft: (index: SheetIndex) => RestoreResult | null
addObservation: () => ActionResult
removeObservation: (index: number) => ActionResult
moveObservationUp: (index: number) => ActionResult
moveObservationDown: (index: number) => ActionResult
updateObservation: (index: number, obs: Observation) => void
setActiveObservation: (index: number) => void
setPractitioner: (next: Practitioner) => void
@@ -73,47 +92,79 @@ export interface ReportStore {
reset: () => void
}
export function emptyObservation(): Observation {
return {
id: generateId(),
zones: [],
findings: [],
freeTextFindings: [],
comment: '',
}
}
/** A fresh v3 document: the store stamps version, id, dates and the sheet. */
function newReport(draft: NewReportDraft, sheet: SheetRef): Report {
return {
...draft,
version: REPORT_VERSION,
id: generateId(),
createdAt: nowIso(),
sheet,
observations:
draft.observations.length === 0
? [emptyObservation()]
: draft.observations,
localAnnotations: [],
}
}
function swapped(list: Observation[], i: number, j: number): Observation[] {
const next = [...list]
;[next[i], next[j]] = [next[j]!, next[i]!]
return next
}
type Patch = Partial<
Pick<ReportStore, 'report' | 'archive' | 'activeObservationIndex'>
>
type Setter = (fn: (s: ReportStore) => Patch | ReportStore) => void
type Getter = () => ReportStore
const OK: ActionResult = { ok: true }
const FAILED: ActionResult = { ok: false }
function onReport(set: Setter, update: (r: Report, s: ReportStore) => Patch) {
set((s) => (s.report ? update(s.report, s) : s))
}
/** Applies a core-built report with its active index; nothing changes on failure. */
function applyCore(
set: Setter,
get: Getter,
run: (report: Report) => CoreOutcome<Report>,
active: (next: Report, s: ReportStore) => number,
): ActionResult {
const state = get()
if (!state.report) return OK
const outcome = run(state.report)
if (!outcome.ok) return FAILED
set(() => ({
report: outcome.value,
activeObservationIndex: active(outcome.value, state),
}))
return OK
}
/**
* The core's content kinds for a draft: the text itself is unreadable by this build
* (`lone_surrogate`: reading it would alter a string, L1). Any other failure is the core's
* or the sheet's and leaves the draft in place.
*/
const UNREADABLE_DRAFT_KINDS: ReadonlySet<string> = new Set([
'invalid',
'unsupported_version',
'lone_surrogate',
])
/** Reads the draft through the core; unreadable content goes to quarantine, never away. */
function restore(
index: SheetIndex,
persistence: ReportPersistence,
archives: ArchivePersistence,
): { result: RestoreResult; patch?: Patch } | null {
const draft = persistence.loadText()
if (draft === null) return null
const archiveText = archives.loadText()
const outcome = index.ops.restoreDraft(draft, archiveText)
if (!outcome.ok) {
// Only an unreadable draft is set aside; a core or sheet failure leaves it in place.
if (!UNREADABLE_DRAFT_KINDS.has(outcome.kind)) {
return { result: { kind: 'core_unavailable' } }
}
const setAside = quarantine('draft', draft, DRAFT_KEY)
return { result: { kind: setAside ? 'quarantined' : 'unreadable_kept' } }
}
const { rebase, archive, archiveRejected } = outcome.value
if (archiveRejected && archiveText !== null) {
quarantine('archive', archiveText, ARCHIVE_KEY)
}
if (rebase.rebased && rebase.unresolvedZones + rebase.unresolvedFindings > 0) {
quarantine('draftPreRebase', draft)
}
return {
result: { kind: 'restored', rebase },
patch: { report: rebase.report, archive, activeObservationIndex: 0 },
}
}
export function createReportStore(
persistence: ReportPersistence,
archives: ArchivePersistence,
@@ -129,78 +180,64 @@ export function createReportStore(
archive: null,
activeObservationIndex: 0,
initReport: (draft, sheet) =>
set(
withArchive(
{ report: newReport(draft, sheet), activeObservationIndex: 0 },
null,
),
),
hydrateReport: (report) =>
set(withArchive({ report, activeObservationIndex: 0 }, null)),
initReport: (draft, sheet) => {
const outcome = reportOps.newReport({
draft,
sheet,
id: generateId(),
createdAt: nowIso(),
observationId: generateId(),
})
if (!outcome.ok) return FAILED
set(withArchive({ report: outcome.value, activeObservationIndex: 0 }, null))
return OK
},
hydrateImport: ({ report, archive }) =>
set(withArchive({ report, activeObservationIndex: 0 }, archive)),
restoreDraft: (index) => {
if (get().report) return null
const draft = persistence.load(index.sheet.migrationMap)
if (!draft) return null
const archive = archives.load()
const rebase = rebaseReportOnSheet(
draft,
index,
archive?.sheetSnapshot ?? null,
)
set({ report: rebase.report, archive, activeObservationIndex: 0 })
return rebase
const restored = restore(index, persistence, archives)
if (!restored) return null
if (restored.patch) set(restored.patch)
return restored.result
},
addObservation: () =>
onReport(set, (r) => {
const observations = [...r.observations, emptyObservation()]
return {
report: { ...r, observations },
activeObservationIndex: observations.length - 1,
}
}),
applyCore(
set,
get,
(r) => reportOps.addObservation(r, generateId()),
(next) => next.observations.length - 1,
),
removeObservation: (index) =>
onReport(set, (r, s) => {
const observations = r.observations.filter((_, i) => i !== index)
const active = Math.min(
s.activeObservationIndex,
Math.max(0, observations.length - 1),
)
return {
report: { ...r, observations },
activeObservationIndex: active,
}
}),
applyCore(
set,
get,
(r) => reportOps.removeObservation(r, index),
(next, s) =>
Math.min(
s.activeObservationIndex,
Math.max(0, next.observations.length - 1),
),
),
moveObservationUp: (index) =>
onReport(set, (r) =>
index <= 0
? {}
: {
report: {
...r,
observations: swapped(r.observations, index - 1, index),
},
},
applyCore(
set,
get,
(r) => reportOps.moveObservation(r, index, 'up'),
(_, s) => s.activeObservationIndex,
),
moveObservationDown: (index) =>
onReport(set, (r) =>
index >= r.observations.length - 1
? {}
: {
report: {
...r,
observations: swapped(r.observations, index, index + 1),
},
},
applyCore(
set,
get,
(r) => reportOps.moveObservation(r, index, 'down'),
(_, s) => s.activeObservationIndex,
),
updateObservation: (index, obs) =>
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+15
View File
@@ -0,0 +1,15 @@
import { CoreRuntime } from '@faunosteo/core-wasm'
import { nodeCoreRuntime } from '@faunosteo/core-wasm/node'
/** A loaded runtime on the shipped build (the package's Node source). */
export function testCoreRuntime(): Promise<CoreRuntime> {
return nodeCoreRuntime('pkg')
}
/** A runtime whose module never loads (CSP refusal, network failure). */
export function unavailableCoreRuntime(): CoreRuntime {
return new CoreRuntime({
compile: () => Promise.reject(new WebAssembly.CompileError('blocked')),
importGlue: () => Promise.reject(new TypeError('blocked')),
})
}
+58
View File
@@ -0,0 +1,58 @@
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import type { Report } from '@faunosteo/core-wasm/types'
import { importAttachment } from '@/pdf/import'
import type { SheetIndex } from '@/services/sheetIndex'
import { FIXTURES_DIR } from './goldens'
import {
leavesAsV2Report,
legacyLeaves,
loadLegacyBaseline,
} from './legacyLeaves'
/**
* The three reports the Step 6 goldens and the R2 envelope freeze are drawn
* from: the Step 5 v2 archive fixture migrated, the v3 demo report, and a v2
* report whose sphenoid and ssb findings the migration cannot place. Since
* R2 they are read the way the application reads an attachment: the core's
* layered reading (v3 parsed, v2 migrated through the sheet's map).
*/
export const GOLDEN_REPORTS = ['v2full', 'demo', 'v2unresolved'] as const
export type GoldenReportName = (typeof GOLDEN_REPORTS)[number]
export interface GoldenReports {
reports: Record<GoldenReportName, Report>
/** Findings the migration flagged in `v2unresolved`. */
unresolvedOfV2Unresolved: number
}
const readJson = (name: string): unknown =>
JSON.parse(readFileSync(resolve(FIXTURES_DIR, name), 'utf8'))
/** sphenoid + ssb (the families the migration cannot place) plus one leaf that resolves. */
function buildV2Unresolved(sheet: SheetIndex) {
const leaves = legacyLeaves(loadLegacyBaseline())
const unresolvedFamilies = leaves.filter(
(l) => l.zoneId === 'sphenoid' || l.zoneId === 'ssb',
)
const resolved = leaves.find((l) => l.zoneId === 'frontal')!
return importAttachment(
leavesAsV2Report([...unresolvedFamilies, resolved]),
sheet,
).read
}
export function buildGoldenReports(sheet: SheetIndex): GoldenReports {
const v2unresolved = buildV2Unresolved(sheet)
return {
reports: {
v2full: importAttachment(readJson('report-v2.full.json'), sheet).read
.report,
demo: importAttachment(readJson('report-v3.demo.json'), sheet).read
.report,
v2unresolved: v2unresolved.report,
},
unresolvedOfV2Unresolved: v2unresolved.unresolvedFindings,
}
}
+9 -2
View File
@@ -17,8 +17,11 @@ import type {
Observation,
Report,
SheetSnapshot,
} from '@faunosteo/domain'
} from '@faunosteo/core-wasm/types'
import { composeHighlightedViewSvg } from '@faunosteo/pdf'
/** The engine's own (Zod-inferred) types of the same JSON contracts. */
type EngineView = Parameters<typeof composeHighlightedViewSvg>
import { nologosBranding } from './sheet'
/**
@@ -241,7 +244,11 @@ export function snapshotView(
observation: Observation,
viewId: string,
): ViewSnapshot {
const svg = composeHighlightedViewSvg(sheet, viewId, observation)
const svg = composeHighlightedViewSvg(
sheet as EngineView[0],
viewId,
observation as EngineView[2],
)
const root = new DOMParser().parseFromString(
svg,
'image/svg+xml',
+54 -24
View File
@@ -1,21 +1,15 @@
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { resolve } from 'node:path'
import {
AnatomicalSheetDocumentSchema,
ReportV2Schema,
type AnatomicalSheetDocument,
type FindingCategory,
type FindingNode,
type ObservationV2,
type ReportV2,
} from '@faunosteo/domain'
import type { LocalizedText } from '@faunosteo/core-wasm/types'
/**
* The legacy catalog as the application's archive knew it: every leaf of the
* generated baseline (`legacy-import/document.json`) becomes a Report v2
* finding, grouped in one observation per zone. Mirrors the anatomy package
* helper of the same name; both read the committed seed, never a copy.
* helper of the same name; both read the committed seed, never a copy. The
* baseline is read as its authoring form (leaves carry no `children` key);
* the core reads the v2 report built from it.
*/
const BASELINE = resolve(
@@ -23,6 +17,18 @@ const BASELINE = resolve(
'../../../../../supabase/seed/anatomical-sheets/equine/legacy-import/document.json',
)
/** A category or node of the baseline in its authoring form. */
interface BaselineNode {
id: string
name: LocalizedText
requires_vet_referral?: boolean
children?: BaselineNode[]
}
export interface LegacyBaseline {
finding_zones: { id: string; categories: BaselineNode[] }[]
}
export interface LegacyLeaf {
zoneId: string
path: string[]
@@ -30,25 +36,49 @@ export interface LegacyLeaf {
vet: boolean
}
export function loadLegacyBaseline(): AnatomicalSheetDocument {
return AnatomicalSheetDocumentSchema.parse(
JSON.parse(readFileSync(BASELINE, 'utf8')),
)
/** A Report v2 document as the deployed application wrote it (input of the migration). */
export interface ReportV2Fixture {
version: 2
id: string
createdAt: string
date: string
practitioner: { name: string }
animal: { speciesId: string; name: string }
owner: { name: string }
observations: {
id: string
zones: unknown[]
findings: {
zoneId: string
path: string[]
labelFrSnapshot: string
labelEnSnapshot: string
requiresVetReferral?: true
}[]
freeTextFindings: string[]
comment: string
}[]
conclusion: string
recommendations: string
}
export function legacyLeaves(doc: AnatomicalSheetDocument): LegacyLeaf[] {
export function loadLegacyBaseline(): LegacyBaseline {
return JSON.parse(readFileSync(BASELINE, 'utf8')) as LegacyBaseline
}
export function legacyLeaves(doc: LegacyBaseline): LegacyLeaf[] {
const out: LegacyLeaf[] = []
const walk = (
zoneId: string,
nodes: readonly (FindingCategory | FindingNode)[],
nodes: readonly BaselineNode[],
prefix: string[],
) => {
for (const node of nodes) {
const path = [...prefix, node.id]
if (node.children.length > 0) walk(zoneId, node.children, path)
const children = node.children ?? []
if (children.length > 0) walk(zoneId, children, path)
else {
const vet =
'requires_vet_referral' in node && node.requires_vet_referral
const vet = node.requires_vet_referral === true
out.push({ zoneId, path, name: node.name, vet })
}
}
@@ -57,8 +87,8 @@ export function legacyLeaves(doc: AnatomicalSheetDocument): LegacyLeaf[] {
return out
}
export function leavesAsV2Report(leaves: LegacyLeaf[]): ReportV2 {
const byZone = new Map<string, ObservationV2>()
export function leavesAsV2Report(leaves: LegacyLeaf[]): ReportV2Fixture {
const byZone = new Map<string, ReportV2Fixture['observations'][number]>()
for (const leaf of leaves) {
let obs = byZone.get(leaf.zoneId)
if (!obs) {
@@ -76,10 +106,10 @@ export function leavesAsV2Report(leaves: LegacyLeaf[]): ReportV2 {
path: leaf.path,
labelFrSnapshot: leaf.name.fr,
labelEnSnapshot: leaf.name.en || leaf.name.fr,
...(leaf.vet ? { requiresVetReferral: true } : {}),
...(leaf.vet ? { requiresVetReferral: true as const } : {}),
})
}
return ReportV2Schema.parse({
return {
version: 2,
id: 'all-leaves',
createdAt: '2026-10-10T00:00:00Z',
@@ -90,5 +120,5 @@ export function leavesAsV2Report(leaves: LegacyLeaf[]): ReportV2 {
observations: [...byZone.values()],
conclusion: '',
recommendations: '',
})
}
}
+70 -15
View File
@@ -1,16 +1,20 @@
import {
buildSheetSnapshot,
ENVELOPE_FORMAT,
ENVELOPE_VERSION,
REPORT_VERSION,
type Branding,
type Observation,
type Report,
type ReportArchiveEnvelope,
} from '@faunosteo/domain'
import type {
Branding,
FindingCategory,
FindingNode,
Observation,
Report,
ReportArchiveEnvelope,
SheetSnapshot,
} from '@faunosteo/core-wasm/types'
import { defaultPdfLabels } from '@faunosteo/pdf'
import type { SheetIndexData } from '@faunosteo/core-wasm/types'
import type { ReportMigrationMap } from '@faunosteo/core-wasm/n-1'
import { coreRuntime } from '@/core/runtime'
import { SheetOps } from '@/core/sheetOps'
import { bundledSheetProvider, type BundledSheetData } from '@/sheets/provider'
import { loadSheetIndex } from '@/sheets/useSheet'
import type { SheetIndex } from '@/services/sheetIndex'
import { SheetIndex } from '@/services/sheetIndex'
/** The bundled reference draft (vitest runs the sheet-bundle plugin in draft mode). */
export async function loadTestSheet(): Promise<SheetIndex> {
@@ -28,7 +32,7 @@ export function minimalReport(
patch: Partial<Report> = {},
): Report {
return {
version: REPORT_VERSION,
version: 3,
id: 'r1',
createdAt: '2026-10-10T10:00:00Z',
date: '2026-10-10',
@@ -63,19 +67,70 @@ export function nologosBranding(): Branding {
}
}
/** The snapshot of `sheet` an archive of `report` carries, built by the core. */
export function sheetSnapshot(
sheet: SheetIndex,
report: Report,
): SheetSnapshot {
const outcome = sheet.ops.snapshot(report)
if (!outcome.ok) throw new Error(`snapshot failed: ${outcome.kind}`)
return outcome.value
}
/** A valid Step 6 envelope for `report`, snapshotted on `sheet` (no logos). */
export function archiveEnvelope(
sheet: SheetIndex,
report: Report,
): ReportArchiveEnvelope {
return {
format: ENVELOPE_FORMAT,
envelopeVersion: ENVELOPE_VERSION,
format: 'faunosteo-report-archive',
envelopeVersion: 1,
exportedAt: '2026-10-11T12:00:00.000Z',
locale: 'fr',
report,
sheetSnapshot: buildSheetSnapshot(sheet.sheet, report),
sheetSnapshot: sheetSnapshot(sheet, report),
branding: nologosBranding(),
labels: defaultPdfLabels,
}
}
/** The bundled migration map, for the frozen N-1 readers (the core keeps its own copy). */
export async function bundledMigrationMap(): Promise<ReportMigrationMap> {
return (await bundledSheet()).migrationMap as ReportMigrationMap
}
/**
* The category or node at a path of a finding zone (first match at each level, as the
* core's walk), read from the parsed document: the tests' view of what `hasNode` answers.
*/
export function findingNodeAt(
sheet: SheetIndex,
zoneId: string,
path: readonly string[],
): FindingCategory | FindingNode | undefined {
if (path.length === 0) return undefined
let nodes: readonly (FindingCategory | FindingNode)[] =
sheet.findingZone(zoneId)?.categories ?? []
let node: FindingCategory | FindingNode | undefined
for (const segment of path) {
node = nodes.find((n) => n.id === segment)
if (!node) return undefined
nodes = node.children
}
return node
}
/** The bundled payload as the provider hands it to the core. */
export async function bundledSheet(): Promise<BundledSheetData> {
const bundle = await bundledSheetProvider.getReferenceSheet('equine')
if (!bundle) throw new Error('bundled sheet missing: run pnpm import:equine')
return bundle
}
/** Another sheet loaded in the core (a revised catalog), outside the provider's cache. */
export function sheetFromBundle(bundle: BundledSheetData): SheetIndex {
const session = coreRuntime().sheet(JSON.stringify(bundle))
const data = session.call<SheetIndexData>('index_data', '')
if (!data.ok) throw new Error(`sheet refused by the core: ${data.kind}`)
return new SheetIndex(data.value, bundle.assets, new SheetOps(session))
}
+5
View File
@@ -1 +1,6 @@
import '@testing-library/jest-dom'
import { setCoreRuntime } from '@/core/runtime'
import { testCoreRuntime } from './helpers/core'
// The application runs on the real core (R2): the shipped wasm build, loaded from disk.
setCoreRuntime(await testCoreRuntime())
@@ -0,0 +1,85 @@
/**
* R2 freeze (RUST_ARCHITECTURE_REVIEW VI.1, VI.2 R2): the archive envelope
* (PDF attachment) of the three golden reports, exported by the application
* path with fixed inputs (FR, every logo slot empty, 1×1 raster, fixed
* export time), committed as the TypeScript domain wrote it before the
* switch to the Rust core. Whatever writes the attachment afterwards, it
* must parse with the frozen N-1 reader and be deep-equal to the frozen
* envelope; only the key order may differ (D-R11). `MAKE_R2_FREEZE=1`
* writes the files: never once the switch has landed without an owner
* decision. Since R2 the golden reports are read and the snapshot built by
* the Rust core: the attachment differs from the frozen one by key order at
* most (the deep-equality below ignores it).
*/
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
import { readAttachmentBytes } from '@faunosteo/pdf'
import {
readArchiveDocument,
ReportArchiveEnvelopeSchema,
} from '@faunosteo/core-wasm/n-1'
import { exportReportToPdf } from '@/pdf/export'
import type { SheetIndex } from '@/services/sheetIndex'
import { bundledMigrationMap, loadTestSheet } from '../helpers/sheet'
import { FIXTURES_DIR, ONE_PX_PNG } from '../helpers/goldens'
import {
buildGoldenReports,
GOLDEN_REPORTS,
type GoldenReports,
} from '../helpers/goldenReports'
vi.mock('@/pdf/browserRasterizer', () => ({
browserRasterizer: vi.fn(async () => ONE_PX_PNG),
}))
vi.mock('@/pdf/branding', async () => {
const { brandingOf } = await import('../helpers/goldens')
return { loadBranding: vi.fn(() => brandingOf('nologos')) }
})
const FREEZE_DIR = resolve(FIXTURES_DIR, 'goldens/r2')
const MAKE_FREEZE = process.env.MAKE_R2_FREEZE === '1'
const EXPORTED_AT = new Date('2026-10-13T09:00:00.000Z')
let sheet: SheetIndex
let golden: GoldenReports
beforeAll(async () => {
sheet = await loadTestSheet()
golden = buildGoldenReports(sheet)
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
vi.useFakeTimers({ toFake: ['Date'] })
vi.setSystemTime(EXPORTED_AT)
})
afterAll(() => {
vi.useRealTimers()
vi.restoreAllMocks()
})
async function exportedAttachment(
name: (typeof GOLDEN_REPORTS)[number],
): Promise<string> {
const { pdf } = await exportReportToPdf(golden.reports[name], sheet, {
locale: 'fr',
})
return new TextDecoder().decode(await readAttachmentBytes(pdf))
}
describe.each(GOLDEN_REPORTS)('archive envelope of %s', (name) => {
const file = resolve(FREEZE_DIR, `envelope.${name}.fr.nologos.json`)
it('matches the frozen envelope and the N-1 reader accepts it', async () => {
const text = await exportedAttachment(name)
if (MAKE_FREEZE) {
mkdirSync(FREEZE_DIR, { recursive: true })
writeFileSync(file, text)
}
const data: unknown = JSON.parse(text)
expect(data).toEqual(JSON.parse(readFileSync(file, 'utf8')))
expect(ReportArchiveEnvelopeSchema.safeParse(data).success).toBe(true)
const outcome = readArchiveDocument(data, await bundledMigrationMap())
expect(outcome.origin).toBe('envelope_v1')
expect(outcome.archive).not.toBeNull()
expect(outcome.snapshotRejected).toBeUndefined()
}, 30_000)
})
@@ -9,7 +9,7 @@ import {
} from 'vitest'
import { cleanup, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { Finding } from '@faunosteo/domain'
import type { Finding, LateralSide } from '@faunosteo/core-wasm/types'
import FindingsTreePicker from '@/components/observation/FindingsTreePicker'
import { useLocaleStore } from '@/state/localeStore'
import type { SheetIndex } from '@/services/sheetIndex'
@@ -22,18 +22,51 @@ beforeAll(async () => {
beforeEach(() => useLocaleStore.setState({ locale: 'fr' }))
afterEach(cleanup)
/**
* The picker reports the clicked leaf; the core builds or removes the finding
* (R2), as ObservationCard wires it. `onChange` receives the observation's
* findings after the toggle, which is what the picker handed out before R2.
*/
function CorePicker({
side,
selected,
onChange,
}: {
side?: LateralSide
selected: Finding[]
onChange: (next: Finding[]) => void
}) {
return (
<FindingsTreePicker
zone={sheet.findingZone('hip')!}
side={side}
selected={selected}
onToggle={(path, leafPosition) => {
const out = sheet.ops.toggleFinding({
observation: {
id: 'obs',
zones: [],
findings: selected,
freeTextFindings: [],
comment: '',
},
findingZoneId: 'hip',
path,
leafPosition,
...(side ? { side } : {}),
})
if (!out.ok) throw new Error(out.kind)
onChange(out.value.findings)
}}
/>
)
}
describe('FindingsTreePicker on a sheet finding zone', () => {
it('drills down the hip zone and selects a leaf as a v3 finding with snapshots and side', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
render(
<FindingsTreePicker
zone={sheet.findingZone('hip')!}
side="left"
selected={[]}
onChange={onChange}
/>,
)
render(<CorePicker side="left" selected={[]} onChange={onChange} />)
expect(screen.getByText('Hanche (coxo-fémorale)')).toBeInTheDocument()
await user.click(
screen.getByRole('button', {
@@ -72,13 +105,7 @@ describe('FindingsTreePicker on a sheet finding zone', () => {
},
]
const onChange = vi.fn()
render(
<FindingsTreePicker
zone={sheet.findingZone('hip')!}
selected={selected}
onChange={onChange}
/>,
)
render(<CorePicker selected={selected} onChange={onChange} />)
expect(screen.getByLabelText('1 finding selected')).toBeInTheDocument()
await user.click(
screen.getByRole('button', { name: 'Open Osteopathic dysfunctions' }),
@@ -113,13 +140,7 @@ describe('FindingsTreePicker on a sheet finding zone', () => {
it('flags a vet-referral leaf and omits the key on other leaves', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
render(
<FindingsTreePicker
zone={sheet.findingZone('hip')!}
selected={[]}
onChange={onChange}
/>,
)
render(<CorePicker selected={[]} onChange={onChange} />)
await user.click(
screen.getByRole('button', {
name: 'Ouvrir Dysfonctions ostéopathiques',
@@ -162,14 +183,7 @@ describe('FindingsTreePicker on a sheet finding zone', () => {
]
function renderPicker(selected: Finding[]) {
render(
<FindingsTreePicker
zone={sheet.findingZone('hip')!}
side="left"
selected={selected}
onChange={vi.fn()}
/>,
)
render(<CorePicker side="left" selected={selected} onChange={vi.fn()} />)
}
it('counts selected findings per level, none on a clean sibling', async () => {
@@ -223,13 +237,7 @@ describe('FindingsTreePicker on a sheet finding zone', () => {
})
it('the findings list carries no permanent compositing hint (text stays crisp)', () => {
render(
<FindingsTreePicker
zone={sheet.findingZone('hip')!}
selected={[]}
onChange={() => {}}
/>,
)
render(<CorePicker selected={[]} onChange={() => {}} />)
const ul = document.querySelector('ul') as HTMLElement
expect(ul.getAttribute('style') ?? '').not.toContain('will-change')
expect(ul.style.willChange).toBe('')
+8 -10
View File
@@ -4,15 +4,11 @@
* use, exported to a v3 PDF and read back without loss.
*/
import { describe, it, expect, vi, beforeAll } from 'vitest'
import {
readReportDocument,
type Finding,
type Report,
} from '@faunosteo/domain'
import type { Finding, Report } from '@faunosteo/core-wasm/types'
import { exportReportToPdf } from '@/pdf/export'
import { importReportFromPdf } from '@/pdf/import'
import { importAttachment, importReportFromPdf } from '@/pdf/import'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet } from '../helpers/sheet'
import { findingNodeAt, loadTestSheet } from '../helpers/sheet'
import {
leavesAsV2Report,
legacyLeaves,
@@ -34,7 +30,8 @@ beforeAll(async () => {
sheet = await loadTestSheet()
const leaves = legacyLeaves(loadLegacyBaseline())
const v2 = leavesAsV2Report(leaves)
const outcome = readReportDocument(v2, sheet.sheet.migrationMap)
// Read as the application reads an attachment: the core migrates the v2 report.
const outcome = importAttachment(v2, sheet).read
report = outcome.report
findings = report.observations.flatMap((o) => o.findings)
unresolvedFindings = outcome.unresolvedFindings
@@ -46,8 +43,9 @@ describe('the 612 legacy leaves in the application', () => {
expect(findings).toHaveLength(612)
expect(unresolvedFindings).toBe(29)
for (const f of findings) {
const node = sheet.nodeAt(f.findingZoneId, f.path)
const node = findingNodeAt(sheet, f.findingZoneId, f.path)
const where = `${f.findingZoneId}/${f.path.join('/')}`
expect(sheet.hasNode(f.findingZoneId, f.path), where).toBe(!f.unresolved)
if (f.unresolved) expect(node, where).toBeUndefined()
else {
expect(node, where).toBeDefined()
@@ -60,7 +58,7 @@ describe('the 612 legacy leaves in the application', () => {
const { pdf: bytes } = await exportReportToPdf(report, sheet, {
locale: 'fr',
})
const back = await importReportFromPdf(bytes, sheet.sheet.migrationMap)
const { read: back } = await importReportFromPdf(bytes, sheet)
expect(back.migrated).toBe(false)
expect(back.origin).toBe('envelope_v1')
expect(back.archive).not.toBeNull()
+192
View File
@@ -0,0 +1,192 @@
/**
* The N-1 reader test (RUST_ARCHITECTURE_REVIEW III.3 rule 7, VI.3 R2 row):
* every draft and archive the application writes through the Rust core must
* stay readable by the build before R2, whose Zod schemas and readers are
* frozen in `@faunosteo/core-wasm/n-1`. A rollback to that build then finds
* every session the R2 build left behind (key order may differ: D-R11).
*/
import {
afterAll,
beforeAll,
beforeEach,
describe,
expect,
it,
vi,
} from 'vitest'
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import {
readArchiveDocument,
readReportDocument,
ReportArchiveEnvelopeSchema,
ReportSchema,
} from '@faunosteo/core-wasm/n-1'
import { readAttachmentBytes } from '@faunosteo/pdf'
import { exportReportToPdf } from '@/pdf/export'
import { importAttachment } from '@/pdf/import'
import { useReportStore } from '@/state/reportStore'
import { ARCHIVE_KEY, DRAFT_KEY } from '@/state/persistence'
import type { SheetIndex } from '@/services/sheetIndex'
import { FIXTURES_DIR, ONE_PX_PNG } from '../helpers/goldens'
import {
archiveEnvelope,
bundledMigrationMap,
loadTestSheet,
minimalReport,
} from '../helpers/sheet'
vi.mock('@/pdf/browserRasterizer', () => ({
browserRasterizer: vi.fn(async () => ONE_PX_PNG),
}))
vi.mock('@/pdf/branding', async () => {
const { brandingOf } = await import('../helpers/goldens')
return { loadBranding: vi.fn(() => brandingOf('nologos')) }
})
let sheet: SheetIndex
beforeAll(async () => {
sheet = await loadTestSheet()
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
})
afterAll(() => vi.restoreAllMocks())
beforeEach(() => {
sessionStorage.clear()
useReportStore.setState({
report: null,
archive: null,
activeObservationIndex: 0,
})
})
const fixture = (name: string): unknown =>
JSON.parse(readFileSync(resolve(FIXTURES_DIR, name), 'utf8'))
/** The draft mirror as the previous build reads it on a rollback. */
async function expectN1ReadsTheDraft(): Promise<void> {
const text = sessionStorage.getItem(DRAFT_KEY)
expect(text).not.toBeNull()
const data: unknown = JSON.parse(text!)
expect(ReportSchema.safeParse(data).success).toBe(true)
const read = readReportDocument(data, await bundledMigrationMap())
expect(read.report).toEqual(useReportStore.getState().report)
}
describe('drafts written through the core', () => {
it('a new report', async () => {
useReportStore.getState().initReport(
{
date: '2026-10-14',
practitioner: { name: 'Dr. Dupont', cabinet: 'Équi' },
animal: { speciesId: 'equine', name: 'Mistral' },
owner: { name: 'Jean Martin' },
observations: [],
conclusion: '',
recommendations: '',
nextAppointment: { kind: 'period', text: 'dans 3 semaines' },
},
sheet.sheet.ref,
)
await expectN1ReadsTheDraft()
})
it('after the editor reducers (zones, sides, vertebrae, findings)', async () => {
useReportStore.getState().initReport(
{
date: '2026-10-14',
practitioner: { name: 'Dr. Dupont' },
animal: { speciesId: 'equine', name: 'Mistral' },
owner: { name: 'Jean Martin' },
observations: [],
conclusion: '',
recommendations: '',
},
sheet.sheet.ref,
)
const apply = (obs: ReturnType<typeof current>) =>
useReportStore.getState().updateObservation(0, obs)
const current = () => useReportStore.getState().report!.observations[0]!
const click = sheet.ops.zoneClick(current(), 'c7-t1')
if (!click.ok || !click.value.observation) throw new Error('zone click')
apply(click.value.observation)
const sides = sheet.ops.addSides(current(), 'hip', ['left', 'right'])
if (!sides.ok) throw new Error('add sides')
apply(sides.value)
const spine = sheet.ops.zoneClick(current(), 'cervical')
if (!spine.ok || !spine.value.observation) throw new Error('spine click')
apply(spine.value.observation)
const synced = sheet.ops.syncVertebrae(
current(),
[
{ region: 'C', index: 3 },
{ region: 'L', index: 2 },
],
'main',
)
if (!synced.ok) throw new Error('vertebrae')
apply(synced.value)
const articular = sheet
.findingZone('hip')!
.categories.find((c) => c.id === 'hip-dysfunctions')!
.children.find((n) => n.id === 'articular')!
const finding = sheet.ops.toggleFinding({
observation: current(),
findingZoneId: 'hip',
path: ['hip-dysfunctions', 'articular', 'hypermobility'],
leafPosition: articular.children.findIndex(
(n) => n.id === 'hypermobility',
),
side: 'left',
})
if (!finding.ok) throw new Error(finding.kind)
apply(finding.value)
expect(current().zones.length).toBeGreaterThanOrEqual(4)
expect(current().findings).toHaveLength(1)
await expectN1ReadsTheDraft()
})
it('after the restore of a v2 draft left by the previous version', async () => {
sessionStorage.setItem(
DRAFT_KEY,
JSON.stringify(fixture('report-v2.full.json')),
)
expect(useReportStore.getState().restoreDraft(sheet)).toMatchObject({
kind: 'restored',
})
await expectN1ReadsTheDraft()
})
it('after the import of an archive (draft and archive mirror)', async () => {
const report = minimalReport(sheet, { conclusion: 'imported' })
const { read, rebase } = importAttachment(
archiveEnvelope(sheet, report),
sheet,
)
useReportStore
.getState()
.hydrateImport({ report: rebase.report, archive: read.archive })
await expectN1ReadsTheDraft()
const archive: unknown = JSON.parse(sessionStorage.getItem(ARCHIVE_KEY)!)
expect(ReportArchiveEnvelopeSchema.safeParse(archive).success).toBe(true)
})
})
describe('archives exported from core-built reports', () => {
it.each([['report-v3.demo.json'], ['report-v2.full.json']])(
'the attachment of %s reads back through the N-1 reader',
async (name) => {
const { report } = importAttachment(fixture(name), sheet).read
const { pdf } = await exportReportToPdf(report, sheet, { locale: 'fr' })
const data: unknown = JSON.parse(
new TextDecoder().decode(await readAttachmentBytes(pdf)),
)
expect(ReportArchiveEnvelopeSchema.safeParse(data).success).toBe(true)
const outcome = readArchiveDocument(data, await bundledMigrationMap())
expect(outcome.origin).toBe('envelope_v1')
expect(outcome.archive).not.toBeNull()
expect(outcome.snapshotRejected).toBeUndefined()
expect(outcome.report).toEqual(report)
},
30_000,
)
})
+49 -28
View File
@@ -15,23 +15,24 @@ import {
} from 'vitest'
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import {
buildSheetIndex,
buildSheetSnapshot,
ReportSchema,
type Branding,
type FindingCategory,
type FindingNode,
type Report,
type ReportArchiveEnvelope,
} from '@faunosteo/domain'
import { exportFromEnvelope, readReportArchive } from '@faunosteo/pdf'
import type {
Branding,
LocalizedText,
Report,
} from '@faunosteo/core-wasm/types'
import { exportFromEnvelope } from '@faunosteo/pdf'
import { exportReportToPdf } from '@/pdf/export'
import { importAttachment, importReportFromPdf } from '@/pdf/import'
import { browserRasterizer } from '@/pdf/browserRasterizer'
import { loadBranding } from '@/pdf/branding'
import type { LoadedSheet } from '@/sheets/provider'
import type { BundledSheetData } from '@/sheets/provider'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet } from '../helpers/sheet'
import {
bundledSheet,
loadTestSheet,
sheetFromBundle,
sheetSnapshot,
} from '../helpers/sheet'
import {
FIXTURES_DIR,
ONE_PX_PNG,
@@ -63,11 +64,12 @@ let demo: Report
beforeAll(async () => {
sheet = await loadTestSheet()
demo = ReportSchema.parse(
demo = importAttachment(
JSON.parse(
readFileSync(resolve(FIXTURES_DIR, 'report-v3.demo.json'), 'utf8'),
),
)
sheet,
).read.report
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
})
afterEach(() => {
@@ -107,10 +109,13 @@ function appExport(index: SheetIndex): Promise<Facts & { pdf: Uint8Array }> {
return recorded(() => exportReportToPdf(demo, index, { locale: 'fr' }))
}
async function archiveOf(pdf: Uint8Array): Promise<ReportArchiveEnvelope> {
const outcome = await readReportArchive(pdf, sheet.sheet.migrationMap)
/** The envelope the app reads back from its own export, as the engine takes it. */
type EngineEnvelope = Parameters<typeof exportFromEnvelope>[0]
async function archiveOf(pdf: Uint8Array): Promise<EngineEnvelope> {
const { read: outcome } = await importReportFromPdf(pdf, sheet)
expect(outcome.origin).toBe('envelope_v1')
return outcome.archive!
return outcome.archive! as EngineEnvelope
}
const REEXPORT = {
@@ -119,26 +124,42 @@ const REEXPORT = {
exportedAt: new Date('2027-01-01T00:00:00.000Z'),
}
function renameNodes(nodes: (FindingCategory | FindingNode)[]): void {
/** A category or node of the bundled payload (authoring form: leaves have no children). */
interface PayloadNode {
name: LocalizedText
children?: PayloadNode[]
}
interface PayloadDocument {
annotations: {
id: string
name: LocalizedText | null
geometry: { type: string; cx?: number } | null
}[]
finding_zones: { name: LocalizedText; categories: PayloadNode[] }[]
}
function renameNodes(nodes: PayloadNode[]): void {
for (const node of nodes) {
node.name = {
fr: `${node.name.fr} (révisé)`,
en: `${node.name.en} (revised)`,
}
renameNodes(node.children)
renameNodes(node.children ?? [])
}
}
/** The catalog after a revision: every label changed, the hip marker moved. */
function revisedSheet(source: LoadedSheet): LoadedSheet {
function revisedSheet(source: BundledSheetData): BundledSheetData {
const next = structuredClone(source)
for (const a of next.document.annotations) {
const document = next.document as PayloadDocument
for (const a of document.annotations) {
if (a.name) {
a.name = { fr: `${a.name.fr} (révisé)`, en: `${a.name.en} (revised)` }
}
if (a.id === 'hip' && a.geometry?.type === 'circle') a.geometry.cx += 100
if (a.id === 'hip' && a.geometry?.type === 'circle') a.geometry.cx! += 100
}
for (const zone of next.document.finding_zones) {
for (const zone of document.finding_zones) {
zone.name = {
fr: `${zone.name.fr} (révisé)`,
en: `${zone.name.en} (revised)`,
@@ -154,14 +175,14 @@ describe('the archive survives its resources', () => {
const archive = await archiveOf(first.pdf)
// The revision is visible through the app path (labels and geometry)...
const revised = buildSheetIndex(revisedSheet(sheet.sheet))
const revised = sheetFromBundle(revisedSheet(await bundledSheet()))
const onRevised = await appExport(revised)
expect(onRevised.texts).not.toEqual(first.texts)
const revisedViews = snapshotViews(
buildSheetSnapshot(revised.sheet, demo),
const revisedViews = snapshotViews(sheetSnapshot(revised, demo), demo)
const archivedViews = snapshotViews(
archive.sheetSnapshot as Parameters<typeof snapshotViews>[0],
demo,
)
const archivedViews = snapshotViews(archive.sheetSnapshot, demo)
expect(revisedViews).not.toEqual(archivedViews)
// ...and absent from a re-export of the envelope alone.
+11 -42
View File
@@ -12,22 +12,17 @@ import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest'
import { PDFDocument } from 'pdf-lib'
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import {
buildSheetSnapshot,
readReportDocument,
ReportSchema,
type Report,
} from '@faunosteo/domain'
import type { Report } from '@faunosteo/core-wasm/types'
import { exportReportToPdf } from '@/pdf/export'
import { importReportFromPdf } from '@/pdf/import'
import type { SheetIndex } from '@/services/sheetIndex'
import type { Locale } from '@/i18n/types'
import { loadTestSheet } from '../helpers/sheet'
import { loadTestSheet, sheetSnapshot } from '../helpers/sheet'
import {
leavesAsV2Report,
legacyLeaves,
loadLegacyBaseline,
} from '../helpers/legacyLeaves'
buildGoldenReports,
GOLDEN_REPORTS,
type GoldenReportName,
} from '../helpers/goldenReports'
import {
checkGolden,
FIXTURES_DIR,
@@ -54,43 +49,17 @@ vi.mock('@/pdf/branding', async () => {
return { loadBranding: vi.fn(() => brandingOf(logoMode.current)) }
})
const REPORTS = ['v2full', 'demo', 'v2unresolved'] as const
type ReportName = (typeof REPORTS)[number]
const REPORTS = GOLDEN_REPORTS
const MODES: readonly LogoMode[] = ['nologos', 'logos']
const BARE_PDF = resolve(FIXTURES_DIR, 'report-v3.bare.pdf')
const readJson = (name: string): unknown =>
JSON.parse(readFileSync(resolve(FIXTURES_DIR, name), 'utf8'))
let sheet: SheetIndex
let reports: Record<ReportName, Report>
let reports: Record<GoldenReportName, Report>
let unresolvedOfV2Unresolved = 0
/** sphenoid + ssb (the families the migration cannot place) plus one leaf that resolves. */
function buildV2Unresolved(): Report {
const leaves = legacyLeaves(loadLegacyBaseline())
const unresolvedFamilies = leaves.filter(
(l) => l.zoneId === 'sphenoid' || l.zoneId === 'ssb',
)
const resolved = leaves.find((l) => l.zoneId === 'frontal')!
const outcome = readReportDocument(
leavesAsV2Report([...unresolvedFamilies, resolved]),
sheet.sheet.migrationMap,
)
unresolvedOfV2Unresolved = outcome.unresolvedFindings
return outcome.report
}
beforeAll(async () => {
sheet = await loadTestSheet()
reports = {
v2full: readReportDocument(
readJson('report-v2.full.json'),
sheet.sheet.migrationMap,
).report,
demo: ReportSchema.parse(readJson('report-v3.demo.json')),
v2unresolved: buildV2Unresolved(),
}
;({ reports, unresolvedOfV2Unresolved } = buildGoldenReports(sheet))
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
})
afterAll(() => vi.restoreAllMocks())
@@ -185,7 +154,7 @@ describe.each(REPORTS)('goldens of %s', (name) => {
// shrinks to the highlighted markers plus the asset's own, and
// `dataAttributes` drops from 2 to 0. Everything else must match.
it('highlighted views: same facts but titles and data attributes', () => {
const snapshot = buildSheetSnapshot(sheet.sheet, reports[name])
const snapshot = sheetSnapshot(sheet, reports[name])
const actual = snapshotViews(snapshot, reports[name])
const expected = readGolden<ViewSnapshot[]>(`views.${name}.json`)
const comparable = (v: ViewSnapshot) => ({
@@ -208,7 +177,7 @@ describe.each(REPORTS)('goldens of %s', (name) => {
describe('report-v3.bare.pdf', () => {
it('is the demo report exported bare by Step 5 and imports with no archive', async () => {
const bytes = new Uint8Array(readFileSync(BARE_PDF))
const outcome = await importReportFromPdf(bytes, sheet.sheet.migrationMap)
const { read: outcome } = await importReportFromPdf(bytes, sheet)
expect(outcome.origin).toBe('bare_v3')
expect(outcome.migrated).toBe(false)
expect(outcome.archive).toBeNull()
+29 -3
View File
@@ -7,9 +7,14 @@
*/
import { describe, it, expect, beforeAll } from 'vitest'
import { PDFDocument } from 'pdf-lib'
import { importReportFromPdf, ImportError, MAX_PDF_BYTES } from '@/pdf/import'
import {
importAttachment,
importReportFromPdf,
ImportError,
MAX_PDF_BYTES,
} from '@/pdf/import'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet } from '../helpers/sheet'
import { loadTestSheet, minimalReport } from '../helpers/sheet'
let sheet: SheetIndex
beforeAll(async () => {
@@ -25,7 +30,7 @@ async function pdfWithoutAttachment(keywords?: string[]): Promise<Uint8Array> {
}
async function rejectsWith(bytes: Uint8Array, kind: string): Promise<void> {
const promise = importReportFromPdf(bytes, sheet.sheet.migrationMap)
const promise = importReportFromPdf(bytes, sheet)
await expect(promise).rejects.toBeInstanceOf(ImportError)
await expect(promise).rejects.toMatchObject({ kind })
}
@@ -46,3 +51,24 @@ describe('importReportFromPdf error kinds', () => {
await rejectsWith(new Uint8Array(MAX_PDF_BYTES + 1), 'invalid_pdf')
})
})
describe('importAttachment on the core (L1)', () => {
it('refuses an attachment with a lone surrogate as lone_surrogate, never rewritten', () => {
for (const text of ['a\ud800b', '\udfff']) {
const attachment = minimalReport(sheet, { conclusion: text })
expect(() => importAttachment(attachment, sheet)).toThrow(
expect.objectContaining({ kind: 'lone_surrogate' }),
)
expect(attachment.conclusion).toBe(text)
}
})
it('imports normal text with pairs and literal backslashes unchanged', () => {
const text = 'é 😀 \\ud800 \ufffd'
const imported = importAttachment(
minimalReport(sheet, { conclusion: text }),
sheet,
)
expect(imported.rebase.report.conclusion).toBe(text)
})
})
+26 -39
View File
@@ -17,18 +17,14 @@ import { AFRelationship, PDFDocument, PDFPage } from 'pdf-lib'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'node:path'
import {
buildSheetSnapshot,
type Observation,
type Report,
} from '@faunosteo/domain'
import type { Observation, Report } from '@faunosteo/core-wasm/types'
import { composeHighlightedViewSvg, defaultPdfLabels } from '@faunosteo/pdf'
import { exportReportToPdf } from '@/pdf/export'
import { importReportFromPdf, ImportError } from '@/pdf/import'
import { formatDate } from '@/lib/dates'
import type { Locale } from '@/i18n/types'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet, minimalReport } from '../helpers/sheet'
import { loadTestSheet, minimalReport, sheetSnapshot } from '../helpers/sheet'
// The factory runs when the engine first loads the adapter: fixed 1×1 PNG.
vi.mock('@/pdf/browserRasterizer', async () => {
@@ -36,6 +32,14 @@ vi.mock('@/pdf/browserRasterizer', async () => {
return { browserRasterizer: vi.fn(async () => ONE_PX_PNG) }
})
/** The engine's own (Zod-inferred) types of the same JSON contracts. */
type EngineView = Parameters<typeof composeHighlightedViewSvg>
/** The layered reading the application does on import (the core's read part). */
async function readBack(bytes: Uint8Array) {
return (await importReportFromPdf(bytes, sheet)).read
}
/** The static PDF strings now belong to the engine's label set. */
const { fr, en } = defaultPdfLabels
@@ -147,7 +151,7 @@ describe('export on a full v3 report (FR)', () => {
const report = minimalReport(sheet, { observations: [fullObservation()] })
for (const locale of ['fr', 'en'] as const) {
const bytes = await exportPdf(report, locale)
const out = await importReportFromPdf(bytes, sheet.sheet.migrationMap)
const out = await readBack(bytes)
expect(out.migrated).toBe(false)
expect(out.origin).toBe('envelope_v1')
expect(out.report).toEqual(report)
@@ -163,7 +167,7 @@ describe('export on a full v3 report (FR)', () => {
// pdf.goldens.test.ts "highlighted views".
it('highlights the observation zones of a view and omits the other markers', () => {
const report = minimalReport(sheet, { observations: [fullObservation()] })
const snapshot = buildSheetSnapshot(sheet.sheet, report)
const snapshot = sheetSnapshot(sheet, report) as EngineView[0]
const svg = composeHighlightedViewSvg(snapshot, 'main', fullObservation())
expect(svg).toContain('viewBox="0 0 2073.4 1629.4"')
expect(svg).toContain('fill="#b85a3f"')
@@ -278,7 +282,7 @@ describe('PDF content on a two-observation report', () => {
})
expect(fetchSpy).not.toHaveBeenCalled()
expect(warnings).toEqual([])
const out = await importReportFromPdf(pdf, sheet.sheet.migrationMap)
const out = await readBack(pdf)
const branding = out.archive!.branding
expect(branding.headerLogo?.kind).toBe('png')
expect(branding.footerLogo?.kind).toBe('png')
@@ -321,27 +325,24 @@ describe('attachment rejection', () => {
it('reports no_attachment for a foreign JSON attachment (no version)', async () => {
const bytes = await pdfWith('other.json', { hello: 'world' })
await expect(
importReportFromPdf(bytes, sheet.sheet.migrationMap),
).rejects.toMatchObject({ kind: 'no_attachment' })
await expect(importReportFromPdf(bytes, sheet)).rejects.toMatchObject({
kind: 'no_attachment',
})
})
it('reports no_attachment for a v3 report failing validation', async () => {
const broken: Record<string, unknown> = { ...minimalReport(sheet) }
delete broken.sheet
const bytes = await pdfWith('osteo-report.json', broken)
await expect(
importReportFromPdf(bytes, sheet.sheet.migrationMap),
).rejects.toMatchObject({ kind: 'no_attachment' })
await expect(importReportFromPdf(bytes, sheet)).rejects.toMatchObject({
kind: 'no_attachment',
})
})
})
describe('import of the frozen v2 archive PDFs', () => {
it('migrates the full v2 report: ids, views, paths, severities, unresolved findings', async () => {
const out = await importReportFromPdf(
fixture('report-v2.full.pdf'),
sheet.sheet.migrationMap,
)
const out = await readBack(fixture('report-v2.full.pdf'))
expect(out.migrated).toBe(true)
const { report } = out
expect(report.version).toBe(3)
@@ -379,10 +380,7 @@ describe('import of the frozen v2 archive PDFs', () => {
expect.arrayContaining(['moderate', 'severe']),
)
// Re-export and re-import: stable.
const again = await importReportFromPdf(
await exportPdf(report, 'fr'),
sheet.sheet.migrationMap,
)
const again = await readBack(await exportPdf(report, 'fr'))
expect(again.report).toEqual(report)
expect(again.migrated).toBe(false)
expect(again.origin).toBe('envelope_v1')
@@ -424,10 +422,7 @@ describe('import of the frozen v2 archive PDFs', () => {
'osteo-report.json',
{ mimeType: 'application/json' },
)
const out = await importReportFromPdf(
await doc.save(),
sheet.sheet.migrationMap,
)
const out = await readBack(await doc.save())
const [obs] = out.report.observations
expect(obs!.zones).toEqual([
expect.objectContaining({
@@ -451,18 +446,12 @@ describe('import of the frozen v2 archive PDFs', () => {
expect(out.unresolvedFindings).toBe(1)
expect(out.unresolvedZones).toBe(1)
// The migrated document is a valid v3 document: exporting it again keeps the flags.
const again = await importReportFromPdf(
await exportPdf(out.report, 'en'),
sheet.sheet.migrationMap,
)
const again = await readBack(await exportPdf(out.report, 'en'))
expect(again.report.observations[0]!.findings[0]!.unresolved).toBe(true)
})
it('migrates the minimal v2 report', async () => {
const out = await importReportFromPdf(
fixture('report-v2.minimal.pdf'),
sheet.sheet.migrationMap,
)
const out = await readBack(fixture('report-v2.minimal.pdf'))
expect(out.report.version).toBe(3)
expect(out.report.observations).toEqual([])
expect(out.unresolvedFindings + out.unresolvedZones).toBe(0)
@@ -477,11 +466,9 @@ describe('import of the frozen v2 archive PDFs', () => {
{ mimeType: 'application/json' },
)
await expect(
importReportFromPdf(await doc.save(), sheet.sheet.migrationMap),
importReportFromPdf(await doc.save(), sheet),
).rejects.toMatchObject({ kind: 'incompatible_version', foundVersion: 7 })
const fake = new Uint8Array([37, 80, 68, 70, 45, 49, 46, 52, 10])
await expect(
importReportFromPdf(fake, sheet.sheet.migrationMap),
).rejects.toThrow(ImportError)
await expect(importReportFromPdf(fake, sheet)).rejects.toThrow(ImportError)
})
})
@@ -0,0 +1,118 @@
/**
* R2 plan rev 2 (robustness BLOCKER 1): when the core cannot run, a reload of
* the editor shows the degraded notice with a retry, never redirects to the
* home page, and never reads, rewrites or removes the tab's draft. A sheet
* payload the core refuses (`invalid_sheet`) shows the same notice. Once the
* module loads, the retry restores the draft.
*/
import {
afterEach,
beforeAll,
beforeEach,
describe,
expect,
it,
vi,
} from 'vitest'
import { cleanup, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import EditorRoute from '@/app/routes/EditorRoute'
import { setCoreRuntime } from '@/core/runtime'
import { bundledSheetProvider } from '@/sheets/provider'
import { setSheetProvider } from '@/sheets/useSheet'
import { useReportStore } from '@/state/reportStore'
import { DRAFT_KEY } from '@/state/persistence'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
import type { SheetIndex } from '@/services/sheetIndex'
import { testCoreRuntime, unavailableCoreRuntime } from '../helpers/core'
import { bundledSheet, loadTestSheet, minimalReport } from '../helpers/sheet'
let sheet: SheetIndex
let draft: string
beforeAll(async () => {
sheet = await loadTestSheet()
draft = JSON.stringify(minimalReport(sheet, { conclusion: 'unsaved work' }))
})
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
sessionStorage.clear()
sessionStorage.setItem('osteo:disclaimer-shown', '1')
window.scrollTo = vi.fn() as unknown as typeof window.scrollTo
vi.stubGlobal('alert', vi.fn())
useReportStore.setState({
report: null,
archive: null,
activeObservationIndex: 0,
})
// After the reset (an empty store mirrors no draft): the tab as a reload finds it.
sessionStorage.setItem(DRAFT_KEY, draft)
})
afterEach(async () => {
cleanup()
vi.unstubAllGlobals()
setCoreRuntime(await testCoreRuntime())
setSheetProvider(bundledSheetProvider)
})
function mount() {
return render(
<MemoryRouter initialEntries={['/editor']}>
<Routes>
<Route path="/" element={<p data-testid="home-route" />} />
<Route path="/editor" element={<EditorRoute />} />
</Routes>
</MemoryRouter>,
)
}
async function expectDegraded() {
await screen.findByText(fr['sheet.core_unavailable']!)
expect(
screen.getByRole('button', { name: fr['sheet.core_retry'] }),
).toBeInTheDocument()
expect(screen.queryByTestId('home-route')).toBeNull()
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(draft)
expect(useReportStore.getState().report).toBeNull()
}
describe('EditorRoute while the core cannot run', () => {
it('shows the degraded notice, stays on the editor and leaves the draft byte-identical', async () => {
setCoreRuntime(unavailableCoreRuntime())
setSheetProvider(bundledSheetProvider)
mount()
await expectDegraded()
expect(window.alert).not.toHaveBeenCalled()
})
it('restores the draft once a retry finds the module', async () => {
const user = userEvent.setup()
setCoreRuntime(unavailableCoreRuntime())
setSheetProvider(bundledSheetProvider)
mount()
await expectDegraded()
// The module is reachable again (network back, CSP fixed).
setCoreRuntime(await testCoreRuntime())
await user.click(
screen.getByRole('button', { name: fr['sheet.core_retry'] }),
)
await waitFor(() =>
expect(useReportStore.getState().report?.conclusion).toBe('unsaved work'),
)
expect(screen.queryByTestId('home-route')).toBeNull()
})
it('shows the same notice for a sheet payload the core refuses (invalid_sheet)', async () => {
const bundle = await bundledSheet()
setSheetProvider({
getReferenceSheet: async () => ({
...bundle,
document: { schema_version: 2, broken: true },
}),
})
mount()
await expectDegraded()
})
})
@@ -43,7 +43,9 @@ beforeEach(() => {
sessionStorage.setItem('osteo:disclaimer-shown', '1')
window.scrollTo = vi.fn() as unknown as typeof window.scrollTo
useReportStore.setState({ report: null, activeObservationIndex: 0 })
useReportStore.getState().hydrateReport(minimalReport(sheet))
useReportStore
.getState()
.hydrateImport({ report: minimalReport(sheet), archive: null })
exportMock.mockReset()
downloads.length = 0
URL.createObjectURL = vi.fn(() => 'blob:faunosteo-test')
@@ -43,8 +43,8 @@ beforeEach(() => {
window.scrollTo = vi.fn() as unknown as typeof window.scrollTo
vi.stubGlobal('alert', vi.fn())
useReportStore.setState({ report: null, activeObservationIndex: 0 })
useReportStore.getState().hydrateReport(
minimalReport(sheet, {
useReportStore.getState().hydrateImport({
report: minimalReport(sheet, {
observations: [
{
id: 'o1',
@@ -55,7 +55,8 @@ beforeEach(() => {
},
],
}),
)
archive: null,
})
})
afterEach(() => {
cleanup()
@@ -1,6 +1,7 @@
/**
* T15 (STEP6 §7, §16): the home route on Step 6 archives, with
* `importReportFromPdf` mocked. Every alert opens with a headline: complete
* T15 (STEP6 §7, §16): the home route on Step 6 archives, with the byte
* scan (`readAttachment`) mocked to hand over the attachment; the layered
* read and the rebase run in the core (R2). Every alert opens with a headline: complete
* restoration or partial recovery. Same sheet: archive kept in the store and
* mirrored, complete + archive_ok. Other sheet: the report is rebased on the
* loaded sheet (unresolved flags, labels from the archived snapshot, sheet
@@ -27,12 +28,11 @@ import {
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import type {
Annotation,
ArchiveReadOutcome,
Report,
ReportArchiveEnvelope,
} from '@faunosteo/domain'
} from '@faunosteo/core-wasm/types'
import HomeRoute from '@/app/routes/HomeRoute'
import { ImportError, importReportFromPdf } from '@/pdf/import'
import { ImportError, readAttachment } from '@/pdf/import'
import { useReportStore } from '@/state/reportStore'
import { ARCHIVE_KEY } from '@/state/persistence'
import { useLocaleStore } from '@/state/localeStore'
@@ -42,9 +42,9 @@ import { archiveEnvelope, loadTestSheet, minimalReport } from '../helpers/sheet'
vi.mock('@/pdf/import', async (importOriginal) => ({
...(await importOriginal<typeof import('@/pdf/import')>()),
importReportFromPdf: vi.fn(),
readAttachment: vi.fn(),
}))
const importMock = vi.mocked(importReportFromPdf)
const readMock = vi.mocked(readAttachment)
let sheet: SheetIndex
@@ -60,7 +60,7 @@ beforeEach(() => {
activeObservationIndex: 0,
})
vi.stubGlobal('alert', vi.fn())
importMock.mockReset()
readMock.mockReset()
})
afterEach(() => {
cleanup()
@@ -69,23 +69,6 @@ afterEach(() => {
const OTHER_SHA = 'b'.repeat(64)
/** An outcome carrying a kept envelope (v3, nothing migrated). */
function archived(
report: Report,
archive: ReportArchiveEnvelope | null,
patch: Partial<ArchiveReadOutcome> = {},
): ArchiveReadOutcome {
return {
report,
origin: 'envelope_v1',
migrated: false,
unresolvedZones: 0,
unresolvedFindings: 0,
archive,
...patch,
}
}
function reportWithHip(): Report {
return minimalReport(sheet, {
observations: [
@@ -162,15 +145,14 @@ async function mountAndPickPdf(): Promise<void> {
const alertMock = () => vi.mocked(window.alert)
/** The alert split on its blank lines: headline first, then the detail lines. */
const alertLines = () =>
(alertMock().mock.calls[0]![0] as string).split('\n\n')
const alertLines = () => (alertMock().mock.calls[0]![0] as string).split('\n\n')
const errorText = () => screen.queryByText(/./, { selector: 'p.text-red-700' })
describe('HomeRoute import of a Step 6 archive', () => {
it('same sheet: keeps the archive in the store and its mirror, alerts archive_ok, no rebase', async () => {
const report = reportWithHip()
const archive = archiveEnvelope(sheet, report)
importMock.mockResolvedValue(archived(report, archive))
readMock.mockResolvedValue(archive)
await mountAndPickPdf()
await screen.findByTestId('editor-route')
const state = useReportStore.getState()
@@ -188,7 +170,9 @@ describe('HomeRoute import of a Step 6 archive', () => {
it('other sheet: rebases onto the loaded sheet, labels from the archived snapshot, alert with the count', async () => {
const { report, archive } = staleReportAndArchive()
importMock.mockResolvedValue(archived(report, archive))
// The attachment is the envelope of the stale report (read by the core).
expect(archive.report).toBe(report)
readMock.mockResolvedValue(archive)
await mountAndPickPdf()
await screen.findByTestId('editor-route')
const opened = useReportStore.getState().report!
@@ -221,7 +205,7 @@ describe('HomeRoute import of a Step 6 archive', () => {
})
const archive = archiveEnvelope(sheet, report)
archive.sheetSnapshot.ref.documentSha256 = OTHER_SHA
importMock.mockResolvedValue(archived(report, archive))
readMock.mockResolvedValue(archive)
await mountAndPickPdf()
await screen.findByTestId('editor-route')
const opened = useReportStore.getState().report!
@@ -237,9 +221,10 @@ describe('HomeRoute import of a Step 6 archive', () => {
it('snapshot rejected: the report opens, the alert names the reason, no archive kept', async () => {
const report = reportWithHip()
importMock.mockResolvedValue(
archived(report, null, { snapshotRejected: 'caps' }),
)
// A label over the 512-character cap: the core drops the snapshot ('caps').
const archive = archiveEnvelope(sheet, report)
archive.sheetSnapshot.document.name.fr = 'x'.repeat(513)
readMock.mockResolvedValue(archive)
await mountAndPickPdf()
await screen.findByTestId('editor-route')
expect(useReportStore.getState().report).toEqual(report)
@@ -256,7 +241,7 @@ describe('HomeRoute import of a Step 6 archive', () => {
})
it('attachment_stripped → its error message, nothing opened', async () => {
importMock.mockRejectedValue(new ImportError('attachment_stripped'))
readMock.mockRejectedValue(new ImportError('attachment_stripped'))
await mountAndPickPdf()
await waitFor(() => expect(errorText()).not.toBeNull())
expect(errorText()!.textContent).toBe(
@@ -1,8 +1,10 @@
/**
* Step 6 Phase 0 characterisation of the import flow on the home route, with
* `importReportFromPdf` mocked: the migration alert (degraded headline, then
* the count), the three ImportError kinds plus the generic error mapped to
* the FR messages, and the navigation to /editor on success.
* the two import steps mocked (R2: `readAttachment`, the engine's byte scan,
* then `importAttachment`, the core's layered read and rebase on the loaded
* sheet): the migration alert (degraded headline, then the count), the three
* ImportError kinds plus the generic error mapped to the FR messages, and the
* navigation to /editor on success; `lone_surrogate` (L1) has its own message.
*/
import {
describe,
@@ -21,9 +23,14 @@ import {
waitFor,
} from '@testing-library/react'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import type { ArchiveReadOutcome } from '@faunosteo/domain'
import type { ArchiveImport } from '@faunosteo/core-wasm/types'
import HomeRoute from '@/app/routes/HomeRoute'
import { ImportError, importReportFromPdf, MAX_PDF_BYTES } from '@/pdf/import'
import {
ImportError,
importAttachment,
MAX_PDF_BYTES,
readAttachment,
} from '@/pdf/import'
import { useReportStore } from '@/state/reportStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
@@ -32,9 +39,12 @@ import { loadTestSheet, minimalReport } from '../helpers/sheet'
vi.mock('@/pdf/import', async (importOriginal) => ({
...(await importOriginal<typeof import('@/pdf/import')>()),
importReportFromPdf: vi.fn(),
readAttachment: vi.fn(),
importAttachment: vi.fn(),
}))
const importMock = vi.mocked(importReportFromPdf)
const readMock = vi.mocked(readAttachment)
const importMock = vi.mocked(importAttachment)
const ATTACHMENT = { version: 3 }
let sheet: SheetIndex
@@ -49,6 +59,8 @@ beforeEach(() => {
activeObservationIndex: 0,
})
vi.stubGlobal('alert', vi.fn())
readMock.mockReset()
readMock.mockResolvedValue(ATTACHMENT)
importMock.mockReset()
})
afterEach(() => {
@@ -56,19 +68,28 @@ afterEach(() => {
vi.unstubAllGlobals()
})
/** The outcome shape importReportFromPdf resolves with (bare report, no archive). */
/** What the import resolves with: the read (bare report, no archive) and no rebase. */
function outcome(patch: {
migrated: boolean
unresolvedZones?: number
unresolvedFindings?: number
}): ArchiveReadOutcome {
}): ArchiveImport {
const report = minimalReport(sheet)
return {
report: minimalReport(sheet),
origin: patch.migrated ? 'v2' : 'bare_v3',
archive: null,
unresolvedZones: 0,
unresolvedFindings: 0,
...patch,
read: {
report,
origin: patch.migrated ? 'v2' : 'bare_v3',
archive: null,
unresolvedZones: 0,
unresolvedFindings: 0,
...patch,
},
rebase: {
report,
unresolvedZones: 0,
unresolvedFindings: 0,
rebased: false,
},
}
}
@@ -98,20 +119,22 @@ const alertMock = () => vi.mocked(window.alert)
const errorText = () => screen.queryByText(/./, { selector: 'p.text-red-700' })
describe('HomeRoute import: success paths', () => {
it('passes the file bytes and the sheet migration map, hydrates, navigates to /editor', async () => {
importMock.mockResolvedValue(outcome({ migrated: false }))
it('passes the file bytes to the scan and the attachment to the loaded sheet, hydrates, navigates to /editor', async () => {
importMock.mockReturnValue(outcome({ migrated: false }))
await mountAndPickPdf()
await screen.findByTestId('editor-route')
expect(readMock).toHaveBeenCalledTimes(1)
expect(readMock.mock.calls[0]![0]).toBeInstanceOf(Uint8Array)
expect(importMock).toHaveBeenCalledTimes(1)
const [bytes, map] = importMock.mock.calls[0]!
expect(bytes).toBeInstanceOf(Uint8Array)
expect(map).toBe(sheet.sheet.migrationMap)
const [attachment, index] = importMock.mock.calls[0]!
expect(attachment).toBe(ATTACHMENT)
expect(index).toBe(sheet)
expect(useReportStore.getState().report?.id).toBe('r1')
expect(alertMock()).not.toHaveBeenCalled()
})
it('alerts "degraded" then the unresolved count (zones + findings) after a lossy migration', async () => {
importMock.mockResolvedValue(
importMock.mockReturnValue(
outcome({ migrated: true, unresolvedZones: 1, unresolvedFindings: 1 }),
)
await mountAndPickPdf()
@@ -120,13 +143,11 @@ describe('HomeRoute import: success paths', () => {
const message = alertMock().mock.calls[0]![0] as string
const [headline, ...lines] = message.split('\n\n')
expect(headline).toBe(fr['home.import.degraded'])
expect(lines).toEqual([
fr['home.import.migrated']!.replace('{count}', '2'),
])
expect(lines).toEqual([fr['home.import.migrated']!.replace('{count}', '2')])
})
it('stays silent on a migration that lost nothing', async () => {
importMock.mockResolvedValue(outcome({ migrated: true }))
importMock.mockReturnValue(outcome({ migrated: true }))
await mountAndPickPdf()
await screen.findByTestId('editor-route')
expect(alertMock()).not.toHaveBeenCalled()
@@ -150,6 +171,11 @@ describe('HomeRoute import: error paths', () => {
new ImportError('no_attachment'),
fr['home.import.error_no_attachment']!,
],
[
'lone_surrogate → malformed text message, file untouched',
new ImportError('lone_surrogate'),
fr['home.import.error_lone_surrogate']!,
],
[
'generic Error → generic message',
new Error('disk on fire'),
@@ -158,7 +184,9 @@ describe('HomeRoute import: error paths', () => {
]
it.each(cases)('%s', async (_label, error, expected) => {
importMock.mockRejectedValue(error)
importMock.mockImplementation(() => {
throw error
})
await mountAndPickPdf()
await waitFor(() => expect(errorText()).not.toBeNull())
expect(errorText()!.textContent).toBe(expected)
@@ -177,6 +205,7 @@ describe('HomeRoute import: size gate', () => {
await waitFor(() => expect(errorText()).not.toBeNull())
expect(errorText()!.textContent).toBe(fr['home.import.error_invalid_pdf'])
expect(read).not.toHaveBeenCalled()
expect(readMock).not.toHaveBeenCalled()
expect(importMock).not.toHaveBeenCalled()
expect(screen.queryByTestId('editor-route')).toBeNull()
expect(useReportStore.getState().report).toBeNull()
+20 -6
View File
@@ -1,7 +1,9 @@
/**
* The archive check tool (scripts/compare-reports.ts) on the frozen v2 PDF,
* on a synthetic v2 report with removed and unknown items, on a v3 report
* and on a Step 6 envelope (archive header line).
* and on a Step 6 envelope (archive header line). The tool keeps its own
* reading on the frozen TypeScript domain until R4 (`compareSheetIndex`);
* the fixtures it compares are built through the application (the core).
*/
import { describe, it, expect, beforeAll } from 'vitest'
import { readFileSync } from 'node:fs'
@@ -14,6 +16,10 @@ import {
} from '@faunosteo/domain'
import { readAttachedDocument } from '@faunosteo/pdf'
import type { SheetIndex } from '@/services/sheetIndex'
import {
compareSheetIndex,
type CompareSheetIndex,
} from '../../scripts/compare/sheet'
import {
compareReport,
diffLines,
@@ -22,12 +28,19 @@ import {
renderSummary,
UNRESOLVED,
} from '../../scripts/compare/report'
import { archiveEnvelope, loadTestSheet, minimalReport } from '../helpers/sheet'
import {
archiveEnvelope,
bundledSheet,
loadTestSheet,
minimalReport,
} from '../helpers/sheet'
const HERE = dirname(fileURLToPath(import.meta.url))
const OPTS = { locale: 'fr' as const, full: false }
/** The application's sheet (fixture building) and the tool's own reading of it. */
let sheet: SheetIndex
let cli: CompareSheetIndex
function minimalV2(): ReportV2 {
return JSON.parse(
@@ -36,12 +49,13 @@ function minimalV2(): ReportV2 {
}
function compareRaw(raw: unknown, full = false) {
const outcome = readArchiveDocument(raw, sheet.sheet.migrationMap)
return compareReport(raw, outcome, sheet, { ...OPTS, full })
const outcome = readArchiveDocument(raw, cli.sheet.migrationMap)
return compareReport(raw, outcome, cli, { ...OPTS, full })
}
beforeAll(async () => {
sheet = await loadTestSheet()
cli = compareSheetIndex(await bundledSheet())
})
describe('compareReport on the frozen v2 archive PDF', () => {
@@ -210,7 +224,7 @@ describe('compareReport on unresolved items', () => {
describe('diff and arguments', () => {
it('diffs the v3 content of a migrated v2 report and its v3 re-reading', () => {
const v2 = minimalV2()
const migrated = readReportDocument(v2, sheet.sheet.migrationMap).report
const migrated = readReportDocument(v2, cli.sheet.migrationMap).report
const a = compareRaw(v2)
const b = compareRaw(migrated)
expect(diffLines(a.normalized, b.normalized)).toEqual([])
@@ -221,7 +235,7 @@ describe('diff and arguments', () => {
})
it('compares placeholders by default and real texts with --full', () => {
const base = readReportDocument(minimalV2(), sheet.sheet.migrationMap)
const base = readReportDocument(minimalV2(), cli.sheet.migrationMap)
const original = { ...base.report, conclusion: 'original' }
const edited = { ...base.report, conclusion: 'changed' }
expect(
@@ -1,214 +0,0 @@
/**
* Replaces char.clickChain (Step 1) one-to-one: every branch of the legacy
* zone-click chain, now decided by the pure service on the bundled sheet's
* annotations, with outcomes in Report v3 shape.
*/
import { beforeAll, describe, expect, it } from 'vitest'
import type { Annotation } from '@faunosteo/domain'
import type { SheetIndex } from '@/services/sheetIndex'
import {
addSides,
collectVertebrae,
decideZoneClick,
ensureZone,
refOf,
removeAllSides,
removeZoneAt,
sidesPresent,
syncVertebrae,
toggleZone,
} from '@/services/zoneInteraction'
import { emptyObservation, loadTestSheet } from '../helpers/sheet'
let sheet: SheetIndex
const a = (id: string): Annotation => {
const annotation = sheet.annotation(id)
if (!annotation) throw new Error(`no annotation ${id}`)
return annotation
}
beforeAll(async () => {
sheet = await loadTestSheet()
})
describe('decideZoneClick', () => {
it('opens the detail view for the trigger, even without an active observation', () => {
expect(decideZoneClick(a('head-trigger'), undefined)).toEqual({
kind: 'open_view',
viewId: 'head',
})
expect(decideZoneClick(a('head-trigger'), emptyObservation())).toEqual({
kind: 'open_view',
viewId: 'head',
})
})
it('only activates a fallback observation when none is active', () => {
expect(decideZoneClick(a('c7-t1'), undefined)).toEqual({
kind: 'activate_fallback',
})
expect(decideZoneClick(undefined, emptyObservation())).toEqual({
kind: 'ignore',
})
})
it('always opens the vertebra picker on a spine zone', () => {
const obs = toggleZone(emptyObservation(), a('cervical'))
expect(decideZoneClick(a('cervical'), emptyObservation())).toEqual({
kind: 'open_vertebra_picker',
})
expect(decideZoneClick(a('cervical'), obs)).toEqual({
kind: 'open_vertebra_picker',
})
})
it('routes bilateral zones through the side picker, or clears both sides', () => {
const hip = a('hip')
expect(decideZoneClick(hip, emptyObservation())).toEqual({
kind: 'open_laterality_picker',
})
const left = addSides(emptyObservation(), hip, ['left'])
expect(decideZoneClick(hip, left)).toEqual({
kind: 'open_laterality_picker',
})
const both = addSides(left, hip, ['right'])
expect(decideZoneClick(hip, both)).toEqual({ kind: 'remove_both_sides' })
})
it('toggles plain zones; the ten bilateral annotations and the 18 others split as the sheet says', () => {
expect(decideZoneClick(a('c7-t1'), emptyObservation())).toEqual({
kind: 'toggle',
})
const observable = sheet.sheet.document.annotations.filter(
(x) => x.kind !== 'detail_trigger',
)
const decisions = observable.map(
(x) => decideZoneClick(x, emptyObservation()).kind,
)
expect(
decisions.filter((k) => k === 'open_laterality_picker'),
).toHaveLength(10)
expect(decisions.filter((k) => k === 'open_vertebra_picker')).toHaveLength(
5,
)
expect(decisions.filter((k) => k === 'toggle')).toHaveLength(12)
})
})
describe('reducers', () => {
it('toggleZone adds a zone with snapshots then removes it', () => {
const added = toggleZone(emptyObservation(), a('c7-t1'))
expect(added.zones).toEqual([
{
annotationId: 'c7-t1',
viewId: 'main',
labelFrSnapshot: 'Charnière C7-T1 (cervico-thoracique)',
labelEnSnapshot: 'C7-T1 junction (cervicothoracic)',
},
])
expect(toggleZone(added, a('c7-t1')).zones).toEqual([])
})
it('ensureZone keeps an existing zone and reports its index', () => {
const base = toggleZone(
toggleZone(emptyObservation(), a('c7-t1')),
a('cervical'),
)
expect(ensureZone(base, a('cervical')).index).toBe(1)
const { observation, index } = ensureZone(emptyObservation(), a('cervical'))
expect(index).toBe(0)
expect(observation.zones[0]!.annotationId).toBe('cervical')
})
it('addSides appends only the missing sides and never removes one', () => {
const hip = a('hip')
const left = addSides(emptyObservation(), hip, ['left'])
expect(sidesPresent(left, refOf(hip))).toEqual(['left'])
const same = addSides(left, hip, ['left'])
expect(same).toBe(left)
const both = addSides(left, hip, ['left', 'right'])
expect(both.zones.map((z) => z.side)).toEqual(['left', 'right'])
expect(removeAllSides(both, refOf(hip)).zones).toEqual([])
})
it('removeZoneAt removes one zone by index and keeps findings (BDR-019 wart kept, D5)', () => {
const obs = {
...toggleZone(emptyObservation(), a('c7-t1')),
findings: [
{
findingZoneId: 'c7-t1',
path: ['c7-t1-dysfunctions', 'segmental', 'fixation'],
labelFrSnapshot: 'F',
labelEnSnapshot: 'F',
},
],
}
const out = removeZoneAt(obs, 0)
expect(out.zones).toEqual([])
expect(out.findings).toHaveLength(1)
})
it('detail-view zones are distinct from main-view zones with the same id', () => {
const atm = a('atm')
const obs = toggleZone(emptyObservation(), atm)
expect(obs.zones[0]).toMatchObject({ annotationId: 'atm', viewId: 'head' })
expect(decideZoneClick(atm, obs)).toEqual({ kind: 'toggle' })
})
})
describe('vertebrae (BDR-019 sync, region codes from the sheet)', () => {
it('collects vertebrae across spine zones, the priority zone first', () => {
const obs = {
...emptyObservation(),
zones: [
{
annotationId: 'thoracic',
viewId: 'main',
vertebrae: [{ region: 'T', index: 2 }],
},
{
annotationId: 'cervical',
viewId: 'main',
vertebrae: [
{ region: 'C', index: 3 },
{ region: 'C', index: 4 },
],
},
{ annotationId: 'c7-t1', viewId: 'main' },
],
}
expect(collectVertebrae(obs, sheet, 1)).toEqual([
{ region: 'C', index: 3 },
{ region: 'C', index: 4 },
{ region: 'T', index: 2 },
])
})
it('replaces per region, prunes emptied zones and spawns zones for new regions', () => {
const base = ensureZone(emptyObservation(), a('cervical')).observation
const out = syncVertebrae(
base,
[
{ region: 'L', index: 3 },
{ region: 'L', index: 4 },
{ region: 'Cd', index: 20 },
],
sheet,
'main',
)
expect(out.zones.map((z) => z.annotationId)).toEqual(['lumbar', 'caudal'])
expect(out.zones[0]!.vertebrae).toEqual([
{ region: 'L', index: 3 },
{ region: 'L', index: 4 },
])
expect(out.zones[0]!.labelFrSnapshot).toBe('Vertèbres lombaires')
const cleared = syncVertebrae(out, [], sheet, 'main')
expect(cleared.zones).toEqual([])
})
it('keeps non-spine zones untouched and ignores unknown regions', () => {
const base = toggleZone(emptyObservation(), a('c7-t1'))
const out = syncVertebrae(base, [{ region: 'XX', index: 1 }], sheet, 'main')
expect(out.zones).toEqual(base.zones)
})
})
+75 -36
View File
@@ -1,17 +1,23 @@
/**
* Replaces anatomy.horse / char.svgCatalogLink: the bundled reference sheet
* loads, validates, and indexes as the canonical document says.
* loads, validates, and indexes as the canonical document says. Since R2 the
* provider hands the raw payload over and the core parses and indexes it;
* the facts the TypeScript index no longer exposes (annotations per view,
* region by code, spine annotation of a region) are read from the document
* the core parsed.
*/
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { beforeAll, describe, expect, it } from 'vitest'
import type {
Annotation,
FindingCategory,
FindingNode,
} from '@faunosteo/core-wasm/types'
import { bundledSheetProvider } from '@/sheets/provider'
import {
buildSheetIndex,
isObservable,
pickLabel,
type SheetIndex,
} from '@/services/sheetIndex'
import { isObservable, type SheetIndex } from '@/services/sheetIndex'
import { setSheetProvider } from '@/sheets/useSheet'
import { pickLabel } from '@/i18n/pickLocaleLabel'
import { loadTestSheet } from '../helpers/sheet'
/** The seed manifest the bundle reads its asset hashes from. */
@@ -25,19 +31,49 @@ beforeAll(async () => {
sheet = await loadTestSheet()
})
/** Annotations drawn on a view, in document order. */
function annotationsOfView(viewId: string): Annotation[] {
return sheet.sheet.document.annotations.filter((a) => a.view_id === viewId)
}
/** The first spine annotation of a region on a view (what the core's rules use). */
function spineAnnotation(code: string, viewId: string) {
return sheet.sheet.document.annotations
.filter(isObservable)
.find((a) => a.view_id === viewId && a.vertebral_region_code === code)
}
/** The name of the category or node at a path, read from the zone's tree. */
function nodeName(zoneId: string, path: string[]): string | undefined {
let nodes: readonly (FindingCategory | FindingNode)[] =
sheet.findingZone(zoneId)?.categories ?? []
let node: FindingCategory | FindingNode | undefined
for (const segment of path) {
node = nodes.find((n) => n.id === segment)
if (!node) return undefined
nodes = node.children
}
return node?.name.fr
}
describe('bundled sheet provider', () => {
it('returns the equine draft with its reference, assets and migration map', async () => {
const loaded = await bundledSheetProvider.getReferenceSheet('equine')
expect(loaded).not.toBeNull()
expect(loaded!.status).toBe('draft')
expect(loaded!.speciesId).toBe('equine')
expect(loaded!.ref.documentSha256).toMatch(/^[0-9a-f]{64}$/)
expect(loaded!.ref.versionId).toBeNull()
expect(loaded!.migrationMap.sheet).toEqual(loaded!.ref)
expect(loaded!.ref.species_id).toBe('equine')
expect(loaded!.ref.document_sha256).toMatch(/^[0-9a-f]{64}$/)
expect(loaded!.ref.version_id).toBeNull()
expect((loaded!.migrationMap as { sheet: unknown }).sheet).toEqual({
sheetId: loaded!.ref.sheet_id,
versionId: loaded!.ref.version_id,
documentSha256: loaded!.ref.document_sha256,
})
expect(Object.keys(loaded!.assets)).toHaveLength(1)
expect(loaded!.assets[loaded!.document.views[0]!.svg_asset_id!]).toContain(
'<svg',
)
const document = loaded!.document as {
views: { svg_asset_id: string | null }[]
}
expect(loaded!.assets[document.views[0]!.svg_asset_id!]).toContain('<svg')
expect(await bundledSheetProvider.getReferenceSheet('canine')).toBeNull()
})
@@ -48,7 +84,8 @@ describe('bundled sheet provider', () => {
svg_asset_id: string
}[]
const horse = manifest[0]!
expect(loaded!.schemaVersion).toBe(2)
expect(loaded!.ref.schema_version).toBe(2)
expect(sheet.sheet.schemaVersion).toBe(2)
expect(Object.keys(loaded!.assetHashes)).toEqual([horse.svg_asset_id])
expect(loaded!.assetHashes[horse.svg_asset_id]).toBe(horse.sha256)
expect(horse.sha256).toMatch(/^[0-9a-f]{64}$/)
@@ -58,7 +95,7 @@ describe('bundled sheet provider', () => {
describe('sheet index', () => {
it('exposes the views, 28 annotations (27 observable), 27 finding zones and 5 regions', () => {
const { document } = sheet.sheet
expect(sheet.mainView.id).toBe('main')
expect(sheet.mainViewId).toBe('main')
expect(sheet.view('head')).toMatchObject({
kind: 'detail',
parent_view_id: 'main',
@@ -66,8 +103,8 @@ describe('sheet index', () => {
})
expect(document.annotations).toHaveLength(28)
expect(document.annotations.filter(isObservable)).toHaveLength(27)
expect(sheet.annotationsOfView('head')).toHaveLength(9)
expect(sheet.annotationsOfView('main')).toHaveLength(19)
expect(annotationsOfView('head')).toHaveLength(9)
expect(annotationsOfView('main')).toHaveLength(19)
expect(document.finding_zones).toHaveLength(27)
expect(sheet.regions().map((r) => r.code)).toEqual([
'C',
@@ -76,7 +113,7 @@ describe('sheet index', () => {
'S',
'Cd',
])
expect(sheet.region('Cd')).toMatchObject({
expect(sheet.regions().find((r) => r.code === 'Cd')).toMatchObject({
count: 18,
count_range: { min: 15, max: 21 },
})
@@ -91,8 +128,8 @@ describe('sheet index', () => {
expect(a.finding_zone_id, a.id).not.toBeNull()
expect(sheet.findingZone(a.finding_zone_id!), a.id).toBeDefined()
}
expect(sheet.spineAnnotation('C', 'main')?.id).toBe('cervical')
expect(sheet.spineAnnotation('C', 'head')).toBeUndefined()
expect(spineAnnotation('C', 'main')?.id).toBe('cervical')
expect(spineAnnotation('C', 'head')).toBeUndefined()
expect(sheet.isSpine('cervical')).toBe(true)
expect(sheet.isSpine('hip')).toBe(false)
expect(sheet.isSpine('head-trigger')).toBe(false)
@@ -101,7 +138,7 @@ describe('sheet index', () => {
it('maps spine annotations to their region codes on the main view', () => {
const codes = ['C', 'T', 'L', 'S', 'Cd']
for (const code of codes) {
const a = sheet.spineAnnotation(code, 'main')
const a = spineAnnotation(code, 'main')
expect(a, code).toBeDefined()
expect(a!.vertebral_region_code).toBe(code)
expect(sheet.isSpine(a!.id)).toBe(true)
@@ -123,27 +160,24 @@ describe('sheet index', () => {
})
it('resolves finding paths and reports absent ones', () => {
expect(
sheet.nodeAt('hip', [
'hip-dysfunctions',
'articular',
'restriction-flexion',
])?.name.fr,
).toBe('Restriction en flexion')
expect(sheet.nodeAt('hip', ['hip-dysfunctions'])?.name.fr).toBe(
const leaf = ['hip-dysfunctions', 'articular', 'restriction-flexion']
expect(sheet.hasNode('hip', leaf)).toBe(true)
expect(nodeName('hip', leaf)).toBe('Restriction en flexion')
expect(sheet.hasNode('hip', ['hip-dysfunctions'])).toBe(true)
expect(nodeName('hip', ['hip-dysfunctions'])).toBe(
'Dysfonctions ostéopathiques',
)
expect(
sheet.nodeAt('cervical', [
sheet.hasNode('cervical', [
'cervical-observations',
'stumbling-proprioceptive',
]),
).toBeUndefined()
expect(sheet.nodeAt('nowhere', ['x'])).toBeUndefined()
expect(sheet.nodeAt('hip', [])).toBeUndefined()
).toBe(false)
expect(sheet.hasNode('nowhere', ['x'])).toBe(false)
expect(sheet.hasNode('hip', [])).toBe(false)
})
it('names annotations and triggers in both locales', () => {
it('names annotations and triggers in both locales', async () => {
expect(pickLabel(sheet.name(sheet.annotation('hip')!), 'fr')).toBe(
'Hanche (coxo-fémorale)',
)
@@ -153,6 +187,11 @@ describe('sheet index', () => {
expect(pickLabel(sheet.name(sheet.annotation('head-trigger')!), 'en')).toBe(
'Head (left lateral view)',
)
expect(buildSheetIndex(sheet.sheet).mainView).toEqual(sheet.mainView)
// A second load of the same payload indexes it the same way.
setSheetProvider(bundledSheetProvider)
const again = await loadTestSheet()
expect(again).not.toBe(sheet)
expect(again.mainViewId).toBe(sheet.mainViewId)
expect(again.sheet.document).toEqual(sheet.sheet.document)
})
})
@@ -0,0 +1,178 @@
/**
* R2 plan rev 2 (robustness 7): a store action whose core call fails changes
* nothing and answers `{ ok: false }`, and the callers stop: the new-report
* page does not open the editor, the home page shows the import error instead
* of opening a report.
*/
import {
afterEach,
beforeAll,
beforeEach,
describe,
expect,
it,
vi,
} from 'vitest'
import {
cleanup,
fireEvent,
render,
screen,
waitFor,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import HomeRoute from '@/app/routes/HomeRoute'
import NewReportRoute from '@/app/routes/NewReportRoute'
import { setCoreRuntime } from '@/core/runtime'
import { readAttachment } from '@/pdf/import'
import { bundledSheetProvider } from '@/sheets/provider'
import { setSheetProvider } from '@/sheets/useSheet'
import { useReportStore } from '@/state/reportStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
import type { SheetIndex } from '@/services/sheetIndex'
import { testCoreRuntime, unavailableCoreRuntime } from '../helpers/core'
import {
emptyObservation,
loadTestSheet,
minimalReport,
} from '../helpers/sheet'
vi.mock('@/pdf/import', async (importOriginal) => ({
...(await importOriginal<typeof import('@/pdf/import')>()),
readAttachment: vi.fn(),
}))
const readMock = vi.mocked(readAttachment)
let sheet: SheetIndex
beforeAll(async () => {
sheet = await loadTestSheet()
})
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
sessionStorage.clear()
localStorage.clear()
vi.stubGlobal('alert', vi.fn())
useReportStore.setState({
report: null,
archive: null,
activeObservationIndex: 0,
})
})
afterEach(async () => {
cleanup()
vi.unstubAllGlobals()
setCoreRuntime(await testCoreRuntime())
setSheetProvider(bundledSheetProvider)
})
const draft = () => ({
date: '2026-10-10',
practitioner: { name: 'Dr. Dupont' },
animal: { speciesId: 'equine', name: 'Mistral' },
owner: { name: 'Jean Martin' },
observations: [],
conclusion: '',
recommendations: '',
})
describe('store actions on a failing core', () => {
it('change nothing and answer { ok: false }', () => {
const report = minimalReport(sheet, {
observations: [emptyObservation('a'), emptyObservation('b')],
})
useReportStore.setState({ report, activeObservationIndex: 1 })
setCoreRuntime(unavailableCoreRuntime())
const s = useReportStore.getState()
expect(s.addObservation()).toEqual({ ok: false })
expect(s.moveObservationUp(1)).toEqual({ ok: false })
expect(s.removeObservation(0)).toEqual({ ok: false })
expect(s.initReport(draft(), sheet.sheet.ref)).toEqual({ ok: false })
expect(useReportStore.getState().report).toBe(report)
expect(useReportStore.getState().activeObservationIndex).toBe(1)
})
it('answer { ok: true } on the live core', () => {
const s = useReportStore.getState()
expect(s.initReport(draft(), sheet.sheet.ref)).toEqual({ ok: true })
expect(s.addObservation()).toEqual({ ok: true })
expect(useReportStore.getState().report!.observations).toHaveLength(2)
})
})
describe('callers stop on a failed core call', () => {
async function fillNewReport() {
const user = userEvent.setup()
render(
<MemoryRouter initialEntries={['/new']}>
<Routes>
<Route path="/new" element={<NewReportRoute />} />
<Route path="/editor" element={<p data-testid="editor-route" />} />
</Routes>
</MemoryRouter>,
)
await user.type(
screen.getByLabelText(fr['form.practitioner.name']!),
'Dr. Dupont',
)
await user.type(screen.getByLabelText(fr['form.animal.name']!), 'Mistral')
await user.type(
screen.getByLabelText(fr['form.owner.name']!),
'Jean Martin',
)
const submit = screen.getByRole('button', { name: fr['new_report.submit'] })
await waitFor(() => expect(submit).toBeEnabled())
await user.click(submit)
}
it('the new-report page stays put when the core cannot load', async () => {
setCoreRuntime(unavailableCoreRuntime())
await fillNewReport()
await waitFor(() =>
expect(window.alert).toHaveBeenCalledWith(fr['sheet.core_unavailable']),
)
expect(screen.queryByTestId('editor-route')).toBeNull()
expect(useReportStore.getState().report).toBeNull()
})
it('the new-report page stays put when the creation fails', async () => {
useReportStore.setState({ initReport: () => ({ ok: false }) })
try {
await fillNewReport()
await waitFor(() =>
expect(window.alert).toHaveBeenCalledWith(fr['core.action_failed']),
)
expect(screen.queryByTestId('editor-route')).toBeNull()
} finally {
useReportStore.setState({
initReport: useReportStore.getInitialState().initReport,
})
}
})
it('the home page shows the import error when the core cannot load', async () => {
readMock.mockResolvedValue({ version: 3 })
setCoreRuntime(unavailableCoreRuntime())
setSheetProvider(bundledSheetProvider)
render(
<MemoryRouter initialEntries={['/']}>
<Routes>
<Route path="/" element={<HomeRoute />} />
<Route path="/editor" element={<p data-testid="editor-route" />} />
</Routes>
</MemoryRouter>,
)
const button = screen.getByRole('button', { name: fr['home.import.cta'] })
await waitFor(() => expect(button).toBeEnabled())
const file = new File([new Uint8Array([37, 80, 68, 70])], 'bilan.pdf', {
type: 'application/pdf',
})
fireEvent.change(document.querySelector('input[type="file"]')!, {
target: { files: [file] },
})
await screen.findByText(fr['home.import.error_core_unavailable']!)
expect(screen.queryByTestId('editor-route')).toBeNull()
expect(useReportStore.getState().report).toBeNull()
})
})
@@ -0,0 +1,198 @@
/**
* R2 plan P12 (rev 2): a draft or an archive the running build cannot read is
* set aside under a quarantine key, never dropped; only the content failures
* of the core (`invalid`, `unsupported_version`, `lone_surrogate`: L1, a text
* the core would alter) quarantine, any other failure
* leaves both keys where they were; the source key is removed only once the
* quarantine write succeeded; a draft rebased with unresolved items keeps its
* raw pre-rebase text.
*/
import {
afterEach,
beforeAll,
beforeEach,
describe,
expect,
it,
vi,
} from 'vitest'
import { useReportStore } from '@/state/reportStore'
import { ARCHIVE_KEY, DRAFT_KEY, QUARANTINE_KEYS } from '@/state/persistence'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet, minimalReport } from '../helpers/sheet'
let sheet: SheetIndex
beforeAll(async () => {
sheet = await loadTestSheet()
})
beforeEach(() => {
sessionStorage.clear()
useReportStore.setState({
report: null,
archive: null,
activeObservationIndex: 0,
})
})
afterEach(() => vi.restoreAllMocks())
const restore = () => useReportStore.getState().restoreDraft(sheet)
/** A sheet whose core answers `kind` to every draft restore. */
function sheetFailingWith(kind: string): SheetIndex {
return {
...sheet,
ops: { restoreDraft: () => ({ ok: false, kind }) },
} as unknown as SheetIndex
}
describe('an unreadable draft', () => {
it.each([
['a known version that does not parse', JSON.stringify({ version: 3 })],
['an unknown version', JSON.stringify({ version: 7 })],
['text that is not JSON', '{not json'],
])('%s is moved to its quarantine key', (_label, raw) => {
sessionStorage.setItem(DRAFT_KEY, raw)
expect(restore()).toEqual({ kind: 'quarantined' })
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBe(raw)
expect(sessionStorage.getItem(DRAFT_KEY)).toBeNull()
expect(useReportStore.getState().report).toBeNull()
})
it('with a lone surrogate (L1) is moved verbatim, the surrogate kept', () => {
const raw = JSON.stringify(minimalReport(sheet, { conclusion: 'a\ud800b' }))
expect(raw).toContain('\\ud800')
sessionStorage.setItem(DRAFT_KEY, raw)
expect(restore()).toEqual({ kind: 'quarantined' })
const kept = sessionStorage.getItem(QUARANTINE_KEYS.draft)
expect(kept).toBe(raw)
expect(JSON.parse(kept!).conclusion).toBe('a\ud800b')
expect(sessionStorage.getItem(DRAFT_KEY)).toBeNull()
expect(useReportStore.getState().report).toBeNull()
})
it('stays where it is when the quarantine write fails (storage full)', () => {
const raw = JSON.stringify({ version: 7 })
sessionStorage.setItem(DRAFT_KEY, raw)
const setItem = sessionStorage.setItem.bind(sessionStorage)
vi.spyOn(sessionStorage, 'setItem').mockImplementation((key, value) => {
if (key.startsWith('osteo:quarantine:')) {
throw new DOMException('full', 'QuotaExceededError')
}
setItem(key, value)
})
// Not announced as set aside: the editor stays put instead of leaving for Home.
expect(restore()).toEqual({ kind: 'unreadable_kept' })
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(raw)
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBeNull()
})
})
describe('a core failure while reading the draft', () => {
it.each(['core_unavailable', 'internal', 'rebase_failed'])(
'%s leaves the draft and the archive untouched',
(kind) => {
const draft = JSON.stringify(minimalReport(sheet))
sessionStorage.setItem(DRAFT_KEY, draft)
sessionStorage.setItem(ARCHIVE_KEY, '{"kept":true}')
const result = useReportStore
.getState()
.restoreDraft(sheetFailingWith(kind))
expect(result).toEqual({ kind: 'core_unavailable' })
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(draft)
expect(sessionStorage.getItem(ARCHIVE_KEY)).toBe('{"kept":true}')
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBeNull()
expect(useReportStore.getState().report).toBeNull()
},
)
})
describe('an unreadable archive beside a readable draft', () => {
it('goes to its quarantine key while the draft restores', () => {
sessionStorage.setItem(
DRAFT_KEY,
JSON.stringify(minimalReport(sheet, { conclusion: 'kept' })),
)
sessionStorage.setItem(ARCHIVE_KEY, '{not json')
expect(restore()).toMatchObject({ kind: 'restored' })
expect(useReportStore.getState().report?.conclusion).toBe('kept')
expect(useReportStore.getState().archive).toBeNull()
expect(sessionStorage.getItem(QUARANTINE_KEYS.archive)).toBe('{not json')
expect(sessionStorage.getItem(ARCHIVE_KEY)).toBeNull()
})
})
describe('a lone surrogate (L1) beside a readable draft or in the open report', () => {
it('sets the archive aside verbatim while the draft restores', () => {
sessionStorage.setItem(
DRAFT_KEY,
JSON.stringify(minimalReport(sheet, { conclusion: 'kept' })),
)
const archive = JSON.stringify({ format: 'x', note: '\udc00' })
sessionStorage.setItem(ARCHIVE_KEY, archive)
expect(restore()).toMatchObject({ kind: 'restored' })
expect(useReportStore.getState().report?.conclusion).toBe('kept')
expect(sessionStorage.getItem(QUARANTINE_KEYS.archive)).toBe(archive)
})
it('refuses a core action and leaves the report as it was', () => {
const report = minimalReport(sheet, { conclusion: 'a\ud800b' })
useReportStore.setState({ report })
expect(useReportStore.getState().addObservation()).toEqual({ ok: false })
expect(useReportStore.getState().report).toBe(report)
expect(useReportStore.getState().report?.conclusion).toBe('a\ud800b')
})
it('leaves normal text with pairs and literal backslashes unchanged', () => {
const text = 'é 😀 \\ud800 \ufffd'
sessionStorage.setItem(
DRAFT_KEY,
JSON.stringify(minimalReport(sheet, { conclusion: text })),
)
expect(restore()).toMatchObject({ kind: 'restored' })
expect(useReportStore.getState().report?.conclusion).toBe(text)
expect(useReportStore.getState().addObservation()).toEqual({ ok: true })
expect(useReportStore.getState().report?.conclusion).toBe(text)
})
})
describe('a draft rebased onto the loaded sheet', () => {
const OTHER_SHA = 'c'.repeat(64)
it('keeps its raw text when the rebase flagged items', () => {
const stale = minimalReport(sheet, {
sheet: { ...sheet.sheet.ref, documentSha256: OTHER_SHA },
observations: [
{
id: 'o',
zones: [{ annotationId: 'point-gone', viewId: 'main' }],
findings: [],
freeTextFindings: [],
comment: '',
},
],
})
const raw = JSON.stringify(stale)
sessionStorage.setItem(DRAFT_KEY, raw)
expect(restore()).toMatchObject({
kind: 'restored',
rebase: { rebased: true, unresolvedZones: 1 },
})
expect(sessionStorage.getItem(QUARANTINE_KEYS.draftPreRebase)).toBe(raw)
// The mirror now holds the rebased draft.
expect(
JSON.parse(sessionStorage.getItem(DRAFT_KEY)!).sheet.documentSha256,
).toBe(sheet.sheet.ref.documentSha256)
})
it('keeps nothing aside when the rebase resolved everything', () => {
const moved = minimalReport(sheet, {
sheet: { ...sheet.sheet.ref, documentSha256: OTHER_SHA },
})
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(moved))
expect(restore()).toMatchObject({
kind: 'restored',
rebase: { rebased: true, unresolvedZones: 0, unresolvedFindings: 0 },
})
expect(sessionStorage.getItem(QUARANTINE_KEYS.draftPreRebase)).toBeNull()
})
})
+37 -34
View File
@@ -13,19 +13,16 @@ import {
it,
vi,
} from 'vitest'
import type { Annotation } from '@faunosteo/domain'
import {
createReportStore,
useReportStore,
emptyObservation,
} from '@/state/reportStore'
import {
ARCHIVE_KEY,
DRAFT_KEY,
sessionStoragePersistence,
} from '@/state/persistence'
import type { Annotation } from '@faunosteo/core-wasm/types'
import { createReportStore, useReportStore } from '@/state/reportStore'
import { ARCHIVE_KEY, DRAFT_KEY, QUARANTINE_KEYS } from '@/state/persistence'
import type { SheetIndex } from '@/services/sheetIndex'
import { archiveEnvelope, loadTestSheet, minimalReport } from '../helpers/sheet'
import {
archiveEnvelope,
emptyObservation,
loadTestSheet,
minimalReport,
} from '../helpers/sheet'
import fullV2 from '../fixtures/report-v2.full.json'
let sheet: SheetIndex
@@ -150,11 +147,21 @@ describe('sessionStorage mirror and restore', () => {
expect(JSON.parse(sessionStorage.getItem(DRAFT_KEY)!).version).toBe(3)
})
it('ignores an unreadable draft and does not replace an open report', () => {
it('sets an unreadable draft aside instead of restoring it, and does not replace an open report', () => {
// R2: an unreadable draft is quarantined (P12), no longer dropped.
sessionStorage.setItem(DRAFT_KEY, '{not json')
expect(sessionStoragePersistence.load(sheet.sheet.migrationMap)).toBeNull()
expect(useReportStore.getState().restoreDraft(sheet)).toEqual({
kind: 'quarantined',
})
expect(useReportStore.getState().report).toBeNull()
sessionStorage.setItem(DRAFT_KEY, JSON.stringify({ version: 1 }))
expect(sessionStoragePersistence.load(sheet.sheet.migrationMap)).toBeNull()
expect(useReportStore.getState().restoreDraft(sheet)).toEqual({
kind: 'quarantined',
})
expect(useReportStore.getState().report).toBeNull()
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBe(
JSON.stringify({ version: 1 }),
)
useReportStore.getState().initReport(draft(), sheet.sheet.ref)
const before = useReportStore.getState().report
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(minimalReport(sheet)))
@@ -165,8 +172,8 @@ describe('sessionStorage mirror and restore', () => {
it('createReportStore accepts another persistence adapter', () => {
const saved: unknown[] = []
const store = createReportStore(
{ load: () => null, save: (r) => saved.push(r) },
{ load: () => null, save: () => undefined },
{ loadText: () => null, save: (r) => saved.push(r) },
{ loadText: () => null, save: () => undefined },
)
store.getState().initReport(draft(), sheet.sheet.ref)
expect(saved.at(-1)).toMatchObject({ version: 3 })
@@ -174,15 +181,6 @@ describe('sessionStorage mirror and restore', () => {
})
describe('store edge cases', () => {
it('hydrateReport stores the given object as is, without revalidating', () => {
const odd = { ...minimalReport(sheet), extra: 1 }
useReportStore.getState().hydrateReport(odd)
expect(useReportStore.getState().report).toBe(odd)
expect(
(useReportStore.getState().report as unknown as { extra: number }).extra,
).toBe(1)
})
it('identity setters are no-ops without a report', () => {
const s = useReportStore.getState()
s.setPractitioner({ name: 'X' })
@@ -213,8 +211,8 @@ describe('archive of an imported Step 6 PDF', () => {
it('the archive is written at the session edges only, never on an edit', () => {
const archiveSaves: unknown[] = []
const store = createReportStore(
{ load: () => null, save: () => undefined },
{ load: () => null, save: (a) => archiveSaves.push(a) },
{ loadText: () => null, save: () => undefined },
{ loadText: () => null, save: (a) => archiveSaves.push(a) },
)
const report = minimalReport(sheet)
const archive = archiveEnvelope(sheet, report)
@@ -239,7 +237,10 @@ describe('archive of an imported Step 6 PDF', () => {
expect(sessionStorage.getItem(ARCHIVE_KEY)).not.toBeNull()
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(report))
const outcome = useReportStore.getState().restoreDraft(sheet)
expect(outcome).toMatchObject({ rebased: false })
expect(outcome).toMatchObject({
kind: 'restored',
rebase: { rebased: false },
})
expect(useReportStore.getState().report?.conclusion).toBe('kept')
expect(useReportStore.getState().archive).toEqual(archive)
})
@@ -250,8 +251,11 @@ describe('archive of an imported Step 6 PDF', () => {
() => useReportStore.getState().initReport(draft(), sheet.sheet.ref),
],
[
'hydrateReport',
() => useReportStore.getState().hydrateReport(minimalReport(sheet)),
'hydrateImport without an archive',
() =>
useReportStore
.getState()
.hydrateImport({ report: minimalReport(sheet), archive: null }),
],
['reset', () => useReportStore.getState().reset()],
])('%s clears the archive and removes its mirror', (_name, act) => {
@@ -292,9 +296,8 @@ describe('archive of an imported Step 6 PDF', () => {
const outcome = useReportStore.getState().restoreDraft(sheet)
expect(outcome).toMatchObject({
rebased: true,
unresolvedZones: 1,
unresolvedFindings: 0,
kind: 'restored',
rebase: { rebased: true, unresolvedZones: 1, unresolvedFindings: 0 },
})
const restored = useReportStore.getState().report!
expect(restored.sheet).toEqual(sheet.sheet.ref)
+2
View File
@@ -14,6 +14,8 @@ export default defineConfig({
environment: 'happy-dom',
globals: true,
setupFiles: ['tests/setup.ts'],
// Refuses to run on a missing or stale core module (pnpm wasm:build).
globalSetup: ['../../packages/core-wasm/tests/global-setup.ts'],
include: ['tests/**/*.test.ts', 'tests/**/*.test.tsx'],
coverage: {
provider: 'v8',
+1
View File
@@ -18,6 +18,7 @@ ts = ["dep:ts-rs"]
[dependencies]
serde.workspace = true
serde_json.workspace = true
url.workspace = true
ts-rs = { workspace = true, optional = true }
[lints]
+136
View File
@@ -0,0 +1,136 @@
//! The visual identity an archive embeds (`archive/branding.ts`, STEP6 §3.4, caps §15).
use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize};
#[cfg(feature = "ts")]
use ts_rs::TS;
use crate::domain::js::{self, literal};
const KIB: usize = 1024;
literal!(KindPng, "png");
literal!(KindSvg, "svg");
/// `http(s)://` then printable ASCII without `"`, `'`, `(`, `)`, `<`, `>` or `\`: the URL is
/// written into PDF link actions. Also at most 2048 characters and a valid URL.
fn is_branding_url(text: &str) -> bool {
let rest = text
.strip_prefix("https://")
.or_else(|| text.strip_prefix("http://"));
let Some(rest) = rest else { return false };
js::utf16_len(text) <= 2048
&& !rest.is_empty()
&& rest
.bytes()
.all(|b| (0x21..=0x7e).contains(&b) && !b"\"'()<>\\".contains(&b))
&& js::is_url(text)
}
fn branding_url<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
let text = String::deserialize(d)?;
if is_branding_url(&text) {
Ok(text)
} else {
Err(D::Error::custom("http(s) URL expected"))
}
}
fn capped<'de, D: Deserializer<'de>>(d: D, max: usize) -> Result<String, D::Error> {
let text = String::deserialize(d)?;
if js::utf16_len(&text) <= max {
Ok(text)
} else {
Err(D::Error::custom("string over its cap"))
}
}
fn png_base64<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
let text = capped(d, 512 * KIB)?;
if js::is_base64(&text) {
Ok(text)
} else {
Err(D::Error::custom("invalid base64"))
}
}
fn svg_text<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
capped(d, 256 * KIB)
}
fn fallback_text<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
capped(d, 128)
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct PngAsset {
pub kind: KindPng,
#[serde(deserialize_with = "png_base64")]
pub base64: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct SvgAsset {
pub kind: KindSvg,
#[serde(deserialize_with = "svg_text")]
pub svg: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(untagged)]
pub enum ImageAsset {
Png(PngAsset),
Svg(SvgAsset),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct Credit {
#[serde(deserialize_with = "js::nullable")]
pub logo: Option<ImageAsset>,
#[serde(deserialize_with = "branding_url")]
pub url: String,
#[serde(deserialize_with = "fallback_text")]
pub fallback_text: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct Branding {
#[serde(deserialize_with = "branding_url")]
pub site_url: String,
#[serde(deserialize_with = "js::nullable")]
pub header_logo: Option<ImageAsset>,
#[serde(deserialize_with = "js::nullable")]
pub footer_logo: Option<ImageAsset>,
#[serde(deserialize_with = "js::nullable")]
pub powered_by: Option<Credit>,
#[serde(deserialize_with = "js::nullable")]
pub partner: Option<Credit>,
}
#[cfg(test)]
mod tests {
use super::is_branding_url;
#[test]
fn branding_urls_follow_the_zod_pattern() {
assert!(is_branding_url("https://faunosteo.com"));
assert!(is_branding_url("http://a.b/c?d=e#f"));
assert!(!is_branding_url("https://a.b/(x)"));
assert!(!is_branding_url("ftp://a.b"));
assert!(!is_branding_url("https://"));
assert!(!is_branding_url("https://a b"));
assert!(!is_branding_url(&format!(
"https://a.b/{}",
"x".repeat(2048)
)));
}
}
@@ -0,0 +1,56 @@
//! The attachment of a Step 6 PDF (`archive/envelope.ts`, STEP6 §2.3): the report wrapped
//! with the sheet snapshot, the branding and the labels it was printed with. Metadata is not
//! strict: an additive v1 field never breaks an older reader.
use serde::{Deserialize, Serialize};
#[cfg(feature = "ts")]
use ts_rs::TS;
use super::branding::Branding;
use super::labels::PdfLabelSet;
use super::snapshot::SheetSnapshot;
use crate::domain::js::{literal, number_literal};
use crate::domain::report::Report;
literal!(EnvelopeFormat, "faunosteo-report-archive");
number_literal!(EnvelopeVersion1, 1);
pub const ENVELOPE_VERSION: u32 = 1;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "lowercase")]
pub enum Locale {
Fr,
En,
}
/// `EnvelopeMetadataSchema.extend({branding, labels})`: what the layered reader checks
/// before the snapshot gate.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EnvelopeWrapper {
pub format: EnvelopeFormat,
pub envelope_version: EnvelopeVersion1,
pub exported_at: String,
pub locale: Locale,
pub branding: Branding,
pub labels: PdfLabelSet,
}
/// An archive envelope, in the order the engine writes it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "camelCase")]
pub struct ReportArchiveEnvelope {
pub format: EnvelopeFormat,
pub envelope_version: EnvelopeVersion1,
/// ISO timestamp of the export.
pub exported_at: String,
pub locale: Locale,
/// As exported, never rebased.
pub report: Report,
pub sheet_snapshot: SheetSnapshot,
pub branding: Branding,
pub labels: PdfLabelSet,
}
+116
View File
@@ -0,0 +1,116 @@
//! The static strings the PDF engine prints, in both locales, frozen into the archive
//! (`archive/labels.ts`): exactly 25 keys, strict, each at most 256 UTF-16 units.
use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize};
#[cfg(feature = "ts")]
use ts_rs::TS;
use crate::domain::js;
/// The 25 keys, in the order of `PDF_LABEL_KEYS`.
pub const PDF_LABEL_KEYS: [&str; 25] = [
"pdf.empty",
"pdf.eyebrow.observation",
"pdf.eyebrow.synthesis",
"pdf.owner_prefix",
"pdf.section.comment",
"pdf.section.conclusion",
"pdf.section.findings_prefix",
"pdf.section.free_findings",
"pdf.section.next_appointment",
"pdf.section.recommendations",
"pdf.section.severity",
"pdf.section.zones",
"pdf.siret_prefix",
"pdf.subject",
"pdf.title.conclusion",
"pdf.title.suffix.bilan",
"pdf.view.detail_prefix",
"pdf.view.general",
"severity.mild",
"severity.moderate",
"severity.severe",
"lateral.left",
"lateral.right",
"footer.powered_by",
"footer.in_partnership",
];
const LABEL_MAX: usize = 256;
fn label<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
let text = String::deserialize(d)?;
if js::utf16_len(&text) <= LABEL_MAX {
Ok(text)
} else {
Err(D::Error::custom("label over 256 characters"))
}
}
/// Fields in the order of the engine dictionaries (`packages/pdf/src/i18n`), which is the
/// order every shipped attachment carries.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct PdfLabels {
#[serde(rename = "pdf.eyebrow.observation", deserialize_with = "label")]
pub pdf_eyebrow_observation: String,
#[serde(rename = "pdf.eyebrow.synthesis", deserialize_with = "label")]
pub pdf_eyebrow_synthesis: String,
#[serde(rename = "pdf.title.conclusion", deserialize_with = "label")]
pub pdf_title_conclusion: String,
#[serde(rename = "pdf.section.zones", deserialize_with = "label")]
pub pdf_section_zones: String,
#[serde(rename = "pdf.section.findings_prefix", deserialize_with = "label")]
pub pdf_section_findings_prefix: String,
#[serde(rename = "pdf.section.free_findings", deserialize_with = "label")]
pub pdf_section_free_findings: String,
#[serde(rename = "pdf.section.severity", deserialize_with = "label")]
pub pdf_section_severity: String,
#[serde(rename = "pdf.section.comment", deserialize_with = "label")]
pub pdf_section_comment: String,
#[serde(rename = "pdf.section.conclusion", deserialize_with = "label")]
pub pdf_section_conclusion: String,
#[serde(rename = "pdf.section.recommendations", deserialize_with = "label")]
pub pdf_section_recommendations: String,
#[serde(rename = "pdf.section.next_appointment", deserialize_with = "label")]
pub pdf_section_next_appointment: String,
#[serde(rename = "pdf.view.general", deserialize_with = "label")]
pub pdf_view_general: String,
#[serde(rename = "pdf.view.detail_prefix", deserialize_with = "label")]
pub pdf_view_detail_prefix: String,
#[serde(rename = "pdf.empty", deserialize_with = "label")]
pub pdf_empty: String,
#[serde(rename = "pdf.owner_prefix", deserialize_with = "label")]
pub pdf_owner_prefix: String,
#[serde(rename = "pdf.siret_prefix", deserialize_with = "label")]
pub pdf_siret_prefix: String,
#[serde(rename = "pdf.title.suffix.bilan", deserialize_with = "label")]
pub pdf_title_suffix_bilan: String,
#[serde(rename = "pdf.subject", deserialize_with = "label")]
pub pdf_subject: String,
#[serde(rename = "severity.mild", deserialize_with = "label")]
pub severity_mild: String,
#[serde(rename = "severity.moderate", deserialize_with = "label")]
pub severity_moderate: String,
#[serde(rename = "severity.severe", deserialize_with = "label")]
pub severity_severe: String,
#[serde(rename = "lateral.left", deserialize_with = "label")]
pub lateral_left: String,
#[serde(rename = "lateral.right", deserialize_with = "label")]
pub lateral_right: String,
#[serde(rename = "footer.powered_by", deserialize_with = "label")]
pub footer_powered_by: String,
#[serde(rename = "footer.in_partnership", deserialize_with = "label")]
pub footer_in_partnership: String,
}
/// Strict: every key present in both locales, no extra key.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct PdfLabelSet {
pub fr: PdfLabels,
pub en: PdfLabels,
}
+15
View File
@@ -0,0 +1,15 @@
//! Archive contracts: the sheet snapshot, the branding, the PDF labels and the envelope.
pub mod branding;
pub mod envelope;
pub mod labels;
pub mod read;
pub mod snapshot;
pub mod snapshot_rules;
pub use branding::*;
pub use envelope::*;
pub use labels::*;
pub use read::{ArchiveOrigin, ArchiveReadOutcome, parse_envelope, read_archive_document};
pub use snapshot::*;
pub use snapshot_rules::{SnapshotRejection, assert_snapshot, build_sheet_snapshot};
+125
View File
@@ -0,0 +1,125 @@
//! Layered reading of a PDF attachment (`archive/envelope.ts`, STEP6 §4, §14 "Read").
//!
//! The report is located and parsed first so it is never lost because of its wrapper; the
//! wrapper is then validated whole or dropped with a reason. Accepted shapes: a bare Report v2
//! or v3, or an archive envelope of version 1.
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[cfg(feature = "ts")]
use ts_rs::TS;
use super::envelope::{ENVELOPE_VERSION, EnvelopeVersion1, EnvelopeWrapper, ReportArchiveEnvelope};
use super::snapshot::SheetSnapshot;
use super::snapshot_rules::{SnapshotRejection, assert_snapshot};
use crate::domain::report::read::{ReadFailure, read_report_document, version_of};
use crate::domain::report::{Report, ReportMigrationMap};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "snake_case")]
pub enum ArchiveOrigin {
EnvelopeV1,
BareV3,
V2,
}
/// What an attachment gave back: always the report, the envelope when accepted.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "camelCase")]
pub struct ArchiveReadOutcome {
pub report: Report,
pub origin: ArchiveOrigin,
pub migrated: bool,
/// From the v2 migration; 0 for a v3 report.
pub unresolved_zones: u32,
pub unresolved_findings: u32,
/// The validated envelope, when accepted.
pub archive: Option<ReportArchiveEnvelope>,
/// Envelope present but dropped, with the reason.
#[serde(skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "ts", ts(optional))]
pub snapshot_rejected: Option<SnapshotRejection>,
}
/// An envelope of any version is recognised by a numeric `envelopeVersion`.
fn envelope_version_of(data: &Value) -> Option<f64> {
data.as_object()?.get("envelopeVersion")?.as_f64()
}
/// Reads the JSON of a PDF attachment of any supported shape. Fails only when the report
/// itself cannot be read (unknown version, corrupt document).
pub fn read_archive_document(
data: &Value,
map: &ReportMigrationMap,
) -> Result<ArchiveReadOutcome, ReadFailure> {
let envelope_version = envelope_version_of(data);
let report_data = match envelope_version {
Some(_) => data.get("report").unwrap_or(&Value::Null),
None => data,
};
let outcome = read_report_document(report_data, map)?;
let migrated = version_of(report_data) != Some(3.0);
let mut read = ArchiveReadOutcome {
report: outcome.report,
origin: if migrated {
ArchiveOrigin::V2
} else {
ArchiveOrigin::BareV3
},
migrated,
unresolved_zones: outcome.unresolved_zones,
unresolved_findings: outcome.unresolved_findings,
archive: None,
snapshot_rejected: None,
};
let Some(version) = envelope_version else {
return Ok(read);
};
if version != f64::from(ENVELOPE_VERSION) {
// The origin stays the report's: the envelope of an unknown version is not read.
read.snapshot_rejected = Some(SnapshotRejection::UnsupportedEnvelope);
return Ok(read);
}
read.origin = ArchiveOrigin::EnvelopeV1;
match read_envelope_v1(data, &read.report) {
Ok(archive) => read.archive = Some(archive),
Err(reason) => read.snapshot_rejected = Some(reason),
}
Ok(read)
}
/// A v1 envelope: wrapper schema → snapshot gate → sheet invariant.
fn read_envelope_v1(
data: &Value,
report: &Report,
) -> Result<ReportArchiveEnvelope, SnapshotRejection> {
// Deserialised by reference: an attachment can be megabytes, never copy the whole value.
let wrapper = EnvelopeWrapper::deserialize(data).map_err(|_| SnapshotRejection::Schema)?;
let snapshot = assert_snapshot(data.get("sheetSnapshot").unwrap_or(&Value::Null))?;
if !snapshot_matches(&snapshot, report) {
return Err(SnapshotRejection::SheetMismatch);
}
Ok(ReportArchiveEnvelope {
format: wrapper.format,
envelope_version: EnvelopeVersion1,
exported_at: wrapper.exported_at,
locale: wrapper.locale,
report: report.clone(),
sheet_snapshot: snapshot,
branding: wrapper.branding,
labels: wrapper.labels,
})
}
fn snapshot_matches(snapshot: &SheetSnapshot, report: &Report) -> bool {
snapshot.reference.sheet_id == report.sheet.sheet_id
&& snapshot.reference.document_sha256 == report.sheet.document_sha256
}
/// `ReportArchiveEnvelopeSchema.parse`: the shape of a whole envelope (the snapshot's shape
/// only, no caps nor integrity), as the session keeps it.
pub fn parse_envelope(data: &Value) -> Result<ReportArchiveEnvelope, serde_json::Error> {
ReportArchiveEnvelope::deserialize(data)
}
+115
View File
@@ -0,0 +1,115 @@
//! The sheet a report archive carries (`archive/snapshot.ts`, STEP6 §2.2): a valid, lean
//! sheet document plus the SVG text of every asset a view reaches. This file holds the shape;
//! the build and the import gate are in `snapshot_rules.rs`.
use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize};
#[cfg(feature = "ts")]
use ts_rs::TS;
use crate::domain::js::{self, JsInt};
use crate::domain::report::v3::sha256;
use crate::domain::sheet::AnatomicalSheetDocument;
use crate::domain::sheet::schema::check;
const MIB: usize = 1024 * 1024;
/// Hard limits on an imported snapshot; every excess is a `caps` rejection.
pub struct SnapshotCaps;
impl SnapshotCaps {
pub const VIEWS: usize = 64;
pub const ANNOTATIONS: usize = 1024;
pub const FINDING_NODES: usize = 8192;
pub const FINDING_DEPTH: usize = 8;
pub const LABEL_CHARS: usize = 512;
pub const ASSETS: usize = 4;
pub const ASSET_BYTES: usize = 2 * MIB;
pub const ASSETS_TOTAL_BYTES: usize = 6 * MIB;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "lowercase")]
pub enum SheetStatus {
Draft,
Published,
}
/// `SheetRefSchema.extend({schemaVersion, speciesId}).strict()`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct SheetSnapshotRef {
#[serde(deserialize_with = "check::non_empty")]
pub sheet_id: String,
#[serde(deserialize_with = "check::nullable_non_empty")]
pub version_id: Option<String>,
#[serde(deserialize_with = "sha256")]
pub document_sha256: String,
#[serde(deserialize_with = "check::positive_int")]
#[cfg_attr(feature = "ts", ts(type = "number"))]
pub schema_version: JsInt,
#[serde(deserialize_with = "check::non_empty")]
pub species_id: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct SheetSnapshotAsset {
#[serde(deserialize_with = "uuid")]
pub svg_asset_id: String,
/// Content address from the seed manifest; a provenance pointer, not a tamper check.
#[serde(deserialize_with = "nullable_sha256")]
pub sha256: Option<String>,
#[serde(deserialize_with = "asset_svg")]
pub svg: String,
}
fn uuid<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
let text = String::deserialize(d)?;
if js::is_uuid(&text) {
Ok(text)
} else {
Err(D::Error::custom("invalid uuid"))
}
}
fn nullable_sha256<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
match Option::<String>::deserialize(d)? {
Some(text) if !js::is_sha256_hex(&text) => Err(D::Error::custom("invalid sha256")),
other => Ok(other),
}
}
fn asset_svg<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
let text = String::deserialize(d)?;
if js::utf16_len(&text) <= SnapshotCaps::ASSET_BYTES {
Ok(text)
} else {
Err(D::Error::custom("asset over cap"))
}
}
fn capped_assets<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<SheetSnapshotAsset>, D::Error> {
let assets = Vec::<SheetSnapshotAsset>::deserialize(d)?;
if assets.len() <= SnapshotCaps::ASSETS {
Ok(assets)
} else {
Err(D::Error::custom("too many assets"))
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct SheetSnapshot {
pub status: SheetStatus,
#[serde(rename = "ref")]
pub reference: SheetSnapshotRef,
/// Lean, valid document (schema v2, strict).
pub document: AnatomicalSheetDocument,
#[serde(deserialize_with = "capped_assets")]
pub assets: Vec<SheetSnapshotAsset>,
}
@@ -0,0 +1,330 @@
//! Building and gating the sheet snapshot of an archive (`archive/snapshot.ts`).
//!
//! The snapshot is a valid, lean sheet document (every view, annotation, category and region;
//! finding trees pruned to the paths the report uses; bibliography emptied) plus the SVG text
//! of every asset a view reaches. `assert_snapshot` is the single gate an imported snapshot
//! passes, in this order: finding depth on the raw input, shape, caps, integrity.
use std::collections::{HashMap, HashSet};
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[cfg(feature = "ts")]
use ts_rs::TS;
use super::snapshot::{SheetSnapshot, SheetSnapshotAsset, SheetSnapshotRef, SnapshotCaps};
use crate::domain::js;
use crate::domain::report::Report;
use crate::domain::sheet::validate::{SheetIssueSeverity, validate_sheet_document};
use crate::domain::sheet::{
AnatomicalSheetDocument, Annotation, FindingCategory, FindingNode, FindingZone, LoadedSheet,
LocalizedOptionalText, SheetView,
};
/// Why an imported snapshot (or its envelope) is dropped; the import reports it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "snake_case")]
pub enum SnapshotRejection {
UnsupportedEnvelope,
Schema,
Caps,
Integrity,
SheetMismatch,
}
// ---------------------------------------------------------------------------
// Build
/// The snapshot of `sheet` that `report` needs: pure, deterministic (document order
/// everywhere). A missing asset is left out and caught by `assert_snapshot`.
pub fn build_sheet_snapshot(sheet: &LoadedSheet, report: &Report) -> SheetSnapshot {
SheetSnapshot {
status: sheet.status,
reference: SheetSnapshotRef {
sheet_id: sheet.reference.sheet_id.clone(),
version_id: sheet.reference.version_id.clone(),
document_sha256: sheet.reference.document_sha256.clone(),
schema_version: sheet.schema_version,
species_id: sheet.species_id.clone(),
},
document: lean_document(&sheet.document, report),
assets: snapshot_assets(sheet),
}
}
/// Finding paths of the report grouped by zone, resolved and unresolved alike.
fn paths_by_zone(report: &Report) -> HashMap<&str, Vec<&[String]>> {
let mut by_zone: HashMap<&str, Vec<&[String]>> = HashMap::new();
for finding in report.observations.iter().flat_map(|o| &o.findings) {
by_zone
.entry(finding.finding_zone_id.as_str())
.or_default()
.push(&finding.path);
}
by_zone
}
/// Paths whose segment at `depth` is `id`.
fn under<'a>(paths: &[&'a [String]], depth: usize, id: &str) -> Vec<&'a [String]> {
paths
.iter()
.filter(|p| p.get(depth).is_some_and(|segment| segment == id))
.copied()
.collect()
}
/// Keeps, in document order, the nodes at `depth` of some path and their used descendants.
fn prune_nodes(nodes: &[FindingNode], paths: &[&[String]], depth: usize) -> Vec<FindingNode> {
nodes
.iter()
.filter_map(|node| {
let kept = under(paths, depth, &node.id);
(!kept.is_empty()).then(|| FindingNode {
id: node.id.clone(),
name: node.name.clone(),
description: LocalizedOptionalText::default(),
requires_vet_referral: node.requires_vet_referral,
reference_ids: Vec::new(),
review_status: node.review_status,
children: prune_nodes(&node.children, &kept, depth + 1),
})
})
.collect()
}
fn prune_categories(categories: &[FindingCategory], paths: &[&[String]]) -> Vec<FindingCategory> {
categories
.iter()
.filter_map(|category| {
let kept = under(paths, 0, &category.id);
(!kept.is_empty()).then(|| FindingCategory {
id: category.id.clone(),
kind: category.kind,
name: category.name.clone(),
description: LocalizedOptionalText::default(),
reference_ids: Vec::new(),
review_status: category.review_status,
children: prune_nodes(&category.children, &kept, 1),
})
})
.collect()
}
fn lean_document(document: &AnatomicalSheetDocument, report: &Report) -> AnatomicalSheetDocument {
let used = paths_by_zone(report);
let prune_zone = |zone: &FindingZone| FindingZone {
id: zone.id.clone(),
name: zone.name.clone(),
categories: prune_categories(
&zone.categories,
used.get(zone.id.as_str()).map_or(&[], Vec::as_slice),
),
};
AnatomicalSheetDocument {
schema_version: document.schema_version,
species_id: document.species_id.clone(),
name: document.name.clone(),
description: document.description.clone(),
scope_disclaimer: document.scope_disclaimer.clone(),
attribution: document.attribution.clone(),
vertebral_config: document.vertebral_config.clone(),
references: Vec::new(),
categories: document.categories.clone(),
views: document.views.clone(),
annotations: document.annotations.clone(),
finding_zones: document.finding_zones.iter().map(prune_zone).collect(),
}
}
/// Views by id, last entry wins (`new Map(views.map(v => [v.id, v]))`).
fn views_by_id(views: &[SheetView]) -> HashMap<&str, &SheetView> {
views.iter().map(|v| (v.id(), v)).collect()
}
/// The asset a view draws: its own, else the first one up its parent chain.
fn asset_of_view<'a>(view: &'a SheetView, views: &HashMap<&str, &'a SheetView>) -> Option<&'a str> {
let mut visited = HashSet::new();
let mut current = Some(view);
while let Some(v) = current {
if !visited.insert(v.id()) {
return None;
}
if let Some(asset) = v.svg_asset_id() {
return Some(asset);
}
current = v
.parent_view_id()
.and_then(|parent| views.get(parent).copied());
}
None
}
/// Asset ids reachable from the views, in view order, each once.
fn reachable_asset_ids(document: &AnatomicalSheetDocument) -> Vec<&str> {
let views = views_by_id(&document.views);
let mut ids: Vec<&str> = Vec::new();
for view in &document.views {
if let Some(id) = asset_of_view(view, &views)
&& !ids.contains(&id)
{
ids.push(id);
}
}
ids
}
fn snapshot_assets(sheet: &LoadedSheet) -> Vec<SheetSnapshotAsset> {
reachable_asset_ids(&sheet.document)
.into_iter()
.filter_map(|id| {
let svg = sheet.assets.get(id)?;
Some(SheetSnapshotAsset {
svg_asset_id: id.to_owned(),
sha256: sheet.asset_hashes.get(id).cloned(),
svg: svg.clone(),
})
})
.collect()
}
// ---------------------------------------------------------------------------
// Assert
/// The single gate of an imported snapshot: depth on the raw input, then shape (`schema`),
/// caps, integrity rules and every view reaching a carried asset (`integrity`).
pub fn assert_snapshot(input: &Value) -> Result<SheetSnapshot, SnapshotRejection> {
assert_finding_depth(input)?;
let snapshot = SheetSnapshot::deserialize(input).map_err(|_| SnapshotRejection::Schema)?;
assert_caps(&snapshot)?;
assert_integrity(&snapshot)?;
Ok(snapshot)
}
/// Depth of the finding trees on the raw input, before the shape parse recurses into it.
/// Iterative: an explicit stack of (node, depth) pairs, categories at depth 1.
fn assert_finding_depth(input: &Value) -> Result<(), SnapshotRejection> {
let zones = input
.as_object()
.and_then(|o| o.get("document"))
.and_then(Value::as_object)
.and_then(|d| d.get("finding_zones"))
.and_then(Value::as_array);
let Some(zones) = zones else { return Ok(()) };
let mut stack: Vec<(&Value, usize)> = zones
.iter()
.filter_map(|zone| zone.as_object()?.get("categories")?.as_array())
.flatten()
.map(|category| (category, 1))
.collect();
while let Some((node, depth)) = stack.pop() {
if depth > SnapshotCaps::FINDING_DEPTH {
return Err(SnapshotRejection::Caps);
}
let children = node
.as_object()
.and_then(|n| n.get("children"))
.and_then(Value::as_array);
stack.extend(children.into_iter().flatten().map(|c| (c, depth + 1)));
}
Ok(())
}
fn count_finding_nodes(document: &AnatomicalSheetDocument) -> usize {
fn nodes(list: &[FindingNode]) -> usize {
list.iter().map(|n| 1 + nodes(&n.children)).sum()
}
document
.finding_zones
.iter()
.flat_map(|z| &z.categories)
.map(|c| 1 + nodes(&c.children))
.sum()
}
/// Longest `name` label (`fr` or `en`, UTF-16 units) anywhere in the document.
fn longest_name(document: &AnatomicalSheetDocument) -> usize {
fn node_names(list: &[FindingNode], longest: &mut usize) {
for node in list {
*longest = (*longest).max(label_len(&node.name));
node_names(&node.children, longest);
}
}
let mut longest = label_len(&document.name);
let mut take = |len: usize| longest = longest.max(len);
document
.views
.iter()
.for_each(|v| take(label_len(v.name())));
document
.categories
.iter()
.for_each(|c| take(label_len(&c.name)));
document
.vertebral_config
.regions
.iter()
.for_each(|r| take(label_len(&r.name)));
for annotation in &document.annotations {
match annotation {
Annotation::Observable(a) => take(label_len(&a.name)),
Annotation::DetailTrigger(t) => take(t.name.as_ref().map_or(0, label_len)),
}
}
for zone in &document.finding_zones {
take(label_len(&zone.name));
for category in &zone.categories {
take(label_len(&category.name));
let mut deep = 0;
node_names(&category.children, &mut deep);
take(deep);
}
}
longest
}
fn label_len(text: &crate::domain::sheet::LocalizedText) -> usize {
js::utf16_len(&text.fr).max(js::utf16_len(&text.en))
}
fn assert_caps(snapshot: &SheetSnapshot) -> Result<(), SnapshotRejection> {
let document = &snapshot.document;
let sizes: Vec<usize> = snapshot.assets.iter().map(|a| a.svg.len()).collect();
let over = document.views.len() > SnapshotCaps::VIEWS
|| document.annotations.len() > SnapshotCaps::ANNOTATIONS
|| count_finding_nodes(document) > SnapshotCaps::FINDING_NODES
|| longest_name(document) > SnapshotCaps::LABEL_CHARS
|| snapshot.assets.len() > SnapshotCaps::ASSETS
|| sizes.iter().any(|&size| size > SnapshotCaps::ASSET_BYTES)
|| sizes.iter().sum::<usize>() > SnapshotCaps::ASSETS_TOTAL_BYTES;
if over {
Err(SnapshotRejection::Caps)
} else {
Ok(())
}
}
fn assert_integrity(snapshot: &SheetSnapshot) -> Result<(), SnapshotRejection> {
let has_error = validate_sheet_document(&snapshot.document)
.iter()
.any(|issue| issue.severity == SheetIssueSeverity::Error);
if has_error {
return Err(SnapshotRejection::Integrity);
}
let present: HashSet<&str> = snapshot
.assets
.iter()
.map(|a| a.svg_asset_id.as_str())
.collect();
let views = views_by_id(&snapshot.document.views);
let every_view_drawn = snapshot
.document
.views
.iter()
.all(|view| asset_of_view(view, &views).is_some_and(|id| present.contains(id)));
if every_view_drawn {
Ok(())
} else {
Err(SnapshotRejection::Integrity)
}
}
+111
View File
@@ -0,0 +1,111 @@
//! The finding builder of the findings picker (`FindingsTreePicker.toggleLeaf` and the
//! card's `onChange`): a finding is keyed by `(findingZoneId, path, side)` and snapshots the
//! labels of the node the practitioner clicked.
use super::EditorError;
use crate::domain::report::{Finding, LateralSide, Observation};
use crate::domain::sheet::{FindingNode, FindingTreeItem, FindingZone, IndexedDocument};
/// What the picker knows about the clicked leaf.
#[derive(Debug, Clone, Copy)]
pub struct LeafClick<'a> {
/// Id of the finding zone the picker shows (last duplicate wins, as `findingZone`).
pub finding_zone_id: &'a str,
/// Node ids from the zone's categories down to the leaf.
pub path: &'a [String],
/// Position of the leaf among its siblings in the list the picker rendered.
pub leaf_position: usize,
pub side: Option<LateralSide>,
}
fn matches(finding: &Finding, click: &LeafClick<'_>) -> bool {
finding.finding_zone_id == click.finding_zone_id
&& finding.side == click.side
&& finding.path.as_slice() == click.path
}
/// Toggles the leaf in the observation's findings: every finding with the same zone, side
/// and path is removed when one exists; otherwise the finding built from the clicked node is
/// appended.
pub fn toggle_finding(
sheet: &IndexedDocument<'_>,
observation: &Observation,
click: &LeafClick<'_>,
) -> Result<Observation, EditorError> {
let zone = sheet
.finding_zone(click.finding_zone_id)
.ok_or(EditorError::UnknownZone)?;
let mut findings = observation.findings.clone();
if findings.iter().any(|f| matches(f, click)) {
findings.retain(|f| !matches(f, click));
} else {
findings.push(build_finding(zone, click)?);
}
Ok(Observation {
findings,
..observation.clone()
})
}
/// The finding the picker records for a leaf: labels snapshotted, the vet flag only when a
/// node (never a category) carries it, the side when the zone has one.
fn build_finding(zone: &FindingZone, click: &LeafClick<'_>) -> Result<Finding, EditorError> {
let leaf = clicked_node(zone, click)?;
let name = leaf.name();
Ok(Finding {
finding_zone_id: zone.id.clone(),
path: click.path.to_vec(),
label_fr_snapshot: name.fr.clone(),
label_en_snapshot: name.en.clone(),
requires_vet_referral: leaf.requires_vet_referral().then_some(true),
side: click.side,
unresolved: None,
})
}
/// The node at `leaf_position` of the list the picker rendered: the zone's categories at the
/// root, else the children of the parent reached by the first-wins walk (`findNode`).
fn clicked_node<'a>(
zone: &'a FindingZone,
click: &LeafClick<'_>,
) -> Result<FindingTreeItem<'a>, EditorError> {
let (last, parents) = click.path.split_last().ok_or(EditorError::UnknownNode)?;
let leaf = match parents.split_first() {
None => zone
.categories
.get(click.leaf_position)
.map(FindingTreeItem::Category),
Some((first, rest)) => parent_children(zone, first, rest)?
.get(click.leaf_position)
.map(FindingTreeItem::Node),
}
.ok_or(EditorError::UnknownNode)?;
if leaf.id() == last {
Ok(leaf)
} else {
Err(EditorError::UnknownNode)
}
}
/// Children of the node at `[first, ...rest]`, each segment the first sibling with that id.
fn parent_children<'a>(
zone: &'a FindingZone,
first: &str,
rest: &[String],
) -> Result<&'a [FindingNode], EditorError> {
let category = zone
.categories
.iter()
.find(|c| c.id == first)
.ok_or(EditorError::UnknownNode)?;
let mut node = FindingTreeItem::Category(category);
for segment in rest {
let child = node
.children()
.iter()
.find(|n| &n.id == segment)
.ok_or(EditorError::UnknownNode)?;
node = FindingTreeItem::Node(child);
}
Ok(node.children())
}
+51
View File
@@ -0,0 +1,51 @@
//! Editor rules of the report (R2.3): what a click on the drawing does to the active
//! observation, how a finding is built from the sheet, how the vertebra picker edits its
//! selection, and the report-level list operations of the store. Ported from
//! `apps/app/src/services/zoneInteraction.ts`, `FindingsTreePicker.toggleLeaf`,
//! `VertebraPicker` and `reportStore.ts`; every function returns new values and never
//! touches its inputs.
pub mod finding;
pub mod report_ops;
pub mod vertebra;
pub mod zone;
pub use finding::{LeafClick, toggle_finding};
pub use report_ops::{
MoveDirection, NewReportDraft, NewReportStamp, add_observation, move_observation, new_report,
remove_observation,
};
pub use vertebra::{VertebraAction, select_vertebrae};
pub use zone::{
ZoneClick, ZoneClickKind, add_sides, collect_vertebrae, remove_zone_at, sync_vertebrae,
vertebra_initial, zone_click,
};
/// Closed failure kinds of the editor rules: inputs the TypeScript code never produced
/// (it either guarded them in the UI or would have corrupted its own state).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EditorError {
/// No annotation of the sheet has this id.
UnknownAnnotation,
/// No finding zone of the sheet has this id.
UnknownZone,
/// The path and position name no node of the finding tree.
UnknownNode,
/// An observation index outside the list.
InvalidIndex,
/// A vertebra count no picker grid can show.
InvalidCount,
}
impl EditorError {
/// The closed kind the facade reports.
pub fn kind(self) -> &'static str {
match self {
Self::UnknownAnnotation => "unknown_annotation",
Self::UnknownZone => "unknown_zone",
Self::UnknownNode => "unknown_node",
Self::InvalidIndex => "invalid_index",
Self::InvalidCount => "invalid_count",
}
}
}
+131
View File
@@ -0,0 +1,131 @@
//! Report-level rules of the store (`apps/app/src/state/reportStore.ts`): a new report is
//! stamped from the form draft, observations are added, removed and moved. The active
//! observation index is screen state and stays in the store.
use serde::{Deserialize, Serialize};
#[cfg(feature = "ts")]
use ts_rs::TS;
use super::EditorError;
use crate::domain::js;
use crate::domain::report::{
Animal, NextAppointment, Observation, Owner, Practitioner, Report, ReportVersion3, SheetRef,
};
/// What a new report needs before version, id, dates and the sheet are stamped
/// (`Omit<Report, 'version' | 'id' | 'createdAt' | 'sheet' | 'localAnnotations'>`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "camelCase")]
pub struct NewReportDraft {
pub date: String,
pub practitioner: Practitioner,
pub animal: Animal,
pub owner: Owner,
pub observations: Vec<Observation>,
pub conclusion: String,
pub recommendations: String,
#[serde(
default,
deserialize_with = "js::present",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(feature = "ts", ts(optional))]
pub next_appointment: Option<NextAppointment>,
}
/// A fresh observation: nothing recorded yet.
fn empty_observation(id: &str) -> Observation {
Observation {
id: id.to_owned(),
..Observation::default()
}
}
/// The ids and the time a new report is stamped with (the core makes neither).
#[derive(Debug, Clone, Copy)]
pub struct NewReportStamp<'a> {
pub id: &'a str,
pub created_at: &'a str,
/// Id of the observation a draft without any starts with.
pub observation_id: &'a str,
}
/// A fresh v3 document: the draft, stamped with version, id, creation time and sheet; a
/// draft without observations starts with one empty observation.
pub fn new_report(draft: NewReportDraft, sheet: SheetRef, stamp: &NewReportStamp<'_>) -> Report {
let observations = if draft.observations.is_empty() {
vec![empty_observation(stamp.observation_id)]
} else {
draft.observations
};
Report {
version: ReportVersion3,
id: stamp.id.to_owned(),
created_at: stamp.created_at.to_owned(),
date: draft.date,
practitioner: draft.practitioner,
animal: draft.animal,
owner: draft.owner,
sheet,
observations,
conclusion: draft.conclusion,
recommendations: draft.recommendations,
next_appointment: draft.next_appointment,
local_annotations: Vec::new(),
}
}
fn with_observations(report: &Report, observations: Vec<Observation>) -> Report {
Report {
observations,
..report.clone()
}
}
/// Appends an empty observation with the given id.
pub fn add_observation(report: &Report, id: &str) -> Report {
let mut observations = report.observations.clone();
observations.push(empty_observation(id));
with_observations(report, observations)
}
/// Removes the observation at `index`; an index outside the list removes nothing.
pub fn remove_observation(report: &Report, index: usize) -> Report {
let observations = report
.observations
.iter()
.enumerate()
.filter(|(i, _)| *i != index)
.map(|(_, o)| o.clone())
.collect();
with_observations(report, observations)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "lowercase")]
pub enum MoveDirection {
Up,
Down,
}
/// Swaps the observation at `index` with its neighbour; nothing happens at the ends. Moving
/// up from an index past the end is refused (the TypeScript swap would write a hole).
pub fn move_observation(
report: &Report,
index: usize,
direction: MoveDirection,
) -> Result<Report, EditorError> {
let len = report.observations.len();
let (first, second) = match direction {
MoveDirection::Up if index == 0 => return Ok(report.clone()),
MoveDirection::Up if index >= len => return Err(EditorError::InvalidIndex),
MoveDirection::Up => (index - 1, index),
MoveDirection::Down if index.saturating_add(1) >= len => return Ok(report.clone()),
MoveDirection::Down => (index, index + 1),
};
let mut observations = report.observations.clone();
observations.swap(first, second);
Ok(with_observations(report, observations))
}
+97
View File
@@ -0,0 +1,97 @@
//! The vertebra picker's selection rules (`VertebraPicker.tsx` toggle / all / none): what a
//! tap on a chip or on "check all" / "uncheck all" does to the selection being edited.
use serde::Deserialize;
#[cfg(feature = "ts")]
use ts_rs::TS;
use super::EditorError;
use crate::domain::js::JsInt;
use crate::domain::report::Vertebra;
/// Largest grid "check all" fills. A region's usual count is a small number; a count beyond
/// this cap is refused instead of allocated (JavaScript would build any array shorter than
/// 2^32 - 1 elements).
const MAX_CHECK_ALL: f64 = 65_535.0;
/// One tap of the picker.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum VertebraAction {
/// A chip: removes that vertebra when selected, appends it otherwise.
Toggle {
region: String,
#[cfg_attr(feature = "ts", ts(type = "number"))]
index: JsInt,
},
/// "Check all": the region's vertebrae 1..=count replace its current ones, appended last.
All {
region: String,
#[cfg_attr(feature = "ts", ts(type = "number"))]
count: JsInt,
},
/// "Uncheck all": every vertebra of the region removed.
None { region: String },
}
fn same(vertebra: &Vertebra, region: &str, index: JsInt) -> bool {
vertebra.region == region && vertebra.index == index
}
fn other_regions(selection: &[Vertebra], region: &str) -> Vec<Vertebra> {
selection
.iter()
.filter(|v| v.region != region)
.cloned()
.collect()
}
/// The selection after one tap; the input is never modified.
pub fn select_vertebrae(
selection: &[Vertebra],
action: &VertebraAction,
) -> Result<Vec<Vertebra>, EditorError> {
match action {
VertebraAction::Toggle { region, index } => Ok(toggled(selection, region, *index)),
VertebraAction::All { region, count } => {
let mut out = other_regions(selection, region);
out.extend(full_region(region, *count)?);
Ok(out)
}
VertebraAction::None { region } => Ok(other_regions(selection, region)),
}
}
fn toggled(selection: &[Vertebra], region: &str, index: JsInt) -> Vec<Vertebra> {
if selection.iter().any(|v| same(v, region, index)) {
return selection
.iter()
.filter(|v| !same(v, region, index))
.cloned()
.collect();
}
let mut out = selection.to_vec();
out.push(Vertebra {
region: region.to_owned(),
index,
});
out
}
/// `Array.from({ length: count }, (_, k) => ({ region, index: k + 1 }))`; a negative count
/// gives an empty array as `ToLength` makes it.
fn full_region(region: &str, count: JsInt) -> Result<Vec<Vertebra>, EditorError> {
let count = count.get().max(0.0);
if count > MAX_CHECK_ALL {
return Err(EditorError::InvalidCount);
}
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
let count = count as u32;
Ok((1..=count)
.map(|index| Vertebra {
region: region.to_owned(),
index: JsInt::from(index),
})
.collect())
}
+379
View File
@@ -0,0 +1,379 @@
//! Zone interaction rules (`apps/app/src/services/zoneInteraction.ts`): what a click on an
//! annotation means for the active observation, and the observation reducers the editor
//! applies. The rules are the legacy ones (click chain of the editor, BDR-019 vertebra sync),
//! keyed by annotation ids.
use serde::Serialize;
#[cfg(feature = "ts")]
use ts_rs::TS;
use super::EditorError;
use crate::domain::report::{LateralSide, Observation, ReportZone, Vertebra};
use crate::domain::sheet::{Annotation, IndexedDocument};
use crate::json::js_number;
/// The kind of a click decision (`ZoneClickDecision.kind`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "snake_case")]
pub enum ZoneClickKind {
Ignore,
OpenView,
ActivateFallback,
OpenVertebraPicker,
OpenLateralityPicker,
RemoveBothSides,
Toggle,
}
/// What a click on an annotation did, with what the editor needs to follow it up.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "camelCase")]
pub struct ZoneClick {
pub kind: ZoneClickKind,
/// `open_view`: the detail view to open.
#[serde(skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "ts", ts(optional))]
pub view_id: Option<String>,
/// The active observation after the click, when the click changed it.
#[serde(skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "ts", ts(optional))]
pub observation: Option<Observation>,
/// `open_vertebra_picker`: the zone the picker edits.
#[serde(skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "ts", ts(optional))]
pub zone_index: Option<u32>,
/// `open_laterality_picker`: the sides already recorded.
#[serde(skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "ts", ts(optional))]
pub sides_present: Option<Vec<LateralSide>>,
/// `open_vertebra_picker`: the picker's initial selection.
#[serde(skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "ts", ts(optional))]
pub vertebrae: Option<Vec<Vertebra>>,
}
impl ZoneClick {
fn of(kind: ZoneClickKind) -> Self {
Self {
kind,
view_id: None,
observation: None,
zone_index: None,
sides_present: None,
vertebrae: None,
}
}
}
/// The zone a click on `annotation` names: its id on its own view.
fn same_zone(zone: &ReportZone, annotation: &Annotation) -> bool {
zone.annotation_id == annotation.id() && zone.view_id == annotation.view_id()
}
/// Sides already recorded for the annotation's zone, in zone order.
pub fn sides_present(observation: &Observation, annotation: &Annotation) -> Vec<LateralSide> {
observation
.zones
.iter()
.filter(|z| same_zone(z, annotation))
.filter_map(|z| z.side)
.collect()
}
/// Legacy click chain: a detail trigger opens its view and is never added; no active
/// observation → the click only activates one; spine zones always open the picker; bilateral
/// zones go through the side picker, or clear both sides when both are set; anything else
/// toggles.
fn decide(annotation: &Annotation, active: Option<&Observation>) -> ZoneClick {
let observable = match annotation {
Annotation::DetailTrigger(trigger) => {
let mut click = ZoneClick::of(ZoneClickKind::OpenView);
click.view_id = Some(trigger.opens_view_id.clone());
return click;
}
Annotation::Observable(observable) => observable,
};
let Some(active) = active else {
return ZoneClick::of(ZoneClickKind::ActivateFallback);
};
if observable.vertebral_region_code.is_some() {
return ZoneClick::of(ZoneClickKind::OpenVertebraPicker);
}
if observable.laterality == crate::domain::sheet::Laterality::Bilateral {
let sides = sides_present(active, annotation);
let both = sides.contains(&LateralSide::Left) && sides.contains(&LateralSide::Right);
return ZoneClick::of(if both {
ZoneClickKind::RemoveBothSides
} else {
ZoneClickKind::OpenLateralityPicker
});
}
ZoneClick::of(ZoneClickKind::Toggle)
}
/// A new zone for the annotation: its ref, the observable name snapshot, the side if any.
fn new_zone(annotation: &Annotation, side: Option<LateralSide>) -> ReportZone {
let mut zone = ReportZone {
annotation_id: annotation.id().to_owned(),
view_id: annotation.view_id().to_owned(),
side,
..ReportZone::default()
};
if let Some(observable) = annotation.observable() {
zone.label_fr_snapshot = Some(observable.name.fr.clone());
zone.label_en_snapshot = Some(observable.name.en.clone());
}
zone
}
fn with_zones(observation: &Observation, zones: Vec<ReportZone>) -> Observation {
Observation {
zones,
..observation.clone()
}
}
/// Plain zone: removed when present (the first match), added when absent (no side).
pub fn toggle_zone(observation: &Observation, annotation: &Annotation) -> Observation {
let found = observation
.zones
.iter()
.position(|z| same_zone(z, annotation));
let zones = match found {
Some(index) => without(&observation.zones, index),
None => appended(&observation.zones, new_zone(annotation, None)),
};
with_zones(observation, zones)
}
/// The zone exists after the call; returns the observation (unchanged when it existed) and
/// the zone's index.
pub fn ensure_zone(observation: &Observation, annotation: &Annotation) -> (Observation, usize) {
match observation
.zones
.iter()
.position(|z| same_zone(z, annotation))
{
Some(index) => (observation.clone(), index),
None => {
let zones = appended(&observation.zones, new_zone(annotation, None));
let index = zones.len() - 1;
(with_zones(observation, zones), index)
}
}
}
fn without(zones: &[ReportZone], index: usize) -> Vec<ReportZone> {
zones
.iter()
.enumerate()
.filter(|(i, _)| *i != index)
.map(|(_, z)| z.clone())
.collect()
}
fn appended(zones: &[ReportZone], zone: ReportZone) -> Vec<ReportZone> {
let mut out = zones.to_vec();
out.push(zone);
out
}
/// Appends the sides not present yet; never removes one (legacy semantics). Unchanged when
/// every side is already there.
pub fn add_sides(
sheet: &IndexedDocument<'_>,
observation: &Observation,
annotation_id: &str,
sides: &[LateralSide],
) -> Result<Observation, EditorError> {
let annotation = sheet
.annotation(annotation_id)
.ok_or(EditorError::UnknownAnnotation)?;
let present = sides_present(observation, annotation);
let added: Vec<ReportZone> = sides
.iter()
.filter(|side| !present.contains(side))
.map(|side| new_zone(annotation, Some(*side)))
.collect();
let mut zones = observation.zones.clone();
zones.extend(added);
Ok(with_zones(observation, zones))
}
/// Every zone of the annotation's ref, whatever its side.
pub fn remove_all_sides(observation: &Observation, annotation: &Annotation) -> Observation {
let zones = observation
.zones
.iter()
.filter(|z| !same_zone(z, annotation))
.cloned()
.collect();
with_zones(observation, zones)
}
/// One zone by index; an index outside the list removes nothing (as `filter` does).
pub fn remove_zone_at(observation: &Observation, index: usize) -> Observation {
with_zones(observation, without(&observation.zones, index))
}
/// Vertebrae of every spine zone of the observation, the zone at `priority` first (the one
/// the picker was opened from), without duplicates. Duplicates are found on the text
/// `region + index` exactly as the TypeScript key, so `C1`/1 and `C`/11 count as one.
pub fn collect_vertebrae(
sheet: &IndexedDocument<'_>,
observation: &Observation,
priority: usize,
) -> Vec<Vertebra> {
let zones = &observation.zones;
let ordered = zones
.iter()
.enumerate()
.filter(|(i, _)| *i == priority)
.chain(zones.iter().enumerate().filter(|(i, _)| *i != priority))
.map(|(_, zone)| zone)
.filter(|zone| sheet.is_spine(&zone.annotation_id));
let mut seen: Vec<String> = Vec::new();
let mut out = Vec::new();
for vertebra in ordered.flat_map(|zone| zone.vertebrae.iter().flatten()) {
let key = format!("{}{}", vertebra.region, js_number(vertebra.index.get()));
if !seen.contains(&key) {
seen.push(key);
out.push(vertebra.clone());
}
}
out
}
/// The picker's initial selection when it opens from the zone at `zone_index` (chip path).
pub fn vertebra_initial(
sheet: &IndexedDocument<'_>,
observation: &Observation,
zone_index: usize,
) -> Vec<Vertebra> {
collect_vertebrae(sheet, observation, zone_index)
}
/// The selection grouped by region, in first-seen order (a JavaScript `Map`).
fn by_region(selection: &[Vertebra]) -> Vec<(String, Vec<Vertebra>)> {
let mut groups: Vec<(String, Vec<Vertebra>)> = Vec::new();
for vertebra in selection {
match groups
.iter_mut()
.find(|(region, _)| *region == vertebra.region)
{
Some((_, list)) => list.push(vertebra.clone()),
None => groups.push((vertebra.region.clone(), vec![vertebra.clone()])),
}
}
groups
}
/// The region of a spine zone (by its annotation id, last duplicate wins).
fn region_of(sheet: &IndexedDocument<'_>, zone: &ReportZone) -> Option<String> {
if !sheet.is_spine(&zone.annotation_id) {
return None;
}
sheet
.annotation(&zone.annotation_id)
.and_then(Annotation::observable)
.and_then(|a| a.vertebral_region_code.clone())
}
/// BDR-019: the picker edits every region at once. Per region the selection REPLACES the
/// zone's vertebrae; a spine zone left without vertebrae (or a second zone of a region
/// already served) is pruned; a region picked without a zone gets one on the view the
/// picker was opened from, else on the main view.
pub fn sync_vertebrae(
sheet: &IndexedDocument<'_>,
observation: &Observation,
selection: &[Vertebra],
view_id: &str,
) -> Observation {
let mut groups = by_region(selection);
let mut kept = Vec::new();
for zone in &observation.zones {
let Some(region) = region_of(sheet, zone) else {
kept.push(zone.clone());
continue;
};
let Some(position) = groups.iter().position(|(r, _)| *r == region) else {
continue;
};
let (_, picked) = groups.remove(position);
kept.push(ReportZone {
vertebrae: Some(picked),
..zone.clone()
});
}
kept.extend(spawned_zones(sheet, groups, view_id));
with_zones(observation, kept)
}
/// Zones for the regions picked without one, in selection order; a region with no spine
/// annotation on the view nor on the main view is dropped.
fn spawned_zones(
sheet: &IndexedDocument<'_>,
groups: Vec<(String, Vec<Vertebra>)>,
view_id: &str,
) -> Vec<ReportZone> {
let main_view_id = sheet.main_view().id().to_owned();
groups
.into_iter()
.filter_map(|(region, picked)| {
let annotation = spine_annotation(sheet, &region, view_id)
.or_else(|| spine_annotation(sheet, &region, &main_view_id))?;
Some(ReportZone {
vertebrae: Some(picked),
..new_zone(annotation, None)
})
})
.collect()
}
/// `index.spineAnnotation(region, view)` as an `Annotation` (first match in the document).
fn spine_annotation<'a>(
sheet: &IndexedDocument<'a>,
region: &str,
view_id: &str,
) -> Option<&'a Annotation> {
sheet.document.annotations.iter().find(|a| {
a.observable().is_some_and(|o| {
o.view_id == view_id && o.vertebral_region_code.as_deref() == Some(region)
})
})
}
/// One click on `annotation_id` with the active observation (`EditorRoute.onZoneClick`):
/// the decision, then the reducer it names, then what the follow-up picker needs.
pub fn zone_click(
sheet: &IndexedDocument<'_>,
observation: Option<&Observation>,
annotation_id: &str,
) -> ZoneClick {
let Some(annotation) = sheet.annotation(annotation_id) else {
return ZoneClick::of(ZoneClickKind::Ignore);
};
let mut click = decide(annotation, observation);
let Some(active) = observation else {
return click;
};
match click.kind {
ZoneClickKind::OpenVertebraPicker => {
let (ensured, index) = ensure_zone(active, annotation);
click.vertebrae = Some(collect_vertebrae(sheet, &ensured, index));
click.zone_index = u32::try_from(index).ok();
click.observation = (ensured != *active).then_some(ensured);
}
ZoneClickKind::OpenLateralityPicker => {
click.sides_present = Some(sides_present(active, annotation));
}
ZoneClickKind::RemoveBothSides => {
click.observation = Some(remove_all_sides(active, annotation));
}
ZoneClickKind::Toggle => click.observation = Some(toggle_zone(active, annotation)),
_ => {}
}
click
}
+384
View File
@@ -0,0 +1,384 @@
//! JavaScript and Zod semantics the ported contracts depend on (R2 plan P1, P2).
//!
//! The TypeScript domain reads JSON with `JSON.parse` and validates it with Zod 3: a duplicate
//! key keeps its last value at its first position, `.int()` accepts any number with an
//! integer value (`2.0`, `1e20`), string lengths count UTF-16 code units, and the patterns are
//! JavaScript regular expressions whose `$` only matches at the end of the input. The helpers
//! below reproduce exactly that, so a document the old code accepted is accepted here and
//! prints the same. One declared exception: a lone surrogate escape, which `JSON.parse` keeps
//! and a Rust string cannot hold, refuses the text instead of being altered (L1).
use std::fmt;
use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::Value;
/// Why a JSON text cannot be read.
#[derive(Debug)]
pub enum JsonReadError {
/// The text escapes a lone UTF-16 surrogate (`\uD800`–`\uDFFF` outside a high + low
/// pair). `JSON.parse` keeps it; reading it here would replace it, so the whole text is
/// refused and the caller keeps it verbatim (L1: user data is never altered silently).
LoneSurrogate { offset: usize },
/// Not JSON.
Syntax(serde_json::Error),
}
impl fmt::Display for JsonReadError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::LoneSurrogate { offset } => {
write!(f, "lone UTF-16 surrogate escape at byte {offset}")
}
Self::Syntax(error) => error.fmt(f),
}
}
}
/// Reads JSON text as `JSON.parse` does, as far as a Rust string allows. serde_json refuses
/// a lone surrogate escape like any other error; the refusal is then classified so callers
/// can name it (the scan runs on failures only).
pub fn parse_json(text: &str) -> Result<Value, JsonReadError> {
serde_json::from_str(text).map_err(|error| match find_lone_surrogate(text) {
Some(offset) => JsonReadError::LoneSurrogate { offset },
None => JsonReadError::Syntax(error),
})
}
/// Byte offset of the first `\uD800`–`\uDFFF` escape that is not a high + low pair.
/// Escapes are consumed left to right, so `\\u…` (an escaped backslash) is skipped.
pub fn find_lone_surrogate(text: &str) -> Option<usize> {
let bytes = text.as_bytes();
let mut i = 0;
while i < bytes.len() {
if bytes[i] != b'\\' {
i += 1;
continue;
}
let Some(unit) = escape_unit(bytes, i) else {
i += 2;
continue;
};
let is_pair = (0xD800..=0xDBFF).contains(&unit)
&& escape_unit(bytes, i + 6).is_some_and(|low| (0xDC00..=0xDFFF).contains(&low));
if is_pair {
i += 12;
continue;
}
if (0xD800..=0xDFFF).contains(&unit) {
return Some(i);
}
i += 6;
}
None
}
/// The code unit of a `\uXXXX` escape starting at `at`, if there is one.
fn escape_unit(bytes: &[u8], at: usize) -> Option<u32> {
let escape = bytes.get(at..at + 6)?;
if escape[0] != b'\\' || escape[1] != b'u' || !escape[2..].iter().all(u8::is_ascii_hexdigit) {
return None;
}
let digits = std::str::from_utf8(&escape[2..]).ok()?;
u32::from_str_radix(digits, 16).ok()
}
/// Length of a string as JavaScript's `.length` counts it (UTF-16 code units).
pub fn utf16_len(text: &str) -> usize {
text.encode_utf16().count()
}
/// An integer as Zod's `.int()` accepts it: any finite number with no fraction, kept as the
/// JavaScript number it is and printed as JavaScript prints it.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Default)]
pub struct JsInt(f64);
impl JsInt {
pub fn new(value: f64) -> Option<Self> {
(value.is_finite() && value.fract() == 0.0).then_some(Self(value))
}
pub fn get(self) -> f64 {
self.0
}
}
impl From<u32> for JsInt {
fn from(value: u32) -> Self {
Self(f64::from(value))
}
}
impl Serialize for JsInt {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
// Exact below 2^53: printed as an integer by every formatter; beyond, the float
// goes through `js_number` like JavaScript.
if self.0.abs() < 9_007_199_254_740_992.0 {
#[allow(clippy::cast_possible_truncation)]
return serializer.serialize_i64(self.0 as i64);
}
serializer.serialize_f64(self.0)
}
}
impl<'de> Deserialize<'de> for JsInt {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let value = f64::deserialize(deserializer)?;
Self::new(value).ok_or_else(|| D::Error::custom("expected an integer"))
}
}
/// `.optional()`: absent is fine, an explicit `null` is refused (serde alone would read it
/// as absent). Used with `#[serde(default, deserialize_with = "js::present")]`.
pub fn present<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
where
D: Deserializer<'de>,
T: Deserialize<'de>,
{
T::deserialize(deserializer).map(Some)
}
/// `.nullable()` without a default: the key is required, `null` is a value. Used with
/// `#[serde(deserialize_with = "js::nullable")]` (no `default`, so a missing key fails).
pub fn nullable<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
where
D: Deserializer<'de>,
T: Deserialize<'de>,
{
Option::<T>::deserialize(deserializer)
}
/// `z.string().min(1)`.
pub fn non_empty(text: &str) -> bool {
!text.is_empty()
}
/// `/^[a-z0-9][a-z0-9_-]{0,63}$/` (stable ids).
pub fn is_stable_id(text: &str) -> bool {
let bytes = text.as_bytes();
!bytes.is_empty()
&& bytes.len() <= 64
&& matches!(bytes[0], b'a'..=b'z' | b'0'..=b'9')
&& bytes[1..]
.iter()
.all(|b| matches!(b, b'a'..=b'z' | b'0'..=b'9' | b'_' | b'-'))
}
/// `/^[A-Za-z0-9][A-Za-z0-9_-]{0,15}$/` (vertebral region codes).
pub fn is_region_code(text: &str) -> bool {
let bytes = text.as_bytes();
!bytes.is_empty()
&& bytes.len() <= 16
&& bytes[0].is_ascii_alphanumeric()
&& bytes[1..]
.iter()
.all(|b| b.is_ascii_alphanumeric() || *b == b'_' || *b == b'-')
}
/// `/^#[0-9a-fA-F]{6}$/`.
pub fn is_hex_color(text: &str) -> bool {
let bytes = text.as_bytes();
bytes.len() == 7 && bytes[0] == b'#' && bytes[1..].iter().all(u8::is_ascii_hexdigit)
}
/// `/^[0-9a-f]{64}$/`.
pub fn is_sha256_hex(text: &str) -> bool {
text.len() == 64 && text.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
}
/// `/^[A-Za-z0-9+/]*={0,2}$/`.
pub fn is_base64(text: &str) -> bool {
let body = text.trim_end_matches('=');
text.len() - body.len() <= 2
&& body
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'+' || b == b'/')
}
/// Zod 3's `.uuid()` pattern: 8-4-4-4-12 hexadecimal digits, any case, any version.
pub fn is_uuid(text: &str) -> bool {
let bytes = text.as_bytes();
bytes.len() == 36
&& bytes.iter().enumerate().all(|(index, byte)| match index {
8 | 13 | 18 | 23 => *byte == b'-',
_ => byte.is_ascii_hexdigit(),
})
}
/// Zod's `.url()`: `new URL(text)` succeeds (WHATWG parser).
pub fn is_url(text: &str) -> bool {
url::Url::parse(text).is_ok()
}
/// A string literal field (the tag of a discriminated union, a format name): reads only
/// that literal and prints it, at the position the Zod schema declares it.
macro_rules! literal {
($name:ident, $value:literal) => {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct $name;
impl serde::Serialize for $name {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str($value)
}
}
impl<'de> serde::Deserialize<'de> for $name {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
use serde::de::Error as _;
let text = <String as serde::Deserialize>::deserialize(deserializer)?;
if text == $value {
Ok($name)
} else {
Err(D::Error::custom(concat!("expected \"", $value, "\"")))
}
}
}
#[cfg(feature = "ts")]
impl ts_rs::TS for $name {
type WithoutGenerics = Self;
type OptionInnerType = Self;
fn name(_: &ts_rs::Config) -> String {
format!("\"{}\"", $value)
}
fn inline(cfg: &ts_rs::Config) -> String {
Self::name(cfg)
}
}
};
}
/// A number literal field (a document version): reads any JSON number equal to it (`2.0`
/// included, as `z.literal(2)` after `JSON.parse`) and prints the integer.
macro_rules! number_literal {
($name:ident, $value:literal) => {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct $name;
impl serde::Serialize for $name {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_u32($value)
}
}
impl<'de> serde::Deserialize<'de> for $name {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
use serde::de::Error as _;
if <f64 as serde::Deserialize>::deserialize(deserializer)? == f64::from($value) {
Ok($name)
} else {
Err(D::Error::custom(concat!("expected ", $value)))
}
}
}
#[cfg(feature = "ts")]
impl ts_rs::TS for $name {
type WithoutGenerics = Self;
type OptionInnerType = Self;
fn name(_: &ts_rs::Config) -> String {
stringify!($value).to_owned()
}
fn inline(cfg: &ts_rs::Config) -> String {
Self::name(cfg)
}
}
};
}
pub(crate) use {literal, number_literal};
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lone_surrogate_escapes_are_found_and_pairs_are_not() {
assert_eq!(find_lone_surrogate("\"a\\ud800b\""), Some(2));
assert_eq!(find_lone_surrogate("\"\\udc00\""), Some(1));
assert_eq!(find_lone_surrogate("\"\\uDBFF\""), Some(1));
assert_eq!(find_lone_surrogate("\"\\ud800\\ud800\""), Some(1));
assert_eq!(find_lone_surrogate("\"\\ud800\\n\""), Some(1));
assert_eq!(find_lone_surrogate("\"\\ud83d\\ude00\\udc00\""), Some(13));
assert_eq!(find_lone_surrogate("\"x\\ud800"), Some(2));
assert_eq!(find_lone_surrogate("\"\\ud83d\\ude00\""), None);
assert_eq!(find_lone_surrogate("\"\\\\ud800\""), None);
assert_eq!(find_lone_surrogate("\"\\u+800 \\u00e9 é\""), None);
assert_eq!(find_lone_surrogate("plain"), None);
}
#[test]
fn a_lone_surrogate_refuses_the_text_and_is_never_replaced() {
for text in [
"{\"t\":\"x\\ud800\"}",
"{\"t\":\"\\udfff\"}",
"{\"t\":[\"ok\",\"\\ud83d\"]}",
"{\"\\ud800\":1}",
] {
assert!(
matches!(parse_json(text), Err(JsonReadError::LoneSurrogate { .. })),
"{text}"
);
}
assert!(matches!(
parse_json("{ not json"),
Err(JsonReadError::Syntax(_))
));
}
#[test]
fn normal_text_reads_unchanged() {
let Ok(value) = parse_json("{\"t\":\"é \\u00e9 \\ud83d\\ude00 😀 \\\\ud800 \\uFFFD\"}")
else {
panic!("parse failed");
};
assert_eq!(value["t"], "é é 😀 😀 \\ud800 \u{FFFD}");
}
#[test]
fn duplicate_keys_keep_the_last_value_at_the_first_position() {
let Ok(value) = parse_json(r#"{"a":1,"b":2,"a":3}"#) else {
panic!("parse failed");
};
assert_eq!(value.to_string(), r#"{"a":3,"b":2}"#);
}
#[test]
fn js_int_accepts_integer_valued_numbers_only() {
let parsed: Vec<Option<JsInt>> = ["2", "2.0", "1e20", "-0", "2.5"]
.iter()
.map(|t| serde_json::from_str::<JsInt>(t).ok())
.collect();
assert_eq!(parsed[0].map(JsInt::get), Some(2.0));
assert_eq!(parsed[1].map(JsInt::get), Some(2.0));
assert_eq!(parsed[2].map(JsInt::get), Some(1e20));
assert!(parsed[3].is_some());
assert!(parsed[4].is_none());
let printed = crate::json::to_js_pretty(&[JsInt(2.0), JsInt(1e20), JsInt(-0.0)]);
assert_eq!(
printed.ok().as_deref(),
Some("[\n 2,\n 100000000000000000000,\n 0\n]")
);
}
#[test]
fn utf16_lengths_count_surrogate_pairs_twice() {
assert_eq!(utf16_len("é"), 1);
assert_eq!(utf16_len("😀"), 2);
}
#[test]
fn patterns_match_the_zod_regular_expressions() {
assert!(is_stable_id("view-main") && is_stable_id(&"a".repeat(64)));
assert!(!is_stable_id("_x") && !is_stable_id("A") && !is_stable_id(&"a".repeat(65)));
assert!(!is_stable_id("a\n"));
assert!(is_region_code("Cd") && !is_region_code("-C") && !is_region_code(""));
assert!(is_hex_color("#a0B1c2") && !is_hex_color("#a0B1c"));
assert!(is_sha256_hex(&"0".repeat(64)) && !is_sha256_hex(&"A".repeat(64)));
assert!(is_base64("") && is_base64("QUJD==") && !is_base64("QUJD===") && !is_base64("a=b"));
assert!(is_uuid("123e4567-E89B-12d3-a456-426614174000"));
assert!(!is_uuid("123e4567e89b12d3a456426614174000"));
assert!(is_url("https://example.org/a?b#c") && !is_url("not a url") && !is_url("http://"));
}
}
Loaded 100 of 314 files, more files were not shown because too many files have changed in this diff. Show more