Skip to main content

lexical_ui/
schema.rs

1//! `LexicalSchema.ts`: serialization schemas. A [`SerializationSchema`]
2//! parses an untrusted JSON value into its domain (substituting its default
3//! for anything outside it), knows that default, and describes its domain
4//! ([`SerializationSchemaMeta`]). A node class declares the properties of
5//! its JSON as a [`NodeSchema`] (`nodeSchema`) of [`SchemaField`]s
6//! (`withField`, `withAccessors`), which drives its `exportJSON` in both
7//! forms and its `updateFromJSON` (`LexicalUtils.ts`' compiled schema,
8//! [`walk_export_json`] and [`walk_update_from_json`]); a NodeState can be
9//! parsed by one (`createState(key, {parse: schema})`,
10//! [`StateValueConfig::from_schema`](crate::StateValueConfig::from_schema)).
11//!
12//! As in the Swift port, a schema's domain is the JSON value itself
13//! ([`Value`], whose `Undefined` is JS's `undefined`), so one type-erased
14//! walk serves every node; a field's accessors convert between that and the
15//! node's typed storage ([`SchemaValue`]). Values are immutable, so JS's
16//! freezing and its record of caller-owned values have nothing to do, and
17//! where JS compares two arrays or objects by identity (`===`) the port
18//! compares them by content (rust/PARITY.md).
19
20use crate::LexicalError;
21use crate::json::{Object, Value};
22use crate::node::LexicalNode;
23use std::any::TypeId;
24use std::cell::RefCell;
25use std::collections::HashMap;
26use std::fmt;
27use std::rc::Rc;
28
29/// A schema's parse: `(value: unknown) => T`, where `Value::Undefined` gives
30/// the default.
31pub type SchemaParse = Rc<dyn Fn(&Value) -> Value>;
32/// A schema's `isEqual(a, b)`.
33pub type SchemaIsEqual = Rc<dyn Fn(&Value, &Value) -> bool>;
34/// A schema's `accepts(value)`.
35pub type SchemaAccepts = Rc<dyn Fn(&Value) -> bool>;
36
37/// `SerializationSchemaMeta`: what a schema describes, for tooling that
38/// introspects it, and for a union choosing a member.
39#[derive(Clone)]
40pub enum SerializationSchemaMeta {
41    String,
42    Number {
43        min: Option<f64>,
44        max: Option<f64>,
45        integer: bool,
46        clamp: bool,
47    },
48    Boolean,
49    Enum {
50        values: Vec<Value>,
51    },
52    Array {
53        item: SerializationSchema,
54    },
55    /// `arraySetValue`.
56    Set {
57        item: SerializationSchema,
58    },
59    Nullable {
60        inner: SerializationSchema,
61        default_as_null: bool,
62    },
63    Optional {
64        inner: SerializationSchema,
65        omit_default: bool,
66    },
67    Union {
68        members: Vec<SerializationSchema>,
69    },
70    Raw,
71    Object {
72        fields: Vec<(String, SerializationSchema)>,
73    },
74    Aliased {
75        inner: SerializationSchema,
76        aliases: Vec<(String, Value)>,
77    },
78    Transform {
79        inner: SerializationSchema,
80    },
81}
82
83impl SerializationSchemaMeta {
84    /// `meta.kind`.
85    pub fn kind(&self) -> &'static str {
86        match self {
87            Self::String => "string",
88            Self::Number { .. } => "number",
89            Self::Boolean => "boolean",
90            Self::Enum { .. } => "enum",
91            Self::Array { .. } => "array",
92            Self::Set { .. } => "set",
93            Self::Nullable { .. } => "nullable",
94            Self::Optional { .. } => "optional",
95            Self::Union { .. } => "union",
96            Self::Raw => "raw",
97            Self::Object { .. } => "object",
98            Self::Aliased { .. } => "aliased",
99            Self::Transform { .. } => "transform",
100        }
101    }
102}
103
104struct SchemaInner {
105    meta: SerializationSchemaMeta,
106    default_value: Value,
107    is_equal: Option<SchemaIsEqual>,
108    accepts: Option<SchemaAccepts>,
109    /// Whether `accepts` came from a combinator (`DERIVED_ACCEPTS`) rather
110    /// than from the schema's author.
111    accepts_is_derived: bool,
112    /// `$isCatchAll`, which JS caches per schema.
113    is_catch_all: bool,
114    parse: SchemaParse,
115}
116
117/// `SerializationSchema<T>`: a parser with its default and the description
118/// of its domain. Clones are the same schema.
119#[derive(Clone)]
120pub struct SerializationSchema(Rc<SchemaInner>);
121
122impl fmt::Debug for SerializationSchema {
123    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124        write!(
125            f,
126            "SerializationSchema({}, default {})",
127            self.0.meta.kind(),
128            self.0.default_value
129        )
130    }
131}
132
133impl SerializationSchema {
134    /// A schema of your own (JS's hand-rolled schema: a parse function with
135    /// `meta`, `defaultValue` and optionally `isEqual` and `accepts`). An
136    /// `accepts` given here is declared: it narrows what a union will
137    /// choose this schema for.
138    pub fn new(
139        meta: SerializationSchemaMeta,
140        default_value: Value,
141        is_equal: Option<SchemaIsEqual>,
142        accepts: Option<SchemaAccepts>,
143        parse: impl Fn(&Value) -> Value + 'static,
144    ) -> Self {
145        let declared = accepts.is_some();
146        Self::build(
147            Rc::new(parse),
148            meta,
149            Some(default_value),
150            is_equal,
151            accepts,
152            !declared,
153        )
154    }
155
156    /// `makeSchema`: a schema that states no default (or `undefined`)
157    /// derives it from parsing `undefined`.
158    fn make(
159        parse: impl Fn(&Value) -> Value + 'static,
160        meta: SerializationSchemaMeta,
161        default_value: Option<Value>,
162        is_equal: Option<SchemaIsEqual>,
163        accepts: impl Fn(&Value) -> bool + 'static,
164    ) -> Self {
165        Self::build(
166            Rc::new(parse),
167            meta,
168            default_value,
169            is_equal,
170            Some(Rc::new(accepts)),
171            true,
172        )
173    }
174
175    fn build(
176        parse: SchemaParse,
177        meta: SerializationSchemaMeta,
178        default_value: Option<Value>,
179        is_equal: Option<SchemaIsEqual>,
180        accepts: Option<SchemaAccepts>,
181        accepts_is_derived: bool,
182    ) -> Self {
183        let default_value = match default_value {
184            None | Some(Value::Undefined) => parse(&Value::Undefined),
185            Some(value) => value,
186        };
187        let declared = accepts.is_some() && !accepts_is_derived;
188        let is_catch_all = !declared && compute_is_catch_all(&meta);
189        SerializationSchema(Rc::new(SchemaInner {
190            meta,
191            default_value,
192            is_equal,
193            accepts,
194            accepts_is_derived,
195            is_catch_all,
196            parse,
197        }))
198    }
199
200    /// Parses an untrusted value; never fails, substituting the default.
201    pub fn parse(&self, value: &Value) -> Value {
202        (self.0.parse)(value)
203    }
204
205    /// `defaultValue`: what `parse(undefined)` returns, which the compact
206    /// form omits.
207    pub fn default_value(&self) -> &Value {
208        &self.0.default_value
209    }
210
211    /// `meta`.
212    pub fn meta(&self) -> &SerializationSchemaMeta {
213        &self.0.meta
214    }
215
216    /// `isEqual`, when the schema declares one.
217    pub fn is_equal(&self) -> Option<&SchemaIsEqual> {
218        self.0.is_equal.as_ref()
219    }
220
221    /// `accepts`, when the schema has one.
222    pub fn accepts(&self) -> Option<&SchemaAccepts> {
223        self.0.accepts.as_ref()
224    }
225
226    /// `declaredAccepts(schema)`: the `accepts` a schema's author wrote,
227    /// not one a combinator derived.
228    pub fn declared_accepts(&self) -> Option<&SchemaAccepts> {
229        if self.0.accepts_is_derived {
230            None
231        } else {
232            self.0.accepts.as_ref()
233        }
234    }
235
236    /// Whether `self` and `other` are the same schema (`===`).
237    pub fn is(&self, other: &SerializationSchema) -> bool {
238        Rc::ptr_eq(&self.0, &other.0)
239    }
240
241    fn is_set(&self) -> bool {
242        matches!(self.0.meta, SerializationSchemaMeta::Set { .. })
243    }
244}
245
246/// `isSchemaEqual(schema, a, b)`: whether two values of `schema`'s domain
247/// say the same thing: the same value, unless the schema declares
248/// otherwise.
249pub fn is_schema_equal(schema: &SerializationSchema, a: &Value, b: &Value) -> bool {
250    a == b || schema.0.is_equal.as_ref().is_some_and(|eq| eq(a, b))
251}
252
253/// `isSchemaDefault(schema, value)`: whether `value` is the one `schema`
254/// restores for an absent property, so writing it says nothing.
255pub fn is_schema_default(schema: &SerializationSchema, value: &Value) -> bool {
256    is_schema_equal(schema, value, &schema.0.default_value)
257}
258
259/// `$acceptsValue(schema, value)`: its `accepts` when it has one, otherwise
260/// the parse inference of `$schemaMatch`.
261fn accepts_value(schema: &SerializationSchema, value: &Value) -> bool {
262    match &schema.0.accepts {
263        Some(accepts) => accepts(value),
264        None => schema_match(schema, value).is_some(),
265    }
266}
267
268/// `$schemaMatch(schema, value)`: the parsed value when `value` is in the
269/// schema's domain. Without `accepts`, a value is in it when it does not
270/// parse to the default, or is the default.
271fn schema_match(schema: &SerializationSchema, value: &Value) -> Option<Value> {
272    if schema.0.accepts.is_some() {
273        return accepts_value(schema, value).then(|| schema.parse(value));
274    }
275    let parsed = schema.parse(value);
276    (!is_schema_default(schema, &parsed) || *value == schema.0.default_value).then_some(parsed)
277}
278
279/// `$computeIsCatchAll`: a `rawValue`, or a wrapper or union that bottoms
280/// out at one (a schema with a declared `accepts` describes something, and
281/// is not one; the caller checks that).
282fn compute_is_catch_all(meta: &SerializationSchemaMeta) -> bool {
283    use SerializationSchemaMeta as M;
284    match meta {
285        M::Raw => true,
286        M::Union { members } => !members.is_empty() && members.iter().all(|m| m.0.is_catch_all),
287        M::Nullable { inner, .. }
288        | M::Optional { inner, .. }
289        | M::Transform { inner }
290        | M::Aliased { inner, .. } => inner.0.is_catch_all,
291        _ => false,
292    }
293}
294
295const FIT_WHOLE: u8 = 1;
296const FIT_VIA_CATCH_ALL: u8 = 2;
297const FIT_COERCIBLE: u8 = 3;
298const FIT_NONE: u8 = 4;
299
300/// `$fitOf(schema, value)`: how well `value` fits `schema`, from whole (1)
301/// to none (4).
302fn fit_of(schema: &SerializationSchema, value: &Value) -> u8 {
303    let declared = schema.declared_accepts();
304    let narrowed = declared.is_some();
305    if let Some(declared) = declared
306        && !declared(value)
307    {
308        return FIT_NONE;
309    }
310    let fit = meta_fit_of(schema, value, narrowed);
311    if narrowed && fit == FIT_NONE {
312        FIT_COERCIBLE
313    } else {
314        fit
315    }
316}
317
318/// `$metaFitOf`: the part of `$fitOf` that reads only what the combinator
319/// recorded.
320fn meta_fit_of(schema: &SerializationSchema, value: &Value, narrowed: bool) -> u8 {
321    use SerializationSchemaMeta as M;
322    match &schema.0.meta {
323        M::Raw => {
324            if narrowed {
325                FIT_WHOLE
326            } else {
327                FIT_VIA_CATCH_ALL
328            }
329        }
330        M::Array { item } => {
331            let Value::Array(items) = value else {
332                return FIT_NONE;
333            };
334            let mut worst = FIT_WHOLE;
335            for element in items.iter().filter(|v| !v.is_undefined()) {
336                worst = worst.max(fit_of(item, element));
337            }
338            worst.min(FIT_COERCIBLE)
339        }
340        M::Object { fields } => {
341            let Some(source) = as_plain_object(value) else {
342                return FIT_NONE;
343            };
344            if !narrowed && has_undeclared_key(source, fields) {
345                return FIT_NONE;
346            }
347            let mut worst = FIT_WHOLE;
348            for (key, v) in source.iter() {
349                if let Some((_, field)) = fields.iter().find(|(k, _)| k == key) {
350                    worst = worst.max(fit_of(field, v));
351                }
352            }
353            worst.min(FIT_COERCIBLE)
354        }
355        M::Union { members } => best_union_member(members, value).0,
356        M::Aliased { inner, aliases } => {
357            let owned = value
358                .as_str()
359                .is_some_and(|s| aliases.iter().any(|(k, _)| k == s));
360            if owned {
361                FIT_WHOLE
362            } else {
363                fit_of(inner, value)
364            }
365        }
366        M::Nullable { inner, .. } => {
367            if value.is_undefined() || value.is_null() {
368                FIT_WHOLE
369            } else {
370                fit_of(inner, value)
371            }
372        }
373        M::Optional { inner, .. } => {
374            if value.is_undefined() {
375                FIT_WHOLE
376            } else {
377                fit_of(inner, value)
378            }
379        }
380        M::Transform { inner } => fit_of(inner, value),
381        _ => {
382            if narrowed || accepts_value(schema, value) {
383                FIT_WHOLE
384            } else {
385                FIT_NONE
386            }
387        }
388    }
389}
390
391/// `$bestUnionMember(members, value)`: the first member that fits best,
392/// where a catch-all ranks below any member that fits on its own terms,
393/// and how well it fits.
394fn best_union_member<'a>(
395    members: &'a [SerializationSchema],
396    value: &Value,
397) -> (u8, Option<&'a SerializationSchema>) {
398    let mut member = None;
399    let mut best_rank = FIT_NONE;
400    let mut best_fit = FIT_NONE;
401    for candidate in members {
402        let fit = fit_of(candidate, value);
403        let rank = if fit < FIT_COERCIBLE && candidate.0.is_catch_all {
404            FIT_COERCIBLE
405        } else {
406            fit
407        };
408        if rank < best_rank {
409            member = Some(candidate);
410            best_rank = rank;
411            best_fit = fit;
412            if rank == FIT_WHOLE {
413                break;
414            }
415        }
416    }
417    (best_fit, member)
418}
419
420/// `undeclared(combinator, inner)`: in JS also the refusal of a wrapped
421/// schema that names an accessor, which a [`SerializationSchema`] can't
422/// (accessors live on [`SchemaField`]), so only the set check remains.
423fn undeclared(combinator: &str, inner: &SerializationSchema) -> Result<(), LexicalError> {
424    not_nested_set(combinator, inner)
425}
426
427/// `notNestedSet(combinator, inner)`.
428fn not_nested_set(combinator: &str, inner: &SerializationSchema) -> Result<(), LexicalError> {
429    if inner.is_set() {
430        return Err(LexicalError::new(format!(
431            "{combinator}: arraySetValue can only be the whole value of a createState, not part of another schema or a node property"
432        )));
433    }
434    Ok(())
435}
436
437/// `isPlainObject(value)`: a JSON object.
438fn as_plain_object(value: &Value) -> Option<&Object> {
439    value.as_object()
440}
441
442/// `hasUndeclaredKey(source, fields)`.
443fn has_undeclared_key(source: &Object, fields: &[(String, SerializationSchema)]) -> bool {
444    source
445        .keys()
446        .any(|key| !fields.iter().any(|(k, _)| k == key))
447}
448
449/// `stringValue(defaultValue)`: `value` when it is a string, otherwise
450/// `default_value`.
451pub fn string_value(default_value: &str) -> SerializationSchema {
452    let default_value = default_value.to_owned();
453    SerializationSchema::make(
454        move |value| match value {
455            Value::String(_) => value.clone(),
456            _ => Value::String(default_value.clone()),
457        },
458        SerializationSchemaMeta::String,
459        None,
460        None,
461        |value| matches!(value, Value::String(_)),
462    )
463}
464
465/// `NumberValueOptions`: the domain of a [`number_value`].
466#[derive(Clone, Copy, Debug, Default)]
467pub struct NumberValueOptions {
468    /// Reject values below this bound (inclusive); with `integer`, rounded
469    /// up to the integer it admits.
470    pub min: Option<f64>,
471    /// Reject values above this bound (inclusive); with `integer`, rounded
472    /// down.
473    pub max: Option<f64>,
474    /// Reject values that are not integers.
475    pub integer: bool,
476    /// Bring a finite value outside `min`/`max` to the nearest bound
477    /// instead of rejecting it.
478    pub clamp: bool,
479}
480
481/// `JSON_NUMBER`: the JSON number grammar, anchored
482/// (`/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/`).
483pub(crate) fn is_json_number(s: &str) -> bool {
484    let b = s.as_bytes();
485    let mut i = 0;
486    let digits = |i: &mut usize| {
487        let start = *i;
488        while *i < b.len() && b[*i].is_ascii_digit() {
489            *i += 1;
490        }
491        *i - start
492    };
493    if b.get(i) == Some(&b'-') {
494        i += 1;
495    }
496    match b.get(i) {
497        Some(b'0') => i += 1,
498        Some(b'1'..=b'9') => {
499            digits(&mut i);
500        }
501        _ => return false,
502    }
503    if b.get(i) == Some(&b'.') {
504        i += 1;
505        if digits(&mut i) == 0 {
506            return false;
507        }
508    }
509    if let Some(b'e' | b'E') = b.get(i) {
510        i += 1;
511        if let Some(b'+' | b'-') = b.get(i) {
512            i += 1;
513        }
514        if digits(&mut i) == 0 {
515            return false;
516        }
517    }
518    i == b.len()
519}
520
521/// JS `String(n)`.
522fn js_number_string(n: f64) -> String {
523    crate::json::number_to_string(n)
524}
525
526/// `numberValue(defaultValue, options)`: a finite number in the domain, or
527/// a string in the JSON number grammar naming one; otherwise
528/// `default_value`. An integer domain rounds its bounds inward; an empty
529/// domain is refused.
530pub fn number_value(
531    default_value: f64,
532    options: NumberValueOptions,
533) -> Result<SerializationSchema, LexicalError> {
534    let NumberValueOptions {
535        min,
536        max,
537        integer,
538        clamp,
539    } = options;
540    let lower = if integer { min.map(f64::ceil) } else { min };
541    let upper = if integer { max.map(f64::floor) } else { max };
542    if let (Some(lo), Some(hi)) = (lower, upper)
543        && lo > hi
544    {
545        let rounded = if integer && (lower != min || upper != max) {
546            format!(
547                " (rounded inward from {}..{} because the domain is integers)",
548                min.map_or("undefined".to_owned(), js_number_string),
549                max.map_or("undefined".to_owned(), js_number_string),
550            )
551        } else {
552            String::new()
553        };
554        return Err(LexicalError::new(format!(
555            "numberValue: the domain is empty; min {} is above max {}{rounded}",
556            js_number_string(lo),
557            js_number_string(hi),
558        )));
559    }
560    let coerce = |value: &Value| -> Option<f64> {
561        match value {
562            Value::Number(n) => Some(*n),
563            Value::String(s) if is_json_number(s) => Some(s.parse().expect("a JSON number")),
564            _ => None,
565        }
566    };
567    let is_numeric = move |n: f64| n.is_finite() && (!integer || n.fract() == 0.0);
568    let in_domain = move |n: f64| {
569        is_numeric(n) && lower.is_none_or(|lo| n >= lo) && upper.is_none_or(|hi| n <= hi)
570    };
571    Ok(SerializationSchema::make(
572        move |value| {
573            let parsed = coerce(value);
574            if clamp && let Some(n) = parsed.filter(|n| is_numeric(*n)) {
575                return Value::Number(match (lower, upper) {
576                    (Some(lo), _) if n < lo => lo,
577                    (_, Some(hi)) if n > hi => hi,
578                    _ => n,
579                });
580            }
581            Value::Number(parsed.filter(|n| in_domain(*n)).unwrap_or(default_value))
582        },
583        SerializationSchemaMeta::Number {
584            min: lower,
585            max: upper,
586            integer,
587            clamp,
588        },
589        None,
590        None,
591        move |value| {
592            coerce(value).is_some_and(|n| if clamp { is_numeric(n) } else { in_domain(n) })
593        },
594    ))
595}
596
597/// `booleanValue(defaultValue)`.
598pub fn boolean_value(default_value: bool) -> SerializationSchema {
599    SerializationSchema::make(
600        move |value| match value {
601            Value::Bool(_) => value.clone(),
602            _ => Value::Bool(default_value),
603        },
604        SerializationSchemaMeta::Boolean,
605        None,
606        None,
607        |value| matches!(value, Value::Bool(_)),
608    )
609}
610
611/// Membership in a JS `Set` (SameValueZero): `NaN` is a member of itself.
612fn same_value_zero(a: &Value, b: &Value) -> bool {
613    match (a, b) {
614        (Value::Number(x), Value::Number(y)) if x.is_nan() && y.is_nan() => true,
615        _ => a == b,
616    }
617}
618
619/// `enumValue(values, defaultValue)`: one of `values`, otherwise the
620/// default, which is the first value unless given (`Some`, which may be
621/// `Value::Undefined`) and must be one of them.
622pub fn enum_value(
623    values: Vec<Value>,
624    default_value: Option<Value>,
625) -> Result<SerializationSchema, LexicalError> {
626    if values.is_empty() {
627        return Err(LexicalError::new(
628            "enumValue: values must not be empty; an enum with no members admits no value",
629        ));
630    }
631    let fallback = default_value.unwrap_or_else(|| values[0].clone());
632    let allowed = {
633        let values = values.clone();
634        move |value: &Value| values.iter().any(|m| same_value_zero(m, value))
635    };
636    if !allowed(&fallback) {
637        return Err(LexicalError::new(
638            "enumValue: the default value is not one of the values",
639        ));
640    }
641    let parse_allowed = allowed.clone();
642    let parse_fallback = fallback.clone();
643    let fallback_undefined = fallback.is_undefined();
644    Ok(SerializationSchema::make(
645        move |value| {
646            if !value.is_undefined() && parse_allowed(value) {
647                value.clone()
648            } else {
649                parse_fallback.clone()
650            }
651        },
652        SerializationSchemaMeta::Enum { values },
653        Some(fallback),
654        None,
655        move |value| allowed(value) && (!value.is_undefined() || fallback_undefined),
656    ))
657}
658
659/// `liftIsEqual(inner)`: `inner`'s equality on a wrapper that adds a nil.
660fn lift_is_equal(inner: &SerializationSchema) -> Option<SchemaIsEqual> {
661    let is_equal = inner.0.is_equal.clone()?;
662    let nil = |v: &Value| v.is_undefined() || v.is_null();
663    Some(Rc::new(move |a, b| {
664        if nil(a) || nil(b) {
665            a == b
666        } else {
667            is_equal(a, b)
668        }
669    }))
670}
671
672/// `nullable(inner, {defaultAsNull})`: `null` for `null` and `undefined`,
673/// otherwise what `inner` parses (`null` again for `inner`'s default with
674/// `default_as_null`).
675pub fn nullable(
676    inner: SerializationSchema,
677    default_as_null: bool,
678) -> Result<SerializationSchema, LexicalError> {
679    undeclared("nullable", &inner)?;
680    let parse_inner = inner.clone();
681    let accepts_inner = inner.clone();
682    let is_equal = lift_is_equal(&inner);
683    Ok(SerializationSchema::make(
684        move |value| {
685            if value.is_undefined() || value.is_null() {
686                return Value::Null;
687            }
688            let parsed = parse_inner.parse(value);
689            if default_as_null && is_schema_default(&parse_inner, &parsed) {
690                Value::Null
691            } else {
692                parsed
693            }
694        },
695        SerializationSchemaMeta::Nullable {
696            inner,
697            default_as_null,
698        },
699        None,
700        is_equal,
701        move |value| {
702            value.is_undefined() || value.is_null() || accepts_value(&accepts_inner, value)
703        },
704    ))
705}
706
707/// `optional(inner, {omitDefault})`: `undefined` for `undefined`, otherwise
708/// what `inner` parses (`undefined` again for `inner`'s default with
709/// `omit_default`).
710pub fn optional(
711    inner: SerializationSchema,
712    omit_default: bool,
713) -> Result<SerializationSchema, LexicalError> {
714    undeclared("optional", &inner)?;
715    let parse_inner = inner.clone();
716    let accepts_inner = inner.clone();
717    let is_equal = lift_is_equal(&inner);
718    Ok(SerializationSchema::make(
719        move |value| {
720            if value.is_undefined() {
721                return Value::Undefined;
722            }
723            let parsed = parse_inner.parse(value);
724            if omit_default && is_schema_default(&parse_inner, &parsed) {
725                Value::Undefined
726            } else {
727                parsed
728            }
729        },
730        SerializationSchemaMeta::Optional {
731            inner,
732            omit_default,
733        },
734        None,
735        is_equal,
736        move |value| value.is_undefined() || accepts_value(&accepts_inner, value),
737    ))
738}
739
740/// `unionValue(members, defaultValue)`: the value as the member that fits
741/// it best parses it, otherwise the default (the first member's unless
742/// given, as `Some`, which may be `Value::Undefined`).
743pub fn union_value(
744    members: Vec<SerializationSchema>,
745    default_value: Option<Value>,
746) -> Result<SerializationSchema, LexicalError> {
747    if members.is_empty() {
748        return Err(LexicalError::new(
749            "unionValue: at least one member schema is required",
750        ));
751    }
752    for member in &members {
753        undeclared("unionValue", member)?;
754    }
755    let fallback = default_value.unwrap_or_else(|| members[0].0.default_value.clone());
756    let parse_members = members.clone();
757    let accepts_members = members.clone();
758    let parse_fallback = fallback.clone();
759    let fallback_undefined = fallback.is_undefined();
760    Ok(SerializationSchema::make(
761        move |value| {
762            if value.is_undefined() {
763                return parse_fallback.clone();
764            }
765            match best_union_member(&parse_members, value).1 {
766                Some(member) => member.parse(value),
767                None => parse_fallback.clone(),
768            }
769        },
770        SerializationSchemaMeta::Union { members },
771        Some(fallback),
772        // `$sameContent`, which is content equality on JSON values.
773        Some(Rc::new(|a: &Value, b: &Value| a == b)),
774        move |value| {
775            (!value.is_undefined() || fallback_undefined)
776                && accepts_members.iter().any(|m| accepts_value(m, value))
777        },
778    ))
779}
780
781/// `aliasedValue(inner, aliases)`: also reads the string names in
782/// `aliases` as the values they stand for.
783pub fn aliased_value(
784    inner: SerializationSchema,
785    aliases: Vec<(String, Value)>,
786) -> Result<SerializationSchema, LexicalError> {
787    undeclared("aliasedValue", &inner)?;
788    let alias = |aliases: &[(String, Value)], value: &Value| -> Option<Value> {
789        let s = value.as_str()?;
790        aliases.iter().find(|(k, _)| k == s).map(|(_, v)| v.clone())
791    };
792    let parse_inner = inner.clone();
793    let parse_aliases = aliases.clone();
794    let accepts_inner = inner.clone();
795    let accepts_aliases = aliases.clone();
796    let default_value = inner.0.default_value.clone();
797    let is_equal = inner.0.is_equal.clone();
798    Ok(SerializationSchema::make(
799        move |value| alias(&parse_aliases, value).unwrap_or_else(|| parse_inner.parse(value)),
800        SerializationSchemaMeta::Aliased { inner, aliases },
801        Some(default_value),
802        is_equal,
803        move |value| {
804            alias(&accepts_aliases, value).is_some() || accepts_value(&accepts_inner, value)
805        },
806    ))
807}
808
809/// `transformValue(inner, transform, {isEqual})`: parses with `inner`, then
810/// maps the result. `is_equal` is only for a transform to an array or an
811/// object.
812pub fn transform_value(
813    inner: SerializationSchema,
814    transform: impl Fn(Value) -> Value + 'static,
815    is_equal: Option<SchemaIsEqual>,
816) -> Result<SerializationSchema, LexicalError> {
817    undeclared("transformValue", &inner)?;
818    let transform = Rc::new(transform);
819    let default_value = transform(inner.0.default_value.clone());
820    if is_equal.is_some() && !matches!(default_value, Value::Array(_) | Value::Object(_)) {
821        return Err(LexicalError::new(format!(
822            "transformValue: isEqual compares reference-typed values, but this schema parses to {}. Two primitives that are not === are two different serialized values; declaring them equal loses one of them in the compact form.",
823            js_typeof(&default_value)
824        )));
825    }
826    let parse_inner = inner.clone();
827    let accepts_inner = inner.clone();
828    let parse_transform = transform.clone();
829    Ok(SerializationSchema::make(
830        move |value| parse_transform(parse_inner.parse(value)),
831        SerializationSchemaMeta::Transform { inner },
832        Some(default_value),
833        is_equal,
834        move |value| accepts_value(&accepts_inner, value),
835    ))
836}
837
838/// JS `typeof` of a JSON value.
839fn js_typeof(value: &Value) -> &'static str {
840    match value {
841        Value::Undefined => "undefined",
842        Value::Null | Value::Array(_) | Value::Object(_) => "object",
843        Value::Bool(_) => "boolean",
844        Value::Number(_) => "number",
845        Value::String(_) => "string",
846    }
847}
848
849/// `rawValue()`: the JSON as it is.
850pub fn raw_value() -> SerializationSchema {
851    SerializationSchema::make(
852        Value::clone,
853        SerializationSchemaMeta::Raw,
854        None,
855        None,
856        |_| true,
857    )
858}
859
860/// `arrayValue(item)`: each element parsed by `item`; anything but an
861/// array is the empty array.
862pub fn array_value(item: SerializationSchema) -> Result<SerializationSchema, LexicalError> {
863    undeclared("arrayValue", &item)?;
864    let parse_item = item.clone();
865    let equal_item = item.clone();
866    Ok(SerializationSchema::make(
867        move |value| match value {
868            Value::Array(items) => {
869                Value::Array(items.iter().map(|v| parse_item.parse(v)).collect())
870            }
871            _ => Value::Array(Vec::new()),
872        },
873        SerializationSchemaMeta::Array { item },
874        None,
875        Some(Rc::new(move |a: &Value, b: &Value| match (a, b) {
876            (Value::Array(a), Value::Array(b)) => {
877                a.len() == b.len()
878                    && a.iter()
879                        .zip(b)
880                        .all(|(x, y)| is_schema_equal(&equal_item, x, y))
881            }
882            _ => false,
883        })),
884        |value| matches!(value, Value::Array(_)),
885    ))
886}
887
888/// JS's `<` on strings: by UTF-16 code units.
889fn js_cmp(a: &str, b: &str) -> std::cmp::Ordering {
890    a.encode_utf16().cmp(b.encode_utf16())
891}
892
893/// `arraySetValue(item)`: a set of strings, written as one array sorted as
894/// JS sorts strings (by UTF-16 code units) without duplicates; members
895/// `item` does not accept are dropped. Only the whole value of a
896/// `createState`.
897pub fn array_set_value(item: SerializationSchema) -> Result<SerializationSchema, LexicalError> {
898    undeclared("arraySetValue", &item)?;
899    if !matches!(item.0.default_value, Value::String(_)) {
900        return Err(LexicalError::new(
901            "arraySetValue: the item schema must produce strings",
902        ));
903    }
904    let parse_item = item.clone();
905    Ok(SerializationSchema::make(
906        move |value| {
907            let Value::Array(items) = value else {
908                return Value::Array(Vec::new());
909            };
910            // A value already canonical (`$isCanonicalSet`) is kept as it
911            // is, which the parse below gives anyway.
912            let mut members: Vec<String> = items
913                .iter()
914                .filter(|m| !m.is_undefined() && accepts_value(&parse_item, m))
915                .filter_map(|m| match parse_item.parse(m) {
916                    Value::String(s) => Some(s),
917                    _ => None,
918                })
919                .collect();
920            members.sort_by(|a, b| js_cmp(a, b));
921            members.dedup();
922            Value::Array(members.into_iter().map(Value::String).collect())
923        },
924        SerializationSchemaMeta::Set { item },
925        None,
926        // `isArraySetEqual`: element by element.
927        Some(Rc::new(|a: &Value, b: &Value| a == b)),
928        |value| matches!(value, Value::Array(_)),
929    ))
930}
931
932/// The `Object.prototype` members a serialized object inherits.
933const OBJECT_PROTOTYPE_MEMBERS: [&str; 12] = [
934    "__defineGetter__",
935    "__defineSetter__",
936    "__lookupGetter__",
937    "__lookupSetter__",
938    "__proto__",
939    "constructor",
940    "hasOwnProperty",
941    "isPrototypeOf",
942    "propertyIsEnumerable",
943    "toLocaleString",
944    "toString",
945    "valueOf",
946];
947
948/// `checkFieldNames(combinator, fields)`.
949fn check_field_names<'a>(
950    combinator: &str,
951    fields: impl IntoIterator<Item = (&'a str, &'a SerializationSchema)>,
952) -> Result<(), LexicalError> {
953    for (key, schema) in fields {
954        if key == "__proto__" {
955            return Err(LexicalError::new(format!(
956                "{combinator}: \"__proto__\" is not a valid field name"
957            )));
958        }
959        if OBJECT_PROTOTYPE_MEMBERS.contains(&key) {
960            return Err(LexicalError::new(format!(
961                "{combinator}: \"{key}\" is a member of Object.prototype, which a serialized object inherits, so it cannot be told apart from a property the document never carried"
962            )));
963        }
964        not_nested_set(combinator, schema)?;
965    }
966    Ok(())
967}
968
969/// A JS property read on a JSON value, as `objectValue` reads its source:
970/// an object's own key, or an array's index or `length`.
971fn js_property(value: &Value, key: &str) -> Value {
972    match value {
973        Value::Object(object) => object.get(key).cloned().unwrap_or(Value::Undefined),
974        Value::Array(items) => {
975            if key == "length" {
976                return Value::Number(items.len() as f64);
977            }
978            crate::json::array_index(key)
979                .and_then(|i| items.get(i as usize))
980                .cloned()
981                .unwrap_or(Value::Undefined)
982        }
983        _ => Value::Undefined,
984    }
985}
986
987/// `objectValue(fields)`: an object with exactly the declared fields, each
988/// parsed by its schema.
989pub fn object_value(
990    fields: Vec<(&str, SerializationSchema)>,
991) -> Result<SerializationSchema, LexicalError> {
992    let fields: Vec<(String, SerializationSchema)> =
993        fields.into_iter().map(|(k, s)| (k.to_owned(), s)).collect();
994    check_field_names("objectValue", fields.iter().map(|(k, s)| (k.as_str(), s)))?;
995    let parse_fields = fields.clone();
996    let equal_fields = fields.clone();
997    let accepts_fields = fields.clone();
998    Ok(SerializationSchema::make(
999        move |value| {
1000            let mut result = Object::new();
1001            for (key, schema) in &parse_fields {
1002                result.insert(key.as_str(), schema.parse(&js_property(value, key)));
1003            }
1004            Value::Object(result)
1005        },
1006        SerializationSchemaMeta::Object { fields },
1007        None,
1008        Some(Rc::new(move |a: &Value, b: &Value| {
1009            let (Some(a), Some(b)) = (as_plain_object(a), as_plain_object(b)) else {
1010                return false;
1011            };
1012            !has_undeclared_key(a, &equal_fields)
1013                && !has_undeclared_key(b, &equal_fields)
1014                && equal_fields.iter().all(|(key, schema)| {
1015                    is_schema_equal(
1016                        schema,
1017                        a.get(key).unwrap_or(&Value::Undefined),
1018                        b.get(key).unwrap_or(&Value::Undefined),
1019                    )
1020                })
1021        })),
1022        move |value| {
1023            as_plain_object(value).is_some_and(|o| !has_undeclared_key(o, &accepts_fields))
1024        },
1025    ))
1026}
1027
1028/// A Rust type a [`with_field`] property can be stored as, converted to
1029/// and from the schema's JSON domain.
1030pub trait SchemaValue: Sized {
1031    /// The value as the schema's JSON; `Value::Undefined` when it has none.
1032    fn to_schema_value(&self) -> Value;
1033    /// The value a parsed JSON value stands for, or `None` when it is not
1034    /// one.
1035    fn from_schema_value(value: &Value) -> Option<Self>;
1036}
1037
1038impl SchemaValue for String {
1039    fn to_schema_value(&self) -> Value {
1040        Value::String(self.clone())
1041    }
1042    fn from_schema_value(value: &Value) -> Option<Self> {
1043        value.as_str().map(str::to_owned)
1044    }
1045}
1046
1047impl SchemaValue for f64 {
1048    fn to_schema_value(&self) -> Value {
1049        Value::Number(*self)
1050    }
1051    fn from_schema_value(value: &Value) -> Option<Self> {
1052        value.as_f64()
1053    }
1054}
1055
1056impl SchemaValue for bool {
1057    fn to_schema_value(&self) -> Value {
1058        Value::Bool(*self)
1059    }
1060    fn from_schema_value(value: &Value) -> Option<Self> {
1061        value.as_bool()
1062    }
1063}
1064
1065impl SchemaValue for Value {
1066    fn to_schema_value(&self) -> Value {
1067        self.clone()
1068    }
1069    fn from_schema_value(value: &Value) -> Option<Self> {
1070        Some(value.clone())
1071    }
1072}
1073
1074/// `None` has no value: `undefined`, or `null` for a property that isn't
1075/// [`optional`].
1076impl<T: SchemaValue> SchemaValue for Option<T> {
1077    fn to_schema_value(&self) -> Value {
1078        self.as_ref().map_or(Value::Undefined, T::to_schema_value)
1079    }
1080    fn from_schema_value(value: &Value) -> Option<Self> {
1081        if value.is_undefined() || value.is_null() {
1082            Some(None)
1083        } else {
1084            T::from_schema_value(value).map(Some)
1085        }
1086    }
1087}
1088
1089impl<T: SchemaValue> SchemaValue for Vec<T> {
1090    fn to_schema_value(&self) -> Value {
1091        Value::Array(self.iter().map(T::to_schema_value).collect())
1092    }
1093    fn from_schema_value(value: &Value) -> Option<Self> {
1094        value.as_array()?.iter().map(T::from_schema_value).collect()
1095    }
1096}
1097
1098/// How the export walk reads a property: from the node, in the schema's
1099/// domain.
1100pub type SchemaGetter = Rc<dyn Fn(&dyn LexicalNode) -> Value>;
1101/// How the import walk applies a parsed value to a writable node.
1102pub type SchemaSetter = Rc<dyn Fn(&mut dyn LexicalNode, Value)>;
1103/// A `when` predicate: whether the property is written at all.
1104pub type SchemaPredicate = Rc<dyn Fn(&dyn LexicalNode) -> bool>;
1105
1106/// One property of a node's serialization schema: its schema with the
1107/// accessors that read it for export and apply it on import, as
1108/// [`with_field`] and [`with_accessors`] make it. JS also lets a plain
1109/// schema stand for the conventional `get<Prop>`/`set<Prop>` methods; a
1110/// Rust node has no methods to find by name, so every property names its
1111/// accessors.
1112#[derive(Clone)]
1113pub struct SchemaField {
1114    schema: SerializationSchema,
1115    /// `None` declares the property import-only (`getter: null`).
1116    getter: Option<SchemaGetter>,
1117    /// `when`: the property is written only where it holds (and is not the
1118    /// default).
1119    when: Option<SchemaPredicate>,
1120    /// `None` declares the property derived on import (`setter: null`),
1121    /// which the compact form leaves out.
1122    setter: Option<SchemaSetter>,
1123    /// `derived: true` (`@experimental`): the node's own code recomputes
1124    /// the property from the document, so tools that copy or compare a
1125    /// node's data can leave it out, and `mergeAdjacent` may not name it.
1126    derived: bool,
1127}
1128
1129impl fmt::Debug for SchemaField {
1130    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1131        f.debug_struct("SchemaField")
1132            .field("schema", &self.schema)
1133            .field("getter", &self.getter.is_some())
1134            .field("when", &self.when.is_some())
1135            .field("setter", &self.setter.is_some())
1136            .field("derived", &self.derived)
1137            .finish()
1138    }
1139}
1140
1141impl SchemaField {
1142    /// The property's schema.
1143    pub fn schema(&self) -> &SerializationSchema {
1144        &self.schema
1145    }
1146
1147    /// `derived`.
1148    pub fn is_derived(&self) -> bool {
1149        self.derived
1150    }
1151
1152    /// Whether the property is exported (it has a getter).
1153    pub fn is_exported(&self) -> bool {
1154        self.getter.is_some()
1155    }
1156
1157    /// Whether the property is applied on import (it has a setter).
1158    pub fn is_imported(&self) -> bool {
1159        self.setter.is_some()
1160    }
1161
1162    /// `{when}`: writes the property only where `when` holds.
1163    pub fn when(mut self, when: impl Fn(&dyn LexicalNode) -> bool + 'static) -> Self {
1164        self.when = Some(Rc::new(when));
1165        self
1166    }
1167
1168    /// `{derived: true}`.
1169    pub fn derived(mut self) -> Self {
1170        self.derived = true;
1171        self
1172    }
1173
1174    /// Whether the compact form omits `value`: `undefined`, or the default
1175    /// (`$isCompactDefaultFor`).
1176    fn is_compact_default(&self, value: &Value) -> bool {
1177        value.is_undefined() || is_schema_default(&self.schema, value)
1178    }
1179}
1180
1181/// The node of type `N` a schema accessor was given.
1182fn node_as<N: LexicalNode>(node: &dyn LexicalNode) -> &N {
1183    node.downcast_ref::<N>()
1184        .expect("a schema field of the node's own class")
1185}
1186
1187fn node_as_mut<N: LexicalNode>(node: &mut dyn LexicalNode) -> &mut N {
1188    node.downcast_mut::<N>()
1189        .expect("a schema field of the node's own class")
1190}
1191
1192/// A getter that reads a node of type `N`.
1193pub fn schema_getter<N: LexicalNode>(get: impl Fn(&N) -> Value + 'static) -> SchemaGetter {
1194    Rc::new(move |node| get(node_as::<N>(node)))
1195}
1196
1197/// A setter that writes a node of type `N`.
1198pub fn schema_setter<N: LexicalNode>(set: impl Fn(&mut N, Value) + 'static) -> SchemaSetter {
1199    Rc::new(move |node, value| set(node_as_mut::<N>(node), value))
1200}
1201
1202/// `withField(schema, {field})`: the property *is* a field of the node `N`
1203/// (`field` reads it, `field_mut` writes it), stored as its
1204/// [`SchemaValue`]. A parsed value the field's type can't hold leaves the
1205/// field as it is. A Rust node's `Clone` carries every field, so the clone
1206/// JS synthesizes for a declared field has nothing left to do. Add
1207/// [`when`](SchemaField::when) and [`derived`](SchemaField::derived) as JS
1208/// does in the options.
1209pub fn with_field<N: LexicalNode, V: SchemaValue + 'static>(
1210    schema: SerializationSchema,
1211    field: fn(&N) -> &V,
1212    field_mut: fn(&mut N) -> &mut V,
1213) -> Result<SchemaField, LexicalError> {
1214    not_nested_set("withField", &schema)?;
1215    // An optional property is absent when it has no value; any other one
1216    // writes `null`.
1217    let optional = matches!(schema.meta(), SerializationSchemaMeta::Optional { .. });
1218    Ok(SchemaField {
1219        schema,
1220        getter: Some(schema_getter::<N>(move |node| {
1221            match field(node).to_schema_value() {
1222                Value::Undefined if !optional => Value::Null,
1223                value => value,
1224            }
1225        })),
1226        when: None,
1227        setter: Some(schema_setter::<N>(move |node, value| {
1228            if let Some(value) = V::from_schema_value(&value) {
1229                *field_mut(node) = value;
1230            }
1231        })),
1232        derived: false,
1233    })
1234}
1235
1236/// `withAccessors(schema, {getter, setter, derived})`: the property is read
1237/// with `getter` and applied with `setter`; `None` declares that direction
1238/// deliberately unsupported (`null`): an import-only property, or one
1239/// derived on import, which the compact form leaves out.
1240pub fn with_accessors(
1241    schema: SerializationSchema,
1242    getter: Option<SchemaGetter>,
1243    setter: Option<SchemaSetter>,
1244) -> Result<SchemaField, LexicalError> {
1245    not_nested_set("withAccessors", &schema)?;
1246    Ok(SchemaField {
1247        schema,
1248        getter,
1249        when: None,
1250        setter,
1251        derived: false,
1252    })
1253}
1254
1255/// `NodeSerializationSchema`: the node-specific properties of a class's
1256/// JSON, as `nodeSchema<N>()({...})` declares them, in key order. Clones
1257/// are the same schema.
1258#[derive(Clone, Debug)]
1259pub struct NodeSchema(Rc<[(&'static str, SchemaField)]>);
1260
1261impl NodeSchema {
1262    /// `meta.fields`.
1263    pub fn fields(&self) -> &[(&'static str, SchemaField)] {
1264        &self.0
1265    }
1266
1267    /// This schema as a subclass resolves it when it overrides the setter
1268    /// that the property `key`'s field write stands in for
1269    /// (`SchemaFieldBase.method`, `resolveSchemaField`): the same
1270    /// properties in the same order, `key` applied with `setter`. A Rust
1271    /// class can't be asked which methods it overrides, so it gives the
1272    /// schemas of the classes it extends as it resolves them, in its
1273    /// [`LexicalNode::json_schema_chain`].
1274    pub fn with_setter(&self, key: &str, setter: SchemaSetter) -> NodeSchema {
1275        NodeSchema(
1276            self.0
1277                .iter()
1278                .map(|(k, field)| {
1279                    let mut field = field.clone();
1280                    if *k == key {
1281                        field.setter = Some(setter.clone());
1282                    }
1283                    (*k, field)
1284                })
1285                .collect(),
1286        )
1287    }
1288}
1289
1290/// `nodeSchema<N>()(fields)`.
1291pub fn node_schema(fields: Vec<(&'static str, SchemaField)>) -> Result<NodeSchema, LexicalError> {
1292    check_field_names("nodeSchema", fields.iter().map(|(k, f)| (*k, &f.schema)))?;
1293    Ok(NodeSchema(fields.into()))
1294}
1295
1296/// `ComposedSchema`: the serialization schema of a node class composed
1297/// across its config chain (`composeSchema`), compiled once per class.
1298struct ComposedSchema {
1299    /// Most derived first, the first declaration of a key winning: the
1300    /// order properties are written in.
1301    fields_derived_first: Vec<(&'static str, SchemaField)>,
1302    /// The same fields ancestors first: the order setters are applied in.
1303    fields_base_first: Vec<(&'static str, SchemaField)>,
1304}
1305
1306thread_local! {
1307    /// `NODE_CLASS_CACHE`'s `composed`, by the node's Rust type.
1308    static COMPOSED: RefCell<HashMap<TypeId, Rc<ComposedSchema>>> = RefCell::new(HashMap::new());
1309}
1310
1311/// `getComposedSchema(klass)`, of the class of `node`: the schemas of
1312/// [`LexicalNode::json_schema_chain`], composed.
1313fn composed_schema(node: &dyn LexicalNode) -> Rc<ComposedSchema> {
1314    let id = node.as_any().type_id();
1315    if let Some(composed) = COMPOSED.with(|c| c.borrow().get(&id).cloned()) {
1316        return composed;
1317    }
1318    let chain = node.json_schema_chain();
1319    let mut derived_first: Vec<(&'static str, SchemaField)> = Vec::new();
1320    for schema in &chain {
1321        for (key, field) in schema.fields() {
1322            if !derived_first.iter().any(|(k, _)| k == key) {
1323                derived_first.push((key, field.clone()));
1324            }
1325        }
1326    }
1327    let mut base_first: Vec<(&'static str, SchemaField)> = Vec::new();
1328    for schema in chain.iter().rev() {
1329        for (key, _) in schema.fields() {
1330            if !base_first.iter().any(|(k, _)| k == key) {
1331                let winner = derived_first
1332                    .iter()
1333                    .find(|(k, _)| k == key)
1334                    .expect("a composed key");
1335                base_first.push(winner.clone());
1336            }
1337        }
1338    }
1339    let composed = Rc::new(ComposedSchema {
1340        fields_derived_first: derived_first,
1341        fields_base_first: base_first,
1342    });
1343    COMPOSED.with(|c| c.borrow_mut().insert(id, composed.clone()));
1344    composed
1345}
1346
1347/// `getComposedSchemaFields(klass)`, of the class of `node`: every
1348/// node-specific property of its JSON, its flat NodeState whose value is a
1349/// schema first, then the composed schema's fields most derived first.
1350pub fn get_composed_schema_fields(node: &dyn LexicalNode) -> Vec<(String, SchemaField)> {
1351    let mut fields: Vec<(String, SchemaField)> = Vec::new();
1352    for required in node.state_configs() {
1353        if required.flat
1354            && let Some(schema) = required.state_config.schema()
1355            && !fields.iter().any(|(k, _)| k == required.state_config.key())
1356        {
1357            fields.push((
1358                required.state_config.key().to_owned(),
1359                SchemaField {
1360                    schema,
1361                    getter: None,
1362                    when: None,
1363                    setter: None,
1364                    derived: false,
1365                },
1366            ));
1367        }
1368    }
1369    for (key, field) in &composed_schema(node).fields_derived_first {
1370        fields.retain(|(k, _)| k != key);
1371        fields.push(((*key).to_owned(), field.clone()));
1372    }
1373    fields
1374}
1375
1376/// `$walkExportJSON(node, compact)`: the JSON the node's schema describes,
1377/// without its NodeState: `type` first in the compact form, an empty
1378/// `children` for an element, each exported property most derived first
1379/// (the compact form leaving out a default and a property derived on
1380/// import, and a `when` gating its property), then `type` and `version` in
1381/// the legacy form. What [`LexicalNode::export_json`] does for a class
1382/// without code of its own (JS's generated code).
1383pub fn walk_export_json(node: &dyn LexicalNode, compact: bool) -> Object {
1384    let composed = composed_schema(node);
1385    let mut json = Object::new();
1386    if compact {
1387        json.insert("type", node.get_type().into());
1388    }
1389    if node.element().is_some() {
1390        json.insert("children", Value::Array(Vec::new()));
1391    }
1392    for (key, field) in &composed.fields_derived_first {
1393        let Some(getter) = &field.getter else {
1394            continue;
1395        };
1396        if compact && field.setter.is_none() {
1397            continue;
1398        }
1399        let mut value = getter(node);
1400        if let Some(when) = &field.when
1401            && (field.is_compact_default(&value) || !when(node))
1402        {
1403            value = Value::Undefined;
1404        }
1405        if compact && field.is_compact_default(&value) {
1406            continue;
1407        }
1408        json.insert(*key, value);
1409    }
1410    if !compact {
1411        json.insert("type", node.get_type().into());
1412        json.insert("version", 1.0.into());
1413    }
1414    json
1415}
1416
1417/// `$walkJSONSetters`'s setters (`$walkSetters`): each property the node's
1418/// schema applies, ancestors first, parsed from `json` (a missing one as
1419/// its default). What [`LexicalNode::update_from_json`] does for a class
1420/// without code of its own; the flat NodeState is applied by the caller
1421/// first, as `$applyJSONSetters` does.
1422pub fn walk_update_from_json(node: &mut dyn LexicalNode, json: &Object) {
1423    let composed = composed_schema(node);
1424    for (key, field) in &composed.fields_base_first {
1425        if let Some(setter) = &field.setter {
1426            let parsed = field
1427                .schema
1428                .parse(json.get(key).unwrap_or(&Value::Undefined));
1429            setter(node, parsed);
1430        }
1431    }
1432}
1433
1434/// `$exportNodeJSONOnce(node, compact)`: the class's generated code where
1435/// it has some ([`LexicalNode::generated_export_json`]), otherwise the
1436/// walk of its schema.
1437pub fn export_node_json_once(node: &dyn LexicalNode, compact: bool) -> Object {
1438    node.generated_export_json(compact)
1439        .unwrap_or_else(|| walk_export_json(node, compact))
1440}
1441
1442/// `$applyJSONSetters(node, serializedNode)` without the flat NodeState,
1443/// which the caller applies first: the class's generated code where it has
1444/// some ([`LexicalNode::generated_update_from_json`]), otherwise the walk
1445/// of its schema.
1446pub fn apply_json_setters(node: &mut dyn LexicalNode, json: &Object) {
1447    if !node.generated_update_from_json(json) {
1448        walk_update_from_json(node, json);
1449    }
1450}
1451
1452#[cfg(test)]
1453mod tests {
1454    use super::*;
1455    use crate::json::parse;
1456
1457    /// The values each property of a node is given, one at a time: a
1458    /// corpus of every type and of the names, numbers and strings the
1459    /// schemas treat specially, as JS checks its generated parsers against
1460    /// the walk over the schema's domain and a fixed set of hostile values.
1461    fn hostile_values() -> Vec<Value> {
1462        let mut values = vec![Value::Undefined];
1463        for text in [
1464            "null",
1465            "true",
1466            "false",
1467            "0",
1468            "-0",
1469            "-1",
1470            "1",
1471            "1.5",
1472            "2",
1473            "3",
1474            "128",
1475            "129",
1476            "1e300",
1477            "\"\"",
1478            "\"0\"",
1479            "\"1\"",
1480            "\"1.5\"",
1481            "\"-1\"",
1482            "\"1e999\"",
1483            "\"0x10\"",
1484            "\" 1\"",
1485            "\"__proto__\"",
1486            "\"toString\"",
1487            "\"bold\"",
1488            "\"code\"",
1489            "\"unmergeable\"",
1490            "\"directionless\"",
1491            "\"token\"",
1492            "\"segmented\"",
1493            "\"normal\"",
1494            "\"ltr\"",
1495            "\"rtl\"",
1496            "\"center\"",
1497            "\"justify\"",
1498            "\"h1\"",
1499            "\"h6\"",
1500            "\"h7\"",
1501            "\"number\"",
1502            "\"bullet\"",
1503            "\"check\"",
1504            "\"ol\"",
1505            "\"ul\"",
1506            "\"x\"",
1507            "\"https://lexical.dev\"",
1508            "[]",
1509            "[\"a\",1,null,\"b\"]",
1510            "[\"b\",\"a\",\"b\"]",
1511            "{}",
1512            "{\"a\":1}",
1513        ] {
1514            values.push(parse(text).expect("JSON"));
1515        }
1516        values
1517    }
1518
1519    /// Whether `node`'s generated `updateFromJSON` and the walk of its
1520    /// schema leave it the same for each hostile value of each key, and
1521    /// then whether its generated `exportJSON` is the walk's in both forms
1522    /// (`exports`, for a node whose export reads no editor state).
1523    fn check_agrees(node: &dyn LexicalNode, keys: &[&str], exports: bool) {
1524        for key in keys {
1525            for value in hostile_values() {
1526                let mut json = Object::new();
1527                json.insert(*key, value.clone());
1528                let mut generated = node.clone_node();
1529                assert!(generated.generated_update_from_json(&json));
1530                let mut walked = node.clone_node();
1531                walk_update_from_json(walked.as_node_mut(), &json);
1532                assert_eq!(
1533                    format!("{generated:?}"),
1534                    format!("{walked:?}"),
1535                    "{} {key}: {value}",
1536                    node.get_type()
1537                );
1538                if exports {
1539                    for compact in [false, true] {
1540                        assert_eq!(
1541                            Value::Object(
1542                                generated
1543                                    .generated_export_json(compact)
1544                                    .expect("generated code")
1545                            )
1546                            .to_string(),
1547                            Value::Object(walk_export_json(&*generated, compact)).to_string(),
1548                            "{} {key}: {value} (compact: {compact})",
1549                            node.get_type()
1550                        );
1551                    }
1552                }
1553            }
1554        }
1555    }
1556
1557    const ELEMENT_KEYS: [&str; 5] = ["direction", "format", "indent", "textFormat", "textStyle"];
1558    const TEXT_KEYS: [&str; 5] = ["detail", "format", "mode", "style", "text"];
1559
1560    fn keys<'a>(own: &[&'a str], base: &[&'a str]) -> Vec<&'a str> {
1561        own.iter().chain(base).copied().collect()
1562    }
1563
1564    // upstream: lexical/src/__tests__/unit/LexicalGeneratedJSON.test.ts::generated exportJSON > every generated parser agrees with the schema-driven walk
1565    #[test]
1566    fn generated_json_is_the_walk_of_the_schema() {
1567        check_agrees(
1568            &crate::nodes::paragraph::ParagraphNode::default(),
1569            &ELEMENT_KEYS,
1570            false,
1571        );
1572        check_agrees(&crate::nodes::text::TextNode::default(), &TEXT_KEYS, true);
1573        check_agrees(&crate::nodes::tab::TabNode::default(), &TEXT_KEYS, true);
1574        check_agrees(
1575            &crate::nodes::line_break::LineBreakNode::default(),
1576            &[],
1577            true,
1578        );
1579        #[cfg(feature = "rich-text")]
1580        {
1581            check_agrees(
1582                &crate::rich_text::HeadingNode::default(),
1583                &keys(&["tag"], &ELEMENT_KEYS),
1584                false,
1585            );
1586            check_agrees(
1587                &crate::rich_text::QuoteNode::default(),
1588                &ELEMENT_KEYS,
1589                false,
1590            );
1591        }
1592        #[cfg(feature = "list")]
1593        {
1594            check_agrees(
1595                &crate::list::ListNode::default(),
1596                &keys(&["listType", "start", "tag"], &ELEMENT_KEYS),
1597                false,
1598            );
1599            check_agrees(
1600                &crate::list::ListItemNode::default(),
1601                &keys(&["checked", "indent", "value"], &ELEMENT_KEYS),
1602                false,
1603            );
1604        }
1605        #[cfg(feature = "link")]
1606        {
1607            let link = ["rel", "target", "title", "url"];
1608            check_agrees(
1609                &crate::link::LinkNode::default(),
1610                &keys(&link, &ELEMENT_KEYS),
1611                false,
1612            );
1613            check_agrees(
1614                &crate::link::AutoLinkNode::default(),
1615                &keys(&keys(&["isUnlinked"], &link), &ELEMENT_KEYS),
1616                false,
1617            );
1618        }
1619        #[cfg(feature = "code")]
1620        {
1621            check_agrees(
1622                &crate::code::CodeNode::default(),
1623                &keys(&["language", "theme"], &ELEMENT_KEYS),
1624                false,
1625            );
1626            check_agrees(
1627                &crate::code::CodeHighlightNode::default(),
1628                &keys(&["highlightType"], &TEXT_KEYS),
1629                true,
1630            );
1631        }
1632        #[cfg(feature = "mark")]
1633        check_agrees(
1634            &crate::mark::MarkNode::default(),
1635            &keys(&["ids"], &ELEMENT_KEYS),
1636            false,
1637        );
1638        #[cfg(feature = "overflow")]
1639        check_agrees(
1640            &crate::overflow::OverflowNode::default(),
1641            &ELEMENT_KEYS,
1642            false,
1643        );
1644        #[cfg(feature = "hashtag")]
1645        check_agrees(&crate::hashtag::HashtagNode::default(), &TEXT_KEYS, true);
1646    }
1647}