Skip to main content

zero_client/protocol/
valita.rs

1//! A small interpreter of valita schemas (`packages/shared/src/valita.ts`),
2//! for messages kept as JSON rather than decoded into Rust types.
3//!
4//! [`Schema::parse`] accepts what valita accepts in `passthrough` mode and
5//! returns what it returns in `strip` mode: objects lose the keys their
6//! schema doesn't name. A union picks its first option that accepts.
7
8use super::literal;
9use crate::decode::{self, DecodeError, Reader, Result};
10use crate::json::{Object, Value};
11
12#[derive(Clone)]
13pub enum Schema {
14    String,
15    Number,
16    Boolean,
17    Null,
18    /// `v.unknown()` and `jsonSchema`.
19    Any,
20    Literal(&'static str),
21    Array(Box<Schema>),
22    /// `v.tuple([s]).concat(v.array(s))`.
23    NonEmptyArray(Box<Schema>),
24    Tuple(Vec<Schema>),
25    Record(Box<Schema>),
26    Object(Vec<(&'static str, Field)>),
27    Union(Vec<Schema>),
28    Nullable(Box<Schema>),
29    /// A schema with a Rust decoder; returns the decoded value's JSON.
30    Custom(fn(&Value) -> Result<Value>),
31}
32
33#[derive(Clone)]
34pub enum Field {
35    Required(Schema),
36    Optional(Schema),
37}
38
39impl Schema {
40    pub fn parse(&self, v: &Value) -> Result<Value> {
41        match self {
42            Schema::String => decode::string(v).map(|_| v.clone()),
43            Schema::Number => decode::number(v).map(|_| v.clone()),
44            Schema::Boolean => decode::bool(v).map(|_| v.clone()),
45            Schema::Null if v.is_null() => Ok(Value::Null),
46            Schema::Null => Err(DecodeError::new(format!(
47                "Expected null, got {}",
48                v.type_name()
49            ))),
50            Schema::Any => Ok(v.clone()),
51            Schema::Literal(expected) => literal(v, expected).map(|()| v.clone()),
52            Schema::Array(e) => decode::array(v, |x| e.parse(x)).map(Value::Array),
53            Schema::NonEmptyArray(e) => {
54                let a = decode::array(v, |x| e.parse(x))?;
55                if a.is_empty() {
56                    return Err(DecodeError::new("Expected non-empty array"));
57                }
58                Ok(Value::Array(a))
59            }
60            Schema::Tuple(elements) => {
61                let a = decode::array_value(v)?;
62                if a.len() != elements.len() {
63                    return Err(DecodeError::new(format!(
64                        "Expected array of length {}, got {}",
65                        elements.len(),
66                        a.len()
67                    )));
68                }
69                a.iter()
70                    .zip(elements)
71                    .enumerate()
72                    .map(|(i, (e, s))| s.parse(e).map_err(|err| err.at(i.to_string())))
73                    .collect::<Result<_>>()
74                    .map(Value::Array)
75            }
76            Schema::Record(e) => Ok(Value::Object(
77                decode::record(v, |x| e.parse(x))?.into_iter().collect(),
78            )),
79            Schema::Object(fields) => {
80                let r = Reader::new(v, "object")?;
81                let mut parsed: Vec<(&str, Value)> = Vec::new();
82                for (key, field) in fields {
83                    let value = match field {
84                        Field::Required(s) => Some(r.required(key, |x| s.parse(x))?),
85                        Field::Optional(s) => r.optional(key, |x| s.parse(x))?,
86                    };
87                    if let Some(value) = value {
88                        parsed.push((key, value));
89                    }
90                }
91                // In the input's order, as valita keeps it.
92                let mut out = Object::new();
93                for key in r.0.keys() {
94                    if let Some((_, value)) = parsed.iter().find(|(k, _)| k == key) {
95                        out.insert(key.clone(), value.clone());
96                    }
97                }
98                Ok(Value::Object(out))
99            }
100            Schema::Union(options) => {
101                options.iter().find_map(|o| o.parse(v).ok()).ok_or_else(|| {
102                    DecodeError::new(format!("No union option matched the {}", v.type_name()))
103                })
104            }
105            Schema::Nullable(_) if v.is_null() => Ok(Value::Null),
106            Schema::Nullable(s) => s.parse(v),
107            Schema::Custom(decode) => decode(v),
108        }
109    }
110}