feat(domain): R2.1 Rust contracts of the sheet, report and archive documents

Sheet document v2, report v3 / v2 / identity, migration map, sheet snapshot,
branding, PDF labels and archive envelope ported from the Zod schemas with
their exact semantics: strict objects where Zod is strict, optional fields
absent (never null), nullable fields required, integers as JavaScript
numbers, UTF-16 caps, hand-checked patterns, url crate for .url(), lone
surrogate escapes read as U+FFFD (L1, owner confirmation pending).
Fields in Zod schema order (PDF labels in the engine dictionary order):
the curated and legacy sheets, the demo report and the three frozen
archive envelopes print byte for byte as their Zod / attachment form.
ts-rs types regenerated; plan rev 2 after three plan challenges.
This commit is contained in:
bchanot committed 2026-10-14 00:04:01 +02:00
1 parent 3114d67959
commit ee0700887f
87 files changed
+2657 -148

No files matched your search

+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,
}
+11
View File
@@ -0,0 +1,11 @@
//! Archive contracts: the sheet snapshot, the branding, the PDF labels and the envelope.
pub mod branding;
pub mod envelope;
pub mod labels;
pub mod snapshot;
pub use branding::*;
pub use envelope::*;
pub use labels::*;
pub use snapshot::*;
+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>,
}
+346
View File
@@ -0,0 +1,346 @@
//! 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: lone
//! surrogate escapes are kept, 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.
use std::borrow::Cow;
use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::Value;
/// Reads JSON text as `JSON.parse` does, as far as a Rust string allows: an escape of a
/// lone UTF-16 surrogate (which `JSON.parse` keeps and Rust strings cannot hold) becomes
/// U+FFFD instead of refusing the whole document (leniency decision L1).
pub fn parse_json(text: &str) -> Result<Value, serde_json::Error> {
serde_json::from_str(&replace_lone_surrogates(text))
}
/// Rewrites `\uD800`–`\uDFFF` escapes that are not a high + low pair to `�`.
/// Escapes are consumed left to right, so `\\u…` (an escaped backslash) is left alone.
pub fn replace_lone_surrogates(text: &str) -> Cow<'_, str> {
let bytes = text.as_bytes();
let mut out: Option<String> = None;
let mut copied = 0;
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;
};
if (0xD800..=0xDBFF).contains(&unit)
&& escape_unit(bytes, i + 6).is_some_and(|low| (0xDC00..=0xDFFF).contains(&low))
{
i += 12;
continue;
}
if (0xD800..=0xDFFF).contains(&unit) {
let buffer = out.get_or_insert_with(|| String::with_capacity(text.len()));
buffer.push_str(&text[copied..i]);
buffer.push_str("\\uFFFD");
copied = i + 6;
}
i += 6;
}
match out {
None => Cow::Borrowed(text),
Some(mut buffer) => {
buffer.push_str(&text[copied..]);
Cow::Owned(buffer)
}
}
}
/// The code unit of a `\uXXXX` escape starting at `at`, if there is one.
fn escape_unit(bytes: &[u8], at: usize) -> Option<u32> {
let hex = bytes.get(at..at + 6)?;
if hex[0] != b'\\' || hex[1] != b'u' {
return None;
}
let digits = std::str::from_utf8(&hex[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_surrogates_become_replacement_characters() {
assert_eq!(replace_lone_surrogates("\"a\\ud800b\""), "\"a\\uFFFDb\"");
assert_eq!(replace_lone_surrogates("\"\\udc00\""), "\"\\uFFFD\"");
assert_eq!(
replace_lone_surrogates("\"\\ud83d\\ude00\""),
"\"\\ud83d\\ude00\""
);
assert_eq!(replace_lone_surrogates("\"\\\\ud800\""), "\"\\\\ud800\"");
assert_eq!(
replace_lone_surrogates("\"\\ud800\\ud800\""),
"\"\\uFFFD\\uFFFD\""
);
assert!(matches!(replace_lone_surrogates("plain"), Cow::Borrowed(_)));
let Ok(value) = parse_json("{\"t\":\"x\\ud800\"}") else {
panic!("lenient parse failed");
};
assert_eq!(value["t"], "x\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://"));
}
}
+4 -5
View File
@@ -1,9 +1,8 @@
//! Data contracts of the core.
//!
//! R0 carries the Report v3 reference types (sheet reference, zone, vertebra) to prove the
//! serialisation rules against the current Zod schemas; the full contracts and the rules
//! arrive at R2 (review Part VI.2).
//! Data contracts and business rules of the core (R2: sheet, report, archive, editor rules).
pub mod archive;
pub mod js;
pub mod report;
pub mod sheet;
pub use report::{LateralSide, ReportZone, SheetRef, Unresolved, Vertebra};
-137
View File
@@ -1,137 +0,0 @@
//! Report v3 reference types (`packages/domain/src/report/v3.ts`), field order as the Zod
//! schemas declare it. Optional fields are absent when unset and nullable fields are `null`
//! (review I.2): the serde attributes below are the contract, not a convenience.
use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
#[cfg(feature = "ts")]
use ts_rs::TS;
/// Reference of the anatomical sheet a report was written against (`Report.sheet`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "camelCase")]
pub struct SheetRef {
pub sheet_id: String,
/// Database version id once the sheet lives in the database; `null` for a bundled draft.
pub version_id: Option<String>,
/// sha256 of the document file the report was written against.
pub document_sha256: String,
}
/// Side of a bilateral zone.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "lowercase")]
pub enum LateralSide {
Left,
Right,
}
/// One vertebra of a spine zone: the region code and the 1-based index in that region.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "camelCase")]
pub struct Vertebra {
pub region: String,
pub index: u32,
}
/// A zone of an observation. Unknown keys are ignored on input, as the Zod schema strips
/// them; optional fields are written only when set.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "camelCase")]
pub struct ReportZone {
pub annotation_id: String,
pub view_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "ts", ts(optional))]
pub side: Option<LateralSide>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "ts", ts(optional))]
pub vertebrae: Option<Vec<Vertebra>>,
/// Annotation name at selection time (or legacy name at migration).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "ts", ts(optional))]
pub label_fr_snapshot: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "ts", ts(optional))]
pub label_en_snapshot: Option<String>,
/// Set by the migration when the legacy id has no canonical annotation.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "ts", ts(optional, type = "true"))]
pub unresolved: Option<Unresolved>,
}
/// The literal `true` flag of a zone or finding the sheet cannot place
/// (`z.literal(true).optional()` in Zod).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Unresolved;
impl Serialize for Unresolved {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_bool(true)
}
}
impl<'de> Deserialize<'de> for Unresolved {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
if bool::deserialize(deserializer)? {
Ok(Unresolved)
} else {
Err(D::Error::custom(
"unresolved must be the literal true when present",
))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::json::to_js_pretty;
#[test]
fn optional_fields_are_absent_and_nullable_fields_are_null() {
let zone = ReportZone {
annotation_id: "hip".to_owned(),
view_id: "main".to_owned(),
..ReportZone::default()
};
let Ok(text) = to_js_pretty(&zone) else {
panic!("serialisation failed");
};
assert_eq!(
text,
"{\n \"annotationId\": \"hip\",\n \"viewId\": \"main\"\n}"
);
let sheet = SheetRef {
sheet_id: "faunosteo-cheval".to_owned(),
version_id: None,
document_sha256: "0".repeat(64),
};
let Ok(text) = to_js_pretty(&sheet) else {
panic!("serialisation failed");
};
assert!(text.contains("\"versionId\": null"));
}
#[test]
fn unresolved_accepts_true_only() {
let parsed: Result<ReportZone, _> =
serde_json::from_str(r#"{"annotationId":"a","viewId":"v","unresolved":true}"#);
assert_eq!(parsed.ok().and_then(|z| z.unresolved), Some(Unresolved));
let refused: Result<ReportZone, _> =
serde_json::from_str(r#"{"annotationId":"a","viewId":"v","unresolved":false}"#);
assert!(refused.is_err());
}
#[test]
fn unknown_keys_are_ignored_like_the_zod_strip_schema() {
let parsed: Result<ReportZone, _> =
serde_json::from_str(r#"{"annotationId":"a","viewId":"v","extra":1}"#);
assert!(parsed.is_ok());
}
}
+104
View File
@@ -0,0 +1,104 @@
//! Identity snapshots carried by every report version (`report/identity.ts`, BDR-010).
//! Report objects are not strict in Zod: unknown keys are ignored and dropped.
use serde::{Deserialize, Serialize};
#[cfg(feature = "ts")]
use ts_rs::TS;
use crate::domain::js::{self, literal};
use crate::domain::sheet::schema::check;
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
pub struct Practitioner {
#[serde(deserialize_with = "check::non_empty")]
pub name: String,
#[serde(
default,
deserialize_with = "js::present",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(feature = "ts", ts(optional))]
pub cabinet: Option<String>,
#[serde(
default,
deserialize_with = "js::present",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(feature = "ts", ts(optional))]
pub contact: Option<String>,
/// SIRET, 14-digit French business identifier (not validated).
#[serde(
default,
deserialize_with = "js::present",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(feature = "ts", ts(optional))]
pub siret: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "camelCase")]
pub struct Animal {
/// Species of the animal; the sheet the report references matches it.
#[serde(deserialize_with = "check::non_empty")]
pub species_id: String,
#[serde(deserialize_with = "check::non_empty")]
pub name: String,
#[serde(
default,
deserialize_with = "js::present",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(feature = "ts", ts(optional))]
pub breed: Option<String>,
#[serde(
default,
deserialize_with = "js::present",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(feature = "ts", ts(optional))]
pub age: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
pub struct Owner {
#[serde(deserialize_with = "check::non_empty")]
pub name: String,
}
literal!(KindDate, "date");
literal!(KindPeriod, "period");
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
pub struct NextAppointmentDate {
pub kind: KindDate,
pub date: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
pub struct NextAppointmentPeriod {
pub kind: KindPeriod,
pub text: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(untagged)]
pub enum NextAppointment {
Date(NextAppointmentDate),
Period(NextAppointmentPeriod),
}
/// Side of a bilateral zone.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "lowercase")]
pub enum LateralSide {
Left,
Right,
}
@@ -0,0 +1,69 @@
//! Correspondence between the legacy identifiers of a Report v2 and the canonical sheet
//! (`report/migration-map.ts`), generated by the curation pipeline. A `null` finding path
//! means "removed from the sheet".
use std::collections::HashMap;
use serde::de::Error as _;
use serde::{Deserialize, Deserializer};
use super::v3::SheetRef;
use crate::domain::js::number_literal;
use crate::domain::sheet::schema::check;
number_literal!(MigrationMapVersion1, 1);
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct LegacyName {
pub fr: String,
pub en: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct MappedAnnotation {
#[serde(deserialize_with = "check::non_empty")]
pub id: String,
pub name: LegacyName,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct ReportMigrationMap {
pub schema_version: MigrationMapVersion1,
pub sheet: SheetRef,
/// Id of the view a v2 zone without `detailSourceId` belongs to.
#[serde(deserialize_with = "check::non_empty")]
pub main_view_id: String,
/// Legacy detail popup key → view id.
#[serde(deserialize_with = "view_record")]
pub views: HashMap<String, String>,
/// Legacy `data-anno-id` → annotation id and the legacy labels.
#[serde(deserialize_with = "record")]
pub annotations: HashMap<String, MappedAnnotation>,
/// `<zoneId>/<path…>` of every legacy finding node → the same key in the sheet, or null.
#[serde(deserialize_with = "record")]
pub finding_paths: HashMap<String, Option<String>>,
}
/// `z.record(…)`: Zod drops a `__proto__` key while rebuilding the object.
fn record<'de, D, T>(d: D) -> Result<HashMap<String, T>, D::Error>
where
D: Deserializer<'de>,
T: Deserialize<'de>,
{
let mut entries = HashMap::<String, T>::deserialize(d)?;
entries.remove("__proto__");
Ok(entries)
}
fn view_record<'de, D: Deserializer<'de>>(d: D) -> Result<HashMap<String, String>, D::Error> {
let views: HashMap<String, String> = record(d)?;
if views.values().any(String::is_empty) {
return Err(D::Error::custom("empty view id"));
}
Ok(views)
}
/// `findingPathKey(zoneId, path)`.
pub fn finding_path_key(zone_id: &str, path: &[String]) -> String {
format!("{zone_id}/{}", path.join("/"))
}
+10
View File
@@ -0,0 +1,10 @@
//! Report contracts: v3 (current), v2 (input only), the migration map, migration and rebase.
pub mod identity;
pub mod migration_map;
pub mod v2;
pub mod v3;
pub use identity::*;
pub use migration_map::{ReportMigrationMap, finding_path_key};
pub use v3::*;
+104
View File
@@ -0,0 +1,104 @@
//! Report document version 2 (`report/v2.ts`), exactly as the deployed application wrote it.
//! An INPUT format only: nothing writes v2 any more, `migrate.rs` lifts it to v3.
use serde::de::Error as _;
use serde::{Deserialize, Deserializer};
use super::identity::{Animal, LateralSide, NextAppointment, Owner, Practitioner};
use super::v3::finding_path;
use crate::domain::js::{self, JsInt, number_literal};
use crate::domain::sheet::schema::check;
number_literal!(ReportVersion2, 2);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
pub enum SeverityV2 {
#[serde(rename = "légère")]
Legere,
#[serde(rename = "modérée")]
Moderee,
#[serde(rename = "sévère")]
Severe,
}
/// A vertebra of the legacy model: regions C, T, L, S, Cd only.
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct VertebraV2 {
#[serde(deserialize_with = "legacy_region")]
pub region: String,
#[serde(deserialize_with = "check::positive_int")]
pub index: JsInt,
}
fn legacy_region<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
let region = String::deserialize(d)?;
if matches!(region.as_str(), "C" | "T" | "L" | "S" | "Cd") {
Ok(region)
} else {
Err(D::Error::custom("unknown legacy vertebral region"))
}
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ObservationZoneV2 {
/// The legacy SVG `data-anno-id`.
#[serde(deserialize_with = "check::non_empty")]
pub bone_id: String,
/// Legacy detail popup key (`head`) when the zone came from that view.
#[serde(default, deserialize_with = "js::present")]
pub detail_source_id: Option<String>,
#[serde(default, deserialize_with = "js::present")]
pub vertebrae: Option<Vec<VertebraV2>>,
#[serde(default, deserialize_with = "js::present")]
pub side: Option<LateralSide>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FindingV2 {
/// Legacy catalog zone key (equal to the canonical finding zone id).
#[serde(deserialize_with = "check::non_empty")]
pub zone_id: String,
#[serde(deserialize_with = "finding_path")]
pub path: Vec<String>,
#[serde(deserialize_with = "check::non_empty")]
pub label_fr_snapshot: String,
#[serde(deserialize_with = "check::non_empty")]
pub label_en_snapshot: String,
#[serde(default, deserialize_with = "js::present")]
pub requires_vet_referral: Option<bool>,
#[serde(default, deserialize_with = "js::present")]
pub side: Option<LateralSide>,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ObservationV2 {
#[serde(deserialize_with = "check::non_empty")]
pub id: String,
pub zones: Vec<ObservationZoneV2>,
pub findings: Vec<FindingV2>,
pub free_text_findings: Vec<String>,
#[serde(default, deserialize_with = "js::present")]
pub severity: Option<SeverityV2>,
pub comment: String,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ReportV2 {
pub version: ReportVersion2,
#[serde(deserialize_with = "check::non_empty")]
pub id: String,
pub created_at: String,
pub date: String,
pub practitioner: Practitioner,
pub animal: Animal,
pub owner: Owner,
pub observations: Vec<ObservationV2>,
pub conclusion: String,
pub recommendations: String,
#[serde(default, deserialize_with = "js::present")]
pub next_appointment: Option<NextAppointment>,
}
+250
View File
@@ -0,0 +1,250 @@
//! Report document version 3 (`report/v3.ts`): zones name an annotation of a view, findings a
//! node path of a finding zone, both by stable ids, with the labels snapshotted. Fields in Zod
//! schema order; `.optional()` fields are absent when unset, nullable ones print `null`.
use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::Value;
#[cfg(feature = "ts")]
use ts_rs::TS;
use super::identity::{Animal, LateralSide, NextAppointment, Owner, Practitioner};
use crate::domain::js::{self, JsInt, number_literal};
use crate::domain::sheet::schema::check;
pub const REPORT_VERSION: u32 = 3;
number_literal!(ReportVersion3, 3);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "lowercase")]
pub enum Severity {
Mild,
Moderate,
Severe,
}
/// One vertebra: the sheet's region code and the 1-based index in that region.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
pub struct Vertebra {
#[serde(deserialize_with = "check::non_empty")]
pub region: String,
#[serde(deserialize_with = "check::positive_int")]
#[cfg_attr(feature = "ts", ts(type = "number"))]
pub index: JsInt,
}
/// The sheet document a report was built on, by content.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "camelCase")]
pub struct SheetRef {
#[serde(deserialize_with = "check::non_empty")]
pub sheet_id: String,
/// Database version id once the sheet lives in the database; `null` for a bundled draft.
#[serde(deserialize_with = "check::nullable_non_empty")]
pub version_id: Option<String>,
/// sha256 of the document file the report was written against.
#[serde(deserialize_with = "sha256")]
pub document_sha256: String,
}
pub(crate) fn sha256<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
let text = String::deserialize(d)?;
if js::is_sha256_hex(&text) {
Ok(text)
} else {
Err(D::Error::custom("invalid sha256"))
}
}
/// The literal `true` flag of a zone or finding the sheet cannot place.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Unresolved;
impl Serialize for Unresolved {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_bool(true)
}
}
impl<'de> Deserialize<'de> for Unresolved {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
if bool::deserialize(deserializer)? {
Ok(Unresolved)
} else {
Err(D::Error::custom(
"unresolved must be the literal true when present",
))
}
}
}
#[cfg(feature = "ts")]
impl TS for Unresolved {
type WithoutGenerics = Self;
type OptionInnerType = Self;
fn name(_: &ts_rs::Config) -> String {
"true".to_owned()
}
fn inline(cfg: &ts_rs::Config) -> String {
Self::name(cfg)
}
}
/// A zone of an observation.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "camelCase")]
pub struct ReportZone {
#[serde(deserialize_with = "check::non_empty")]
pub annotation_id: String,
#[serde(deserialize_with = "check::non_empty")]
pub view_id: String,
#[serde(
default,
deserialize_with = "js::present",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(feature = "ts", ts(optional))]
pub side: Option<LateralSide>,
#[serde(
default,
deserialize_with = "js::present",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(feature = "ts", ts(optional))]
pub vertebrae: Option<Vec<Vertebra>>,
/// Annotation name at selection time (or legacy name at migration).
#[serde(
default,
deserialize_with = "js::present",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(feature = "ts", ts(optional))]
pub label_fr_snapshot: Option<String>,
#[serde(
default,
deserialize_with = "js::present",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(feature = "ts", ts(optional))]
pub label_en_snapshot: Option<String>,
/// Set by the migration when the legacy id has no canonical annotation.
#[serde(
default,
deserialize_with = "js::present",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(feature = "ts", ts(optional))]
pub unresolved: Option<Unresolved>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "camelCase")]
pub struct Finding {
#[serde(deserialize_with = "check::non_empty")]
pub finding_zone_id: String,
/// Node ids from the zone's categories down to the leaf.
#[serde(deserialize_with = "finding_path")]
pub path: Vec<String>,
#[serde(deserialize_with = "check::non_empty")]
pub label_fr_snapshot: String,
#[serde(deserialize_with = "check::non_empty")]
pub label_en_snapshot: String,
#[serde(
default,
deserialize_with = "js::present",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(feature = "ts", ts(optional))]
pub requires_vet_referral: Option<bool>,
#[serde(
default,
deserialize_with = "js::present",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(feature = "ts", ts(optional))]
pub side: Option<LateralSide>,
/// Set by the migration when the path no longer exists in the sheet; data kept.
#[serde(
default,
deserialize_with = "js::present",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(feature = "ts", ts(optional))]
pub unresolved: Option<Unresolved>,
}
/// `z.array(z.string().min(1)).min(1)`.
pub(crate) fn finding_path<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<String>, D::Error> {
let path = check::non_empty_strings(d)?;
if path.is_empty() {
Err(D::Error::custom("a finding path has at least one segment"))
} else {
Ok(path)
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "camelCase")]
pub struct Observation {
#[serde(deserialize_with = "check::non_empty")]
pub id: String,
pub zones: Vec<ReportZone>,
pub findings: Vec<Finding>,
pub free_text_findings: Vec<String>,
#[serde(
default,
deserialize_with = "js::present",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(feature = "ts", ts(optional))]
pub severity: Option<Severity>,
pub comment: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "camelCase")]
pub struct Report {
pub version: ReportVersion3,
#[serde(deserialize_with = "check::non_empty")]
pub id: String,
/// ISO timestamp of report creation.
pub created_at: String,
/// ISO date of the clinical encounter.
pub date: String,
pub practitioner: Practitioner,
pub animal: Animal,
pub owner: Owner,
pub sheet: SheetRef,
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>,
/// Reserved for report-only points (OPEN_QUESTIONS Q6); empty until defined.
#[serde(default, deserialize_with = "no_local_annotations")]
#[cfg_attr(feature = "ts", ts(type = "Array<unknown>"))]
pub local_annotations: Vec<Value>,
}
/// `z.array(z.unknown()).max(0).default([])`.
fn no_local_annotations<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<Value>, D::Error> {
let items = Vec::<Value>::deserialize(d)?;
if items.is_empty() {
Ok(items)
} else {
Err(D::Error::custom("localAnnotations must be empty"))
}
}
+5
View File
@@ -0,0 +1,5 @@
//! The anatomical sheet: document contract, integrity rules, index.
pub mod schema;
pub use schema::*;
+669
View File
@@ -0,0 +1,669 @@
//! Canonical anatomical sheet document, schema_version 2
//! (`packages/domain/src/anatomical-sheet/schema.ts`, ANATOMICAL_SHEET_MODEL.md §2).
//!
//! Every object is strict as in Zod (`deny_unknown_fields`); fields are declared in the Zod
//! schema order, so a parsed document prints as `JSON.stringify(Schema.parse(x), null, 2)`.
//! Cross-references are the integrity tier (`validate.rs`), not the shape.
use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize};
#[cfg(feature = "ts")]
use ts_rs::TS;
use crate::domain::js::{self, JsInt};
pub const SHEET_DOCUMENT_SCHEMA_VERSION: u32 = 2;
/// Field checks, each one a Zod constraint of the schema.
pub(crate) mod check {
use serde::de::Error as _;
use serde::{Deserialize, Deserializer};
use crate::domain::js::{self, JsInt};
fn checked<'de, D: Deserializer<'de>>(
deserializer: D,
rule: fn(&str) -> bool,
what: &str,
) -> Result<String, D::Error> {
let text = String::deserialize(deserializer)?;
if rule(&text) {
Ok(text)
} else {
Err(D::Error::custom(format!("invalid {what}")))
}
}
pub fn non_empty<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
checked(d, js::non_empty, "empty string")
}
pub fn stable_id<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
checked(d, js::is_stable_id, "stable id")
}
pub fn region_code<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
checked(d, js::is_region_code, "region code")
}
pub fn stable_ids<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<String>, D::Error> {
let ids = Vec::<String>::deserialize(d)?;
if ids.iter().all(|id| js::is_stable_id(id)) {
Ok(ids)
} else {
Err(D::Error::custom("invalid stable id"))
}
}
pub fn non_empty_strings<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<String>, D::Error> {
let items = Vec::<String>::deserialize(d)?;
if items.iter().all(|item| !item.is_empty()) {
Ok(items)
} else {
Err(D::Error::custom("empty string"))
}
}
fn nullable_checked<'de, D: Deserializer<'de>>(
deserializer: D,
rule: fn(&str) -> bool,
what: &str,
) -> Result<Option<String>, D::Error> {
match Option::<String>::deserialize(deserializer)? {
Some(text) if !rule(&text) => Err(D::Error::custom(format!("invalid {what}"))),
other => Ok(other),
}
}
pub fn nullable_stable_id<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
nullable_checked(d, js::is_stable_id, "stable id")
}
pub fn nullable_region_code<'de, D: Deserializer<'de>>(
d: D,
) -> Result<Option<String>, D::Error> {
nullable_checked(d, js::is_region_code, "region code")
}
pub fn nullable_hex_color<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
nullable_checked(d, js::is_hex_color, "colour")
}
pub fn nullable_uuid<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
nullable_checked(d, js::is_uuid, "uuid")
}
pub fn nullable_non_empty<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
nullable_checked(d, js::non_empty, "empty string")
}
/// `z.string().url().refine(/^https?:\/\//i)`, nullable.
pub fn nullable_http_url<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
nullable_checked(d, is_reference_url, "http(s) URL")
}
fn is_reference_url(text: &str) -> bool {
let scheme = text.get(..8).unwrap_or(text).to_ascii_lowercase();
(scheme.starts_with("http://") || scheme.starts_with("https://")) && js::is_url(text)
}
/// `z.number().int().min(1)` (and `.positive()` on integers).
pub fn positive_int<'de, D: Deserializer<'de>>(d: D) -> Result<JsInt, D::Error> {
let value = JsInt::deserialize(d)?;
if value.get() >= 1.0 {
Ok(value)
} else {
Err(D::Error::custom("expected an integer of at least 1"))
}
}
/// `z.number().finite()`.
pub fn finite<'de, D: Deserializer<'de>>(d: D) -> Result<f64, D::Error> {
let value = f64::deserialize(d)?;
if value.is_finite() {
Ok(value)
} else {
Err(D::Error::custom("expected a finite number"))
}
}
/// `z.number().finite().positive()`.
pub fn positive<'de, D: Deserializer<'de>>(d: D) -> Result<f64, D::Error> {
let value = finite(d)?;
if value > 0.0 {
Ok(value)
} else {
Err(D::Error::custom("expected a positive number"))
}
}
}
use crate::domain::js::{literal, number_literal};
literal!(KindMain, "main");
literal!(KindDetail, "detail");
literal!(KindDetailTrigger, "detail_trigger");
literal!(TypeCircle, "circle");
literal!(TypePolygon, "polygon");
literal!(TypePath, "path");
number_literal!(SchemaVersion2, 2);
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct LocalizedText {
#[serde(deserialize_with = "check::non_empty")]
pub fr: String,
#[serde(deserialize_with = "check::non_empty")]
pub en: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct LocalizedOptionalText {
#[serde(
default,
deserialize_with = "js::present",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(feature = "ts", ts(optional))]
pub fr: Option<String>,
#[serde(
default,
deserialize_with = "js::present",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(feature = "ts", ts(optional))]
pub en: Option<String>,
}
/// How far the content was checked against references.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "snake_case")]
pub enum ReviewStatus {
#[default]
Inherited,
Reviewed,
ToConfirm,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct CountRange {
#[serde(deserialize_with = "check::positive_int")]
#[cfg_attr(feature = "ts", ts(type = "number"))]
pub min: JsInt,
#[serde(deserialize_with = "check::positive_int")]
#[cfg_attr(feature = "ts", ts(type = "number"))]
pub max: JsInt,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct VertebralRegion {
#[serde(deserialize_with = "check::region_code")]
pub code: String,
pub name: LocalizedText,
#[serde(deserialize_with = "check::positive_int")]
#[cfg_attr(feature = "ts", ts(type = "number"))]
pub count: JsInt,
#[serde(default)]
pub count_range: Option<CountRange>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct AnnotationCategory {
#[serde(deserialize_with = "check::stable_id")]
pub id: String,
pub name: LocalizedText,
#[serde(deserialize_with = "check::nullable_hex_color")]
pub color: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct ViewBox {
#[serde(deserialize_with = "check::finite")]
pub min_x: f64,
#[serde(deserialize_with = "check::finite")]
pub min_y: f64,
#[serde(deserialize_with = "check::positive")]
pub width: f64,
#[serde(deserialize_with = "check::positive")]
pub height: f64,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct MainView {
#[serde(deserialize_with = "check::stable_id")]
pub id: String,
pub name: LocalizedText,
#[serde(deserialize_with = "check::nullable_uuid")]
pub svg_asset_id: Option<String>,
#[serde(deserialize_with = "js::nullable")]
pub view_box: Option<ViewBox>,
pub kind: KindMain,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct DetailView {
#[serde(deserialize_with = "check::stable_id")]
pub id: String,
pub name: LocalizedText,
#[serde(deserialize_with = "check::nullable_uuid")]
pub svg_asset_id: Option<String>,
#[serde(deserialize_with = "js::nullable")]
pub view_box: Option<ViewBox>,
pub kind: KindDetail,
#[serde(deserialize_with = "check::stable_id")]
pub parent_view_id: String,
}
/// Views form a tree: a detail names its parent, any depth.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(untagged)]
pub enum SheetView {
Main(MainView),
Detail(DetailView),
}
impl SheetView {
pub fn id(&self) -> &str {
match self {
Self::Main(view) => &view.id,
Self::Detail(view) => &view.id,
}
}
pub fn name(&self) -> &LocalizedText {
match self {
Self::Main(view) => &view.name,
Self::Detail(view) => &view.name,
}
}
pub fn svg_asset_id(&self) -> Option<&str> {
match self {
Self::Main(view) => view.svg_asset_id.as_deref(),
Self::Detail(view) => view.svg_asset_id.as_deref(),
}
}
pub fn view_box(&self) -> Option<&ViewBox> {
match self {
Self::Main(view) => view.view_box.as_ref(),
Self::Detail(view) => view.view_box.as_ref(),
}
}
/// The parent of a detail view; `None` for the main view.
pub fn parent_view_id(&self) -> Option<&str> {
match self {
Self::Main(_) => None,
Self::Detail(view) => Some(&view.parent_view_id),
}
}
pub fn is_main(&self) -> bool {
matches!(self, Self::Main(_))
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct Circle {
#[serde(rename = "type")]
pub kind: TypeCircle,
#[serde(deserialize_with = "check::finite")]
pub cx: f64,
#[serde(deserialize_with = "check::finite")]
pub cy: f64,
#[serde(deserialize_with = "check::positive")]
pub r: f64,
}
/// A polygon point: a pair of finite numbers.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
pub struct Point(pub f64, pub f64);
impl<'de> Deserialize<'de> for Point {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let (x, y) = <(f64, f64)>::deserialize(deserializer)?;
if x.is_finite() && y.is_finite() {
Ok(Point(x, y))
} else {
Err(D::Error::custom("expected finite coordinates"))
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct Polygon {
#[serde(rename = "type")]
pub kind: TypePolygon,
#[serde(deserialize_with = "at_least_three")]
pub points: Vec<Point>,
}
fn at_least_three<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<Point>, D::Error> {
let points = Vec::<Point>::deserialize(d)?;
if points.len() >= 3 {
Ok(points)
} else {
Err(D::Error::custom("a polygon has at least 3 points"))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct PathGeometry {
#[serde(rename = "type")]
pub kind: TypePath,
#[serde(deserialize_with = "check::non_empty")]
pub d: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(untagged)]
pub enum Geometry {
Circle(Circle),
Polygon(Polygon),
Path(PathGeometry),
}
/// Explicit on every annotation: absence no longer carries meaning.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "snake_case")]
pub enum Laterality {
Unpaired,
Bilateral,
Left,
Right,
}
/// The two observable annotation kinds share one shape.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "snake_case")]
pub enum ObservableKind {
Point,
Zone,
}
/// A point or zone annotation: observable, linked to findings by one explicit field.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct ObservableAnnotation {
#[serde(deserialize_with = "check::stable_id")]
pub id: String,
#[serde(deserialize_with = "check::stable_id")]
pub view_id: String,
#[serde(deserialize_with = "check::stable_id")]
pub category_id: String,
pub laterality: Laterality,
#[serde(deserialize_with = "js::nullable")]
pub geometry: Option<Geometry>,
#[serde(default)]
pub review_status: ReviewStatus,
#[serde(default, deserialize_with = "check::nullable_hex_color")]
pub color: Option<String>,
pub name: LocalizedText,
#[serde(deserialize_with = "check::nullable_stable_id")]
pub finding_zone_id: Option<String>,
#[serde(deserialize_with = "check::nullable_region_code")]
pub vertebral_region_code: Option<String>,
pub kind: ObservableKind,
}
/// Navigation only: a trigger opens a detail view and never carries findings.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct DetailTriggerAnnotation {
#[serde(deserialize_with = "check::stable_id")]
pub id: String,
#[serde(deserialize_with = "check::stable_id")]
pub view_id: String,
#[serde(deserialize_with = "check::stable_id")]
pub category_id: String,
pub laterality: Laterality,
#[serde(deserialize_with = "js::nullable")]
pub geometry: Option<Geometry>,
#[serde(default)]
pub review_status: ReviewStatus,
#[serde(default, deserialize_with = "check::nullable_hex_color")]
pub color: Option<String>,
pub kind: KindDetailTrigger,
#[serde(deserialize_with = "js::nullable")]
pub name: Option<LocalizedText>,
#[serde(deserialize_with = "check::stable_id")]
pub opens_view_id: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(untagged)]
pub enum Annotation {
Observable(ObservableAnnotation),
DetailTrigger(DetailTriggerAnnotation),
}
impl Annotation {
pub fn id(&self) -> &str {
match self {
Self::Observable(a) => &a.id,
Self::DetailTrigger(a) => &a.id,
}
}
pub fn view_id(&self) -> &str {
match self {
Self::Observable(a) => &a.view_id,
Self::DetailTrigger(a) => &a.view_id,
}
}
pub fn category_id(&self) -> &str {
match self {
Self::Observable(a) => &a.category_id,
Self::DetailTrigger(a) => &a.category_id,
}
}
pub fn observable(&self) -> Option<&ObservableAnnotation> {
match self {
Self::Observable(a) => Some(a),
Self::DetailTrigger(_) => None,
}
}
pub fn trigger(&self) -> Option<&DetailTriggerAnnotation> {
match self {
Self::Observable(_) => None,
Self::DetailTrigger(a) => Some(a),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "snake_case")]
pub enum ReferenceType {
Book,
Journal,
Standard,
Legal,
Web,
Manual,
}
/// One bibliographic reference, declared once and cited by id.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct Reference {
#[serde(deserialize_with = "check::stable_id")]
pub id: String,
#[serde(rename = "type")]
pub kind: ReferenceType,
#[serde(deserialize_with = "check::non_empty")]
pub citation: String,
#[serde(default, deserialize_with = "check::nullable_http_url")]
pub url: Option<String>,
#[serde(default, deserialize_with = "check::nullable_non_empty")]
pub doi: Option<String>,
}
/// A finding node; every optional key of the authoring form is filled in when parsed.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct FindingNode {
#[serde(deserialize_with = "check::stable_id")]
pub id: String,
pub name: LocalizedText,
#[serde(default)]
pub description: LocalizedOptionalText,
#[serde(default)]
pub requires_vet_referral: bool,
#[serde(default, deserialize_with = "check::stable_ids")]
pub reference_ids: Vec<String>,
#[serde(default)]
pub review_status: ReviewStatus,
#[serde(default)]
pub children: Vec<FindingNode>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "snake_case")]
pub enum FindingCategoryKind {
Dysfunction,
ConsultationReason,
Anamnesis,
Custom,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct FindingCategory {
#[serde(deserialize_with = "check::stable_id")]
pub id: String,
pub kind: FindingCategoryKind,
pub name: LocalizedText,
#[serde(default)]
pub description: LocalizedOptionalText,
#[serde(default, deserialize_with = "check::stable_ids")]
pub reference_ids: Vec<String>,
#[serde(default)]
pub review_status: ReviewStatus,
pub children: Vec<FindingNode>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct FindingZone {
#[serde(deserialize_with = "check::stable_id")]
pub id: String,
pub name: LocalizedText,
pub categories: Vec<FindingCategory>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct Attribution {
#[serde(deserialize_with = "check::non_empty_strings")]
pub authors: Vec<String>,
#[serde(deserialize_with = "check::nullable_non_empty")]
pub license: Option<String>,
#[serde(deserialize_with = "check::nullable_non_empty")]
pub notes: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct VertebralConfig {
pub regions: Vec<VertebralRegion>,
}
/// The canonical sheet document (schema_version 2).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct AnatomicalSheetDocument {
pub schema_version: SchemaVersion2,
#[serde(deserialize_with = "check::stable_id")]
pub species_id: String,
pub name: LocalizedText,
pub description: LocalizedOptionalText,
pub scope_disclaimer: LocalizedOptionalText,
pub attribution: Attribution,
pub vertebral_config: VertebralConfig,
pub references: Vec<Reference>,
pub categories: Vec<AnnotationCategory>,
pub views: Vec<SheetView>,
pub annotations: Vec<Annotation>,
pub finding_zones: Vec<FindingZone>,
}
/// A category or a node of a finding tree: what `nodeAt` returns.
pub enum FindingTreeItem<'a> {
Category(&'a FindingCategory),
Node(&'a FindingNode),
}
impl<'a> FindingTreeItem<'a> {
pub fn id(&self) -> &'a str {
match self {
Self::Category(c) => &c.id,
Self::Node(n) => &n.id,
}
}
pub fn name(&self) -> &'a LocalizedText {
match self {
Self::Category(c) => &c.name,
Self::Node(n) => &n.name,
}
}
pub fn children(&self) -> &'a [FindingNode] {
match self {
Self::Category(c) => &c.children,
Self::Node(n) => &n.children,
}
}
/// Categories carry no vet flag (`'requires_vet_referral' in leaf` is false for them).
pub fn requires_vet_referral(&self) -> bool {
match self {
Self::Category(_) => false,
Self::Node(n) => n.requires_vet_referral,
}
}
}
+25
View File
@@ -0,0 +1,25 @@
//! Shared helpers of the core integration tests: repository files and the Zod oracles.
#![allow(
dead_code,
clippy::disallowed_methods,
clippy::unwrap_used,
clippy::expect_used
)]
use serde_json::Value;
/// A repository file, by path from the repository root.
pub fn repo_file(relative: &str) -> String {
let path = format!("{}/../../{relative}", env!("CARGO_MANIFEST_DIR"));
std::fs::read_to_string(&path).unwrap_or_else(|error| panic!("{path}: {error}"))
}
/// A Zod oracle (`crates/core/tests/oracles/<name>`): its source file and the Zod output in
/// the JavaScript pretty form.
pub fn zod_oracle(name: &str) -> (String, String) {
let oracle: Value =
serde_json::from_str(&repo_file(&format!("crates/core/tests/oracles/{name}"))).unwrap();
let source = oracle["source"].as_str().unwrap().to_owned();
let output = faunosteo_core::json::to_js_pretty(&oracle["output"]).unwrap();
(repo_file(&source), output)
}
@@ -0,0 +1 @@
{"source":"supabase/seed/anatomical-sheets/equine/draft/report-migration-map.json","output":{"schema_version":1,"sheet":{"sheetId":"503dc301-a8b1-50d4-9e44-0919b2fc2916","versionId":null,"documentSha256":"27c7383c445c73dc2001ebf4794a3ea63d416910bbbaa0d7848dd720de7c2660"},"main_view_id":"main","views":{"head":"head"},"annotations":{"point-mpbwrkp0":{"id":"hind-fetlock","name":{"fr":"Boulet post. (métatarso-phalangien)","en":"Hind fetlock"}},"point-mpbwsi9q":{"id":"hock","name":{"fr":"Jarret (tarsien)","en":"Hock"}},"point-mpbwt4fa":{"id":"stifle","name":{"fr":"Grasset (fémoro-tibial)","en":"Stifle"}},"point-mpbwtst0":{"id":"hip","name":{"fr":"Hanche (coxo-fémorale)","en":"Hip joint"}},"point-mpbwugty":{"id":"sacroiliac","name":{"fr":"Articulation Sacro-Iliaque","en":"Sacroiliac Joint"}},"point-mpbwv4xy":{"id":"shoulder","name":{"fr":"Épaule (scapulo-humérale)","en":"Shoulder joint"}},"point-mpbwvpvt":{"id":"elbow","name":{"fr":"Coude (huméro-radial)","en":"Elbow joint"}},"point-mpbwwaru":{"id":"fore-fetlock","name":{"fr":"Boulet ant. (métacarpo-phalangien)","en":"Fore fetlock"}},"point-mpbwwxvn":{"id":"fore-sesamoids","name":{"fr":"Sésamoïdes ant. (boulet)","en":"Forelimb Sesamoids"}},"point-mpbwxnb4":{"id":"l6-s1","name":{"fr":"Charnière L6-S1 (lombo-sacrée)","en":"L6-S1 (Lumbosacral)"}},"point-mpbwyd9i":{"id":"t18-l1","name":{"fr":"Charnière T18-L1 (dorso-lombaire)","en":"T18-L1 (Thoracolumbar)"}},"point-mpbwyyc9":{"id":"c7-t1","name":{"fr":"Charnière C7-T1 (cervico-thoracique)","en":"C7-T1 (Cervicothoracic)"}},"zone-mpbx00jq":{"id":"caudal","name":{"fr":"Vertèbres caudales","en":"Coccygeal Vertebrae"}},"zone-mpbx0xnp":{"id":"sacral","name":{"fr":"Vertèbres sacrales","en":"Sacral Vertebrae"}},"zone-mpbx1rm9":{"id":"lumbar","name":{"fr":"Vertèbres lombaires","en":"Lumbar Vertebrae"}},"zone-mpbx2rpe":{"id":"thoracic","name":{"fr":"Vertèbres thoraciques","en":"Thoracic Vertebrae"}},"zone-mpbx5hx2":{"id":"cervical","name":{"fr":"Vertèbres cervicales","en":"Cervical Vertebrae"}},"zone-mpby55kd":{"id":"head-trigger","name":{"fr":"","en":""}},"point-mpbykomv":{"id":"parietal","name":{"fr":"Pariétal","en":"Parietal bone"}},"point-mpbylh35":{"id":"frontal","name":{"fr":"Frontal","en":"Frontal bone"}},"point-mpbymcln":{"id":"sphenoid","name":{"fr":"Sphénoïde","en":"Sphenoid"}},"point-mpbyn2k3":{"id":"temporal","name":{"fr":"Temporel","en":"Temporal"}},"point-mpbynls5":{"id":"occipital","name":{"fr":"Occipital","en":"Occipital"}},"point-mpbyo7zq":{"id":"atm","name":{"fr":"Articulation Temporo-Mandibulaire (ATM)","en":"Temporomandibular Joint (TMJ)"}},"point-mpbyphay":{"id":"ssb","name":{"fr":"Synchondrose Sphéno-Basilaire (SSB)","en":"Spheno-Basilar Synchondrosis (SBS)"}},"point-mpbyq841":{"id":"hyoid","name":{"fr":"Hyoïde","en":"Hyoid"}},"point-mpbyqxbg":{"id":"c0-c1","name":{"fr":"Charnière C0-C1 (occipito-atloïdienne)","en":"C0-C1 (Occipito-atlantal)"}}},"finding_paths":{"parietal/parietal-dysfunctions":"parietal/parietal-dysfunctions","parietal/parietal-dysfunctions/mobility":"parietal/parietal-dysfunctions/mobility","parietal/parietal-dysfunctions/mobility/flexion-external-rotation":"parietal/parietal-dysfunctions/mobility/flexion-external-rotation","parietal/parietal-dysfunctions/mobility/extension-internal-rotation":"parietal/parietal-dysfunctions/mobility/extension-internal-rotation","parietal/parietal-dysfunctions/mobility/global-restriction":"parietal/parietal-dysfunctions/mobility/global-restriction","parietal/parietal-dysfunctions/intraosseous":"parietal/parietal-dysfunctions/intraosseous","parietal/parietal-dysfunctions/intraosseous/squama-deformation":"parietal/parietal-dysfunctions/intraosseous/squama-deformation","parietal/parietal-dysfunctions/intraosseous/interparietal-compression":"parietal/parietal-dysfunctions/intraosseous/interparietal-compression","parietal/parietal-dysfunctions/sutures":"parietal/parietal-dysfunctions/sutures","parietal/parietal-dysfunctions/sutures/frontoparietal":"parietal/parietal-dysfunctions/sutures/frontoparietal","parietal/parietal-dysfunctions/sutures/parieto-occipital":"parietal/parietal-dysfunctions/sutures/parieto-occipital","parietal/parietal-dysfunctions/sutures/parieto-temporal":"parietal/parietal-dysfunctions/sutures/parieto-temporal","parietal/parietal-dysfunctions/sutures/sphenoparietal":"parietal/parietal-dysfunctions/sutures/sphenoparietal","parietal/parietal-dysfunctions/sutures/interparietal":"parietal/parietal-dysfunctions/sutures/sagittal","parietal/parietal-observations":"parietal/parietal-consultation-reasons","parietal/parietal-observations/behavior-change":"parietal/parietal-consultation-reasons/behavior-change","parietal/parietal-observations/behavior-change/head-touch-hypersensitivity":"parietal/parietal-consultation-reasons/behavior-change/head-touch-hypersensitivity","parietal/parietal-observations/behavior-change/new-irritability":"parietal/parietal-consultation-reasons/behavior-change/new-irritability","parietal/parietLine truncated
@@ -0,0 +1 @@
{"source":"apps/app/tests/fixtures/report-v2.full.json","output":{"version":2,"id":"fixture-full-v2","createdAt":"2026-06-01T09:00:00.000Z","date":"2026-06-01","practitioner":{"name":"Dr. Claire Dupont","cabinet":"Cabinet Équi-Ostéo","contact":"claire@example.test","siret":"12345678901234"},"animal":{"speciesId":"equine","name":"Mistral","breed":"Selle Français","age":"9 ans"},"owner":{"name":"Jean Martin"},"observations":[{"id":"obs-1","zones":[{"boneId":"point-mpbwyyc9"},{"boneId":"point-mpbwtst0","side":"left"},{"boneId":"point-mpbwtst0","side":"right"}],"findings":[{"zoneId":"c7-t1","path":["c7-t1-dysfunctions","segmental","fixation"],"labelFrSnapshot":"Fixation de la charnière","labelEnSnapshot":"Junction fixation"},{"zoneId":"hip","path":["hip-dysfunctions","articular","restriction-flexion"],"labelFrSnapshot":"Restriction en flexion","labelEnSnapshot":"Flexion restriction","side":"left"}],"freeTextFindings":["Sensibilité au garrot"],"severity":"modérée","comment":"Réagit à la palpation du garrot."},{"id":"obs-2","zones":[{"boneId":"zone-mpbx5hx2","vertebrae":[{"region":"C","index":3},{"region":"C","index":4}]}],"findings":[{"zoneId":"cervical","path":["cervical-observations","stumbling-proprioceptive"],"labelFrSnapshot":"Trébuchements / déficit proprioceptif rapporté","labelEnSnapshot":"Reported stumbling / proprioceptive deficit","requiresVetReferral":true}],"freeTextFindings":[],"severity":"sévère","comment":""},{"id":"obs-3","zones":[{"boneId":"point-mpbyo7zq","detailSourceId":"head"}],"findings":[{"zoneId":"atm","path":["atm-observations","headshaking"],"labelFrSnapshot":"Headshaking (secouement de tête)","labelEnSnapshot":"Headshaking","requiresVetReferral":true}],"freeTextFindings":[],"comment":"Vue détail tête."}],"conclusion":"Dysfonction cervico-thoracique avec compensation du bassin.","recommendations":"Repos 3 jours puis reprise progressive.","nextAppointment":{"kind":"date","date":"2026-07-01"}}}
@@ -0,0 +1 @@
{"source":"apps/app/tests/fixtures/report-v2.minimal.json","output":{"version":2,"id":"fixture-minimal-v2","createdAt":"2026-06-01T09:00:00.000Z","date":"2026-06-01","practitioner":{"name":"Dr. Dupont"},"animal":{"speciesId":"equine","name":"Mistral"},"owner":{"name":"Jean Martin"},"observations":[],"conclusion":"","recommendations":""}}
@@ -0,0 +1 @@
{"source":"apps/app/tests/fixtures/report-v3.demo.json","output":{"version":3,"id":"fixture-demo-v3","createdAt":"2026-10-11T09:30:00.000Z","date":"2026-10-11","practitioner":{"name":"Dr. Claire Dupont","cabinet":"Cabinet Équi-Ostéo","contact":"claire@example.test","siret":"12345678901234"},"animal":{"speciesId":"equine","name":"Mistral","breed":"Selle Français","age":"9 ans"},"owner":{"name":"Jean Martin"},"sheet":{"sheetId":"503dc301-a8b1-50d4-9e44-0919b2fc2916","versionId":null,"documentSha256":"27c7383c445c73dc2001ebf4794a3ea63d416910bbbaa0d7848dd720de7c2660"},"observations":[{"id":"obs-demo-1","zones":[{"annotationId":"c7-t1","viewId":"main","labelFrSnapshot":"Charnière C7-T1 (cervico-thoracique)","labelEnSnapshot":"C7-T1 junction (cervicothoracic)"},{"annotationId":"t18-l1","viewId":"main","labelFrSnapshot":"Charnière T18-L1 (thoraco-lombaire)","labelEnSnapshot":"T18-L1 junction (thoracolumbar)"}],"findings":[{"findingZoneId":"c7-t1","path":["c7-t1-dysfunctions","segmental","restriction-flexion"],"labelFrSnapshot":"Restriction en flexion","labelEnSnapshot":"Flexion restriction"},{"findingZoneId":"c7-t1","path":["c7-t1-dysfunctions","segmental","restriction-extension"],"labelFrSnapshot":"Restriction en extension","labelEnSnapshot":"Extension restriction"}],"freeTextFindings":[],"severity":"mild","comment":"Réagit à la palpation de la charnière."},{"id":"obs-demo-2","zones":[{"annotationId":"hip","viewId":"main","side":"left","labelFrSnapshot":"Hanche (coxo-fémorale)","labelEnSnapshot":"Hip joint"},{"annotationId":"hip","viewId":"main","side":"right","labelFrSnapshot":"Hanche (coxo-fémorale)","labelEnSnapshot":"Hip joint"}],"findings":[{"findingZoneId":"hip","path":["hip-dysfunctions","articular","restriction-flexion"],"labelFrSnapshot":"Restriction en flexion","labelEnSnapshot":"Flexion restriction","side":"left"},{"findingZoneId":"hip","path":["hip-dysfunctions","articular","restriction-abduction-adduction"],"labelFrSnapshot":"Restriction en abduction / adduction","labelEnSnapshot":"Abduction / adduction restriction","side":"right"}],"freeTextFindings":[],"severity":"moderate","comment":""},{"id":"obs-demo-3","zones":[{"annotationId":"cervical","viewId":"main","vertebrae":[{"region":"C","index":3},{"region":"C","index":4}],"labelFrSnapshot":"Vertèbres cervicales","labelEnSnapshot":"Cervical vertebrae"}],"findings":[{"findingZoneId":"cervical","path":["cervical-dysfunctions","segmental","localized-fixation"],"labelFrSnapshot":"Fixation segmentaire localisée (C2–C7)","labelEnSnapshot":"Localized segmental fixation (C2–C7)"}],"freeTextFindings":[],"severity":"severe","comment":"Fixation nette en latéroflexion droite."},{"id":"obs-demo-4","zones":[{"annotationId":"atm","viewId":"head","labelFrSnapshot":"Articulation temporo-mandibulaire (ATM)","labelEnSnapshot":"Temporomandibular joint (TMJ)"},{"annotationId":"frontal","viewId":"head","labelFrSnapshot":"Frontal","labelEnSnapshot":"Frontal bone"}],"findings":[{"findingZoneId":"frontal","path":["frontal-consultation-reasons","head-rubbing"],"labelFrSnapshot":"Frottements répétés de la tête rapportés","labelEnSnapshot":"Reported repeated head rubbing","requiresVetReferral":true},{"findingZoneId":"atm","path":["atm-dysfunctions","articular","restriction-opening"],"labelFrSnapshot":"Restriction à l'ouverture","labelEnSnapshot":"Opening restriction"}],"freeTextFindings":[],"comment":""},{"id":"obs-demo-5","zones":[{"annotationId":"sacroiliac","viewId":"main","side":"right","labelFrSnapshot":"Articulation sacro-iliaque","labelEnSnapshot":"Sacroiliac joint"},{"annotationId":"occipital","viewId":"head","labelFrSnapshot":"Occipital","labelEnSnapshot":"Occipital bone"}],"findings":[],"freeTextFindings":["Sensibilité au garrot","Tension du ligament nuchal"],"severity":"mild","comment":"Compensation probable."},{"id":"obs-demo-6","zones":[{"annotationId":"lumbar","viewId":"main","vertebrae":[{"region":"L","index":2},{"region":"L","index":3}],"labelFrSnapshot":"Vertèbres lombaires","labelEnSnapshot":"Lumbar vertebrae"},{"annotationId":"l6-s1","viewId":"main","labelFrSnapshot":"Charnière L6-S1 (lombo-sacrée)","labelEnSnapshot":"L6-S1 junction (lumbosacral joint)"}],"findings":[{"findingZoneId":"lumbar","path":["lumbar-dysfunctions","segmental","restriction-extension"],"labelFrSnapshot":"Restriction en extension","labelEnSnapshot":"Extension restriction"}],"freeTextFindings":["Raideur lombaire au pas"],"comment":""}],"conclusion":"Dysfonction cervico-thoracique avec compensation du bassin et tension crânienne associée.","recommendations":"Repos 3 jours puis reprise progressive ; contrôle vétérinaire pour les frottements de tête.","nextAppointment":{"kind":"period","text":"6 à 8 semaines"},"localAnnotations":[]}}
@@ -0,0 +1 @@
{"source":"supabase/seed/anatomical-sheets/equine/draft/document.json","output":{"schema_version":2,"species_id":"equine","name":{"fr":"Cheval","en":"Horse"},"description":{"fr":"Fiche anatomique officielle Faunosteo du cheval (Equus caballus)","en":"Official Faunosteo anatomical sheet of the horse (Equus caballus)"},"scope_disclaimer":{"fr":"Les éléments listés relèvent du périmètre légal de l'ostéopathie animale (art. L. 243-3 12° et R. 243-6 du Code rural et de la pêche maritime) : dysfonctions ostéopathiques palpées, observations cliniques et motifs de consultation rapportés. Aucun diagnostic médical n'est posé. Toute pathologie organique relève du vétérinaire ; conformément à l'art. R. 243-8, le propriétaire est orienté vers un vétérinaire lorsque les symptômes ou lésions nécessitent un diagnostic ou un traitement médical, persistent ou s'aggravent.","en":"The items listed fall within the legal scope of animal osteopathy in France (Articles L. 243-3 (12°) and R. 243-6 of the Code rural et de la pêche maritime): palpated osteopathic dysfunctions, clinical observations and reported reasons for consultation. No medical diagnosis is made. Any organic disease is a matter for a veterinarian; under Article R. 243-8 the owner is referred to a veterinarian whenever symptoms or lesions require a medical diagnosis or treatment, persist or worsen."},"attribution":{"authors":["Faunosteo"],"license":null,"notes":"Import des données historiques: Horse.svg, Horse_head.svg, pathologies.json (schema 2.0)"},"vertebral_config":{"regions":[{"code":"C","name":{"fr":"Cervicales","en":"Cervical"},"count":7,"count_range":null},{"code":"T","name":{"fr":"Thoraciques","en":"Thoracic"},"count":18,"count_range":{"min":17,"max":19}},{"code":"L","name":{"fr":"Lombaires","en":"Lumbar"},"count":6,"count_range":{"min":5,"max":6}},{"code":"S","name":{"fr":"Sacrales","en":"Sacral"},"count":5,"count_range":null},{"code":"Cd","name":{"fr":"Caudales","en":"Caudal"},"count":18,"count_range":{"min":15,"max":21}}]},"references":[{"id":"legacy-catalog","type":"manual","citation":"Catalogue historique Faunosteo (pathologies.json, schéma 2.0), import du 2026-10-09","url":null,"doi":null},{"id":"cr-l243-3","type":"legal","citation":"Code rural et de la pêche maritime, art. L. 243-3 12° (dérogation : actes d'ostéopathie animale ; texte consolidé non rouvert sur Légifrance, article confirmé par la réponse ministérielle QE 8187 et le CNOV)","url":"https://www.legifrance.gouv.fr/codes/article_lc/LEGIARTI000033449047","doi":null},{"id":"decret-2017-572","type":"legal","citation":"Décret n° 2017-572 du 19 avril 2017 relatif aux actes d'ostéopathie animale","url":"https://www.legifrance.gouv.fr/jorf/id/JORFTEXT000034450108","doi":null},{"id":"nav-2017","type":"standard","citation":"International Committee on Veterinary Gross Anatomical Nomenclature. Nomina Anatomica Veterinaria, 6e éd., 2017 (WAVA). Osteologia p. 11-16 (ossa cranii, os hyoideum), Arthrologia (suturae capitis, synchondroses cranii)","url":"https://www.vetmed.uni-leipzig.de/fileadmin/Fakult%C3%A4t_VMF/Institut_Veterin%C3%A4r-Anatomisches/Dokumente/NAV_6th-Edition-2017.pdf","doi":null},{"id":"sisson-1914","type":"book","citation":"Sisson S. The Anatomy of the Domestic Animals. Philadelphia : W.B. Saunders, 1914 (texte intégral ; éditions révisées Grossman 1953, Getty 1975). Crâne du cheval p. 52-69, hyoïde p. 70-71, articulations de la tête p. 214-217, muscles de la mandibule et de l'hyoïde p. 261-266","url":"https://archive.org/stream/anatomyofdomesti01siss/anatomyofdomesti01siss_djvu.txt","doi":null},{"id":"umn-large-animal","type":"web","citation":"University of Minnesota. Large Animal Anatomy (manuel ouvert), chapitre « Neck & Head », consulté le 2026-10-10","url":"https://open.lib.umn.edu/largeanimalanatomy/chapter/neck-head/","doi":null},{"id":"lim-2013","type":"journal","citation":"Lim CK, Saulez MN, Viljoen A, Carstens A. Basilar skull fracture in a Thoroughbred colt: radiography or computed tomography? J S Afr Vet Assoc 2013;84(1), art. 19","url":"https://scielo.org.za/scielo.php?script=sci_arttext&pid=S1019-91282013000100032","doi":null},{"id":"who-2010","type":"standard","citation":"Organisation mondiale de la Santé. Benchmarks for training in osteopathy. Genève : OMS, 2010. ISBN 978 92 4 159966 5 (section 1.2, « somatic dysfunction »)","url":"https://oialliance.org/wp-content/uploads/2024/02/BenchmarksforTraininginOsteopathy-1.pdf","doi":null},{"id":"guillaud-2016","type":"journal","citation":"Guillaud A, Darbois N, Monvoisin R, Pinsault N. Reliability of diagnosis and clinical efficacy of cranial osteopathy: a systematic review. PLoS ONE 2016;11(12):e0167823","url":"https://doi.org/10.1371/journal.pone.0167823","doi":"10.1371/journal.pone.0167823"},{"id":"jakel-2011","type":"journal","citation":"Jäkel A, von Hauenschild P. Therapeutic effects of cranial osteopathic manipulative medicine: a systematic review. J Am OsteLine truncated
@@ -0,0 +1 @@
{"source":"supabase/seed/anatomical-sheets/equine/legacy-import/document.json","output":{"schema_version":2,"species_id":"equine","name":{"fr":"Cheval","en":"Horse"},"description":{"fr":"Fiche anatomique officielle Faunosteo","en":"Official Faunosteo anatomical sheet"},"scope_disclaimer":{"fr":"Les éléments listés correspondent au périmètre légal de l'ostéopathie animale : dysfonctions ostéopathiques palpées, observations cliniques et motifs de consultation. Aucun diagnostic médical n'est posé. Toute pathologie organique relève du vétérinaire."},"attribution":{"authors":["Faunosteo"],"license":null,"notes":"Import des données historiques: Horse.svg, Horse_head.svg, pathologies.json (schema 2.0)"},"vertebral_config":{"regions":[{"code":"C","name":{"fr":"Cervicales","en":"Cervical"},"count":7,"count_range":null},{"code":"T","name":{"fr":"Thoraciques","en":"Thoracic"},"count":18,"count_range":null},{"code":"L","name":{"fr":"Lombaires","en":"Lumbar"},"count":6,"count_range":null},{"code":"S","name":{"fr":"Sacrales","en":"Sacral"},"count":5,"count_range":null},{"code":"Cd","name":{"fr":"Caudales","en":"Caudal"},"count":18,"count_range":null}]},"references":[],"categories":[{"id":"articulations","name":{"fr":"Articulations","en":"Joints"},"color":null},{"id":"os","name":{"fr":"Os","en":"Bones"},"color":null},{"id":"charnieres-vertebrales","name":{"fr":"Charnières vertébrales","en":"Vertebral hinges"},"color":null},{"id":"zone-colonne","name":{"fr":"Zone colonne","en":"Spine"},"color":null},{"id":"cadrans-du-crane","name":{"fr":"Cadrans du crâne","en":"Skull quadrants"},"color":null}],"views":[{"id":"main","name":{"fr":"Vue générale","en":"Overview"},"svg_asset_id":"8bc2cd09-5fca-54c6-a78e-bdd3f6abaa3a","view_box":null,"kind":"main"},{"id":"head","name":{"fr":"Tête","en":"Head"},"svg_asset_id":"5043348c-b84b-50c3-bbf8-01ff539d163c","view_box":null,"kind":"detail","parent_view_id":"main"}],"annotations":[{"id":"hind-fetlock","view_id":"main","category_id":"articulations","laterality":"bilateral","geometry":{"type":"circle","cx":1523,"cy":1397,"r":34},"review_status":"inherited","color":null,"name":{"fr":"Boulet post. (métatarso-phalangien)","en":"Hind fetlock"},"finding_zone_id":"hind-fetlock","vertebral_region_code":null,"kind":"point"},{"id":"hock","view_id":"main","category_id":"articulations","laterality":"bilateral","geometry":{"type":"circle","cx":1542,"cy":1159,"r":34},"review_status":"inherited","color":null,"name":{"fr":"Jarret (tarsien)","en":"Hock"},"finding_zone_id":"hock","vertebral_region_code":null,"kind":"point"},{"id":"stifle","view_id":"main","category_id":"articulations","laterality":"bilateral","geometry":{"type":"circle","cx":1464,"cy":918,"r":34},"review_status":"inherited","color":null,"name":{"fr":"Grasset (fémoro-tibial)","en":"Stifle"},"finding_zone_id":"stifle","vertebral_region_code":null,"kind":"point"},{"id":"hip","view_id":"main","category_id":"articulations","laterality":"bilateral","geometry":{"type":"circle","cx":1516,"cy":695,"r":34},"review_status":"inherited","color":null,"name":{"fr":"Hanche (coxo-fémorale)","en":"Hip joint"},"finding_zone_id":"hip","vertebral_region_code":null,"kind":"point"},{"id":"sacroiliac","view_id":"main","category_id":"articulations","laterality":"bilateral","geometry":{"type":"circle","cx":1590,"cy":606,"r":34},"review_status":"inherited","color":null,"name":{"fr":"Articulation Sacro-Iliaque","en":"Sacroiliac Joint"},"finding_zone_id":"sacroiliac","vertebral_region_code":null,"kind":"point"},{"id":"shoulder","view_id":"main","category_id":"articulations","laterality":"bilateral","geometry":{"type":"circle","cx":784,"cy":907,"r":34},"review_status":"inherited","color":null,"name":{"fr":"Épaule (scapulo-humérale)","en":"Shoulder joint"},"finding_zone_id":"shoulder","vertebral_region_code":null,"kind":"point"},{"id":"elbow","view_id":"main","category_id":"articulations","laterality":"bilateral","geometry":{"type":"circle","cx":743.0451049804688,"cy":1193,"r":34},"review_status":"inherited","color":null,"name":{"fr":"Coude (huméro-radial)","en":"Elbow joint"},"finding_zone_id":"elbow","vertebral_region_code":null,"kind":"point"},{"id":"fore-fetlock","view_id":"main","category_id":"articulations","laterality":"bilateral","geometry":{"type":"circle","cx":736,"cy":1379,"r":34},"review_status":"inherited","color":null,"name":{"fr":"Boulet ant. (métacarpo-phalangien)","en":"Fore fetlock"},"finding_zone_id":"fore-fetlock","vertebral_region_code":null,"kind":"point"},{"id":"fore-sesamoids","view_id":"main","category_id":"os","laterality":"bilateral","geometry":{"type":"circle","cx":784,"cy":1371,"r":34},"review_status":"inherited","color":null,"name":{"fr":"Sésamoïdes ant. (boulet)","en":"Forelimb Sesamoids"},"finding_zone_id":"fore-sesamoids","vertebral_region_code":null,"kind":"point"},{"id":"l6-s1","view_id":"main","category_id":"charnieres-vertebrales","laterality":"unpaired","geometry":{"type":"circle","cx":1424.2662353515625,"Line truncated
+41
View File
@@ -0,0 +1,41 @@
//! Report contracts against the Zod oracles.
#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
mod common;
use faunosteo_core::domain::js::parse_json;
use faunosteo_core::domain::report::v2::ReportV2;
use faunosteo_core::domain::report::{Report, ReportMigrationMap};
use faunosteo_core::json::to_js_pretty;
#[test]
fn the_demo_report_prints_as_zod_outputs_it() {
let (source, expected) = common::zod_oracle("report-v3.demo.json");
let report: Report = serde_json::from_value(parse_json(&source).unwrap()).unwrap();
assert_eq!(to_js_pretty(&report).unwrap(), expected);
}
#[test]
fn the_v2_fixtures_and_the_migration_map_parse() {
for name in ["report-v2.full.json", "report-v2.minimal.json"] {
let (source, _) = common::zod_oracle(name);
let parsed: Result<ReportV2, _> = serde_json::from_value(parse_json(&source).unwrap());
assert!(parsed.is_ok(), "{name}: {parsed:?}");
}
let (source, _) = common::zod_oracle("migration-map.draft.json");
let map: ReportMigrationMap = serde_json::from_value(parse_json(&source).unwrap()).unwrap();
assert!(map.annotations.len() > 20 && map.finding_paths.len() > 600);
}
#[test]
fn the_frozen_envelopes_parse_and_print_as_their_attachment() {
use faunosteo_core::domain::archive::ReportArchiveEnvelope;
for name in ["demo", "v2full", "v2unresolved"] {
let text = common::repo_file(&format!(
"apps/app/tests/fixtures/goldens/r2/envelope.{name}.fr.nologos.json"
));
let envelope: ReportArchiveEnvelope =
serde_json::from_value(parse_json(&text).unwrap()).unwrap();
assert_eq!(to_js_pretty(&envelope).unwrap(), text, "{name}");
}
}
+26
View File
@@ -0,0 +1,26 @@
//! The sheet document contract against the Zod oracles: the reference documents parse and
//! print byte for byte as `JSON.stringify(AnatomicalSheetDocumentSchema.parse(x), null, 2)`.
#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
mod common;
use faunosteo_core::domain::js::parse_json;
use faunosteo_core::domain::sheet::AnatomicalSheetDocument;
use faunosteo_core::json::to_js_pretty;
fn assert_like_zod(oracle: &str) {
let (source, expected) = common::zod_oracle(oracle);
let document: AnatomicalSheetDocument =
serde_json::from_value(parse_json(&source).unwrap()).unwrap();
assert_eq!(to_js_pretty(&document).unwrap(), expected, "{oracle}");
}
#[test]
fn the_curated_draft_prints_as_zod_outputs_it() {
assert_like_zod("sheet.draft.json");
}
#[test]
fn the_legacy_import_baseline_prints_as_zod_outputs_it() {
assert_like_zod("sheet.legacy-import.json");
}