Skip to main content

odk_cli/loaders/
json_schema.rs

1//! JSON Schema loader
2//!
3//! Loads a standard [JSON Schema](https://json-schema.org) document into a
4//! `CompiledSchema`, so schemas that already exist elsewhere become ODK inputs
5//! without being rewritten in ODK's own format. The motivating case is Rust
6//! types that derive their schema via `schemars` (for example Resonance's
7//! `ProjectDocument`), where the Rust type is the source of truth and the JSON
8//! Schema is generated from it.
9//!
10//! Draft 2020-12 (`$defs`) and draft-07 (`definitions`) are both accepted; they
11//! differ here only in where named subschemas live.
12//!
13//! # Mapping
14//!
15//! | JSON Schema                        | CompiledSchema                     |
16//! |------------------------------------|------------------------------------|
17//! | `title`                            | schema name (falls back to file stem) |
18//! | root object with `properties`      | a model named after the title      |
19//! | `$defs` / `definitions` entry      | a model, or a union if it is a string `enum` |
20//! | `properties.X`                     | a field, optional unless listed in `required` |
21//! | `$ref: "#/$defs/Foo"`              | `CompiledType::Ref { name: "Foo" }`|
22//! | `type: [T, "null"]`                | type `T`, field marked optional    |
23//! | `oneOf` / `anyOf`                  | `CompiledType::Union`              |
24//! | `items`                            | `CompiledType::Array`              |
25//! | inline `type: object`              | `CompiledType::Object`             |
26//! | `minLength`, `maximum`, `pattern`, … | `FieldConstraints`               |
27//!
28//! # Not represented
29//!
30//! Keywords with no ODK equivalent are dropped rather than approximated:
31//! multi-branch `allOf` composition, `not`, conditional `if`/`then`/`else`,
32//! `patternProperties`, and `additionalProperties` schemas. A schema relying on
33//! them loads, but the constraint is not carried into the IR.
34//!
35//! A *single-branch* `allOf` is unwrapped, because that is how schemars emits a
36//! `$ref` on a field that also has a description, and treating it as
37//! unrepresentable would silently drop the reference.
38
39use std::collections::HashMap;
40use std::path::Path;
41
42use odk_schema::{
43    CompiledField, CompiledModel, CompiledSchema, CompiledType, CompiledUnion,
44    CompiledUnionVariant, FieldConstraints, LiteralValue, ScalarType,
45};
46use serde_json::Value;
47
48/// Error type for JSON Schema loading.
49#[derive(Debug)]
50pub enum JsonSchemaLoadError {
51    Io(std::io::Error),
52    Parse(serde_json::Error),
53    Validation(String),
54}
55
56impl std::fmt::Display for JsonSchemaLoadError {
57    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58        match self {
59            JsonSchemaLoadError::Io(e) => write!(f, "IO error: {}", e),
60            JsonSchemaLoadError::Parse(e) => write!(f, "JSON parse error: {}", e),
61            JsonSchemaLoadError::Validation(msg) => write!(f, "Validation error: {}", msg),
62        }
63    }
64}
65
66impl std::error::Error for JsonSchemaLoadError {}
67
68impl From<std::io::Error> for JsonSchemaLoadError {
69    fn from(e: std::io::Error) -> Self {
70        JsonSchemaLoadError::Io(e)
71    }
72}
73
74impl From<serde_json::Error> for JsonSchemaLoadError {
75    fn from(e: serde_json::Error) -> Self {
76        JsonSchemaLoadError::Parse(e)
77    }
78}
79
80/// Whether a JSON document looks like a JSON Schema rather than an ODK schema.
81///
82/// ODK's own JSON format is keyed by `models`, so that wins if both are somehow
83/// present: this only claims documents that are unambiguously JSON Schema.
84pub fn is_json_schema(content: &str) -> bool {
85    let Ok(value) = serde_json::from_str::<Value>(content) else {
86        return false;
87    };
88    let Some(obj) = value.as_object() else {
89        return false;
90    };
91
92    if obj.contains_key("models") {
93        return false;
94    }
95
96    let declared = obj
97        .get("$schema")
98        .and_then(Value::as_str)
99        .is_some_and(|s| s.contains("json-schema.org"));
100
101    declared
102        || obj.contains_key("$defs")
103        || obj.contains_key("definitions")
104        || (obj.contains_key("properties")
105            && obj.get("type").and_then(Value::as_str) == Some("object"))
106}
107
108/// Load a JSON Schema document from a file.
109///
110/// # Errors
111///
112/// Returns an error if the file cannot be read, is not valid JSON, or is not an
113/// object at the root.
114pub fn load_json_schema(path: &Path) -> Result<CompiledSchema, JsonSchemaLoadError> {
115    let content = std::fs::read_to_string(path)?;
116    let fallback_name = path
117        .file_stem()
118        .and_then(|s| s.to_str())
119        .map(sanitize_name)
120        .unwrap_or_else(|| "Schema".to_string());
121
122    parse_json_schema(&content, &fallback_name)
123}
124
125/// Convert a JSON Schema document into a `CompiledSchema`.
126///
127/// # Errors
128///
129/// Returns an error if the document is not valid JSON or is not a JSON object.
130pub fn parse_json_schema(
131    content: &str,
132    fallback_name: &str,
133) -> Result<CompiledSchema, JsonSchemaLoadError> {
134    let root: Value = serde_json::from_str(content)?;
135    let obj = root
136        .as_object()
137        .ok_or_else(|| JsonSchemaLoadError::Validation("root must be a JSON object".into()))?;
138
139    let title = obj.get("title").and_then(Value::as_str);
140    let name = title.map_or_else(|| fallback_name.to_string(), sanitize_name);
141
142    let mut schema = CompiledSchema::new(&name);
143
144    // Named subschemas: 2020-12 puts them in $defs, draft-07 in definitions
145    let defs = obj
146        .get("$defs")
147        .or_else(|| obj.get("definitions"))
148        .and_then(Value::as_object);
149
150    if let Some(defs) = defs {
151        for (def_name, def) in defs {
152            let def_name = sanitize_name(def_name);
153
154            if let Some(union) = string_enum_union(&def_name, def) {
155                schema.add_union(union);
156            } else {
157                schema.add_model(object_model(&def_name, def));
158            }
159        }
160    }
161
162    // The root itself is a model when it describes an object. A schema that is
163    // only a container for $defs (no properties of its own) contributes none
164    if obj.contains_key("properties") {
165        schema.add_model(object_model(&name, &root));
166    }
167
168    Ok(schema)
169}
170
171/// Build a model from an object subschema.
172fn object_model(name: &str, schema: &Value) -> CompiledModel {
173    let mut model = CompiledModel::new(name);
174
175    if let Some(desc) = schema.get("description").and_then(Value::as_str) {
176        model.description = Some(desc.to_string());
177    }
178
179    let required: Vec<&str> = schema
180        .get("required")
181        .and_then(Value::as_array)
182        .map(|a| a.iter().filter_map(Value::as_str).collect())
183        .unwrap_or_default();
184
185    if let Some(props) = schema.get("properties").and_then(Value::as_object) {
186        for (prop_name, prop) in props {
187            let (field_type, nullable) = convert_type(prop);
188
189            let mut field = CompiledField::new(prop_name, field_type);
190
191            // A property is optional if it is absent from `required`, or if its
192            // type admits null. schemars emits both shapes depending on whether
193            // the Rust field is `Option<T>` or carries `#[serde(default)]`
194            if nullable || !required.contains(&prop_name.as_str()) {
195                field = field.optional();
196            }
197
198            if let Some(desc) = prop.get("description").and_then(Value::as_str) {
199                field.description = Some(desc.to_string());
200            }
201
202            field.constraints = constraints(prop);
203
204            model.add_field(field);
205        }
206    }
207
208    model
209}
210
211/// Build a union from a subschema whose `enum` is a list of strings.
212fn string_enum_union(name: &str, schema: &Value) -> Option<CompiledUnion> {
213    let values = schema.get("enum")?.as_array()?;
214
215    let variants: Vec<CompiledUnionVariant> = values
216        .iter()
217        .filter_map(Value::as_str)
218        .map(|v| CompiledUnionVariant {
219            name: v.to_string(),
220            // the literal is what makes this a value union in TypeSpec; without
221            // it the variant name is emitted as a bare identifier and fails to
222            // resolve
223            variant_type: Some(CompiledType::Literal {
224                value: LiteralValue::String(v.to_string()),
225            }),
226        })
227        .collect();
228
229    // Mixed-type enums are not string unions; leave them to the type mapper
230    if variants.len() != values.len() || variants.is_empty() {
231        return None;
232    }
233
234    Some(CompiledUnion {
235        name: name.to_string(),
236        variants,
237        tag: None,
238        rename_all: None,
239        description: schema
240            .get("description")
241            .and_then(Value::as_str)
242            .map(ToString::to_string),
243        extensions: odk_schema::Extensions::default(),
244        source: None,
245    })
246}
247
248/// Convert a subschema to a type, reporting whether it also admits null.
249fn convert_type(schema: &Value) -> (CompiledType, bool) {
250    if let Some(reference) = schema.get("$ref").and_then(Value::as_str) {
251        return (
252            CompiledType::Ref {
253                name: ref_name(reference),
254            },
255            false,
256        );
257    }
258
259    // schemars wraps a $ref in a single-branch allOf whenever the property also
260    // carries a description, so unwrapping that is what keeps references from
261    // being silently flattened to an empty type
262    if let Some([only]) = schema
263        .get("allOf")
264        .and_then(Value::as_array)
265        .map(Vec::as_slice)
266    {
267        return convert_type(only);
268    }
269
270    // oneOf/anyOf: a single non-null branch is the common `Option<T>` shape and
271    // collapses to that branch; anything else stays a union
272    for key in ["oneOf", "anyOf"] {
273        if let Some(branches) = schema.get(key).and_then(Value::as_array) {
274            let non_null: Vec<&Value> = branches.iter().filter(|b| !is_null_schema(b)).collect();
275            let nullable = non_null.len() < branches.len();
276
277            if non_null.len() == 1 {
278                let (inner, inner_nullable) = convert_type(non_null[0]);
279                return (inner, nullable || inner_nullable);
280            }
281
282            let variants: Vec<CompiledType> = non_null.iter().map(|b| convert_type(b).0).collect();
283
284            if !variants.is_empty() {
285                return (CompiledType::Union { variants }, nullable);
286            }
287        }
288    }
289
290    // `type` may be a string or a list including "null"
291    let (type_name, nullable) = match schema.get("type") {
292        Some(Value::String(s)) => (Some(s.as_str()), false),
293        Some(Value::Array(types)) => {
294            let nullable = types.iter().any(|t| t.as_str() == Some("null"));
295            let first = types
296                .iter()
297                .filter_map(Value::as_str)
298                .find(|t| *t != "null");
299            (first, nullable)
300        }
301        _ => (None, false),
302    };
303
304    let format = schema.get("format").and_then(Value::as_str);
305
306    let compiled = match type_name {
307        Some("string") => CompiledType::Scalar {
308            name: string_scalar(format),
309        },
310        Some("integer") => CompiledType::Scalar {
311            name: integer_scalar(format),
312        },
313        Some("number") => CompiledType::Scalar {
314            name: match format {
315                Some("float") => ScalarType::Float32,
316                _ => ScalarType::Float64,
317            },
318        },
319        Some("boolean") => CompiledType::Scalar {
320            name: ScalarType::Boolean,
321        },
322        Some("array") => {
323            let items = schema.get("items").map_or(
324                CompiledType::Scalar {
325                    name: ScalarType::Unknown,
326                },
327                |i| convert_type(i).0,
328            );
329
330            CompiledType::Array {
331                items: Box::new(items),
332                length: None,
333            }
334        }
335        Some("object") => {
336            // An inline object with properties becomes a structural type; a bare
337            // `type: object` (free-form map) has nothing to describe
338            if schema.get("properties").is_some() {
339                let model = object_model("", schema);
340                CompiledType::Object {
341                    fields: model.fields,
342                }
343            } else {
344                CompiledType::Scalar {
345                    name: ScalarType::Unknown,
346                }
347            }
348        }
349        _ => CompiledType::Scalar {
350            name: ScalarType::Unknown,
351        },
352    };
353
354    (compiled, nullable)
355}
356
357/// Map a string `format` to the narrowest scalar ODK has.
358fn string_scalar(format: Option<&str>) -> ScalarType {
359    match format {
360        Some("date-time") => ScalarType::UtcDateTime,
361        Some("date") => ScalarType::PlainDate,
362        Some("time") => ScalarType::PlainTime,
363        Some("duration") => ScalarType::Duration,
364        Some("uri" | "url") => ScalarType::Url,
365        Some("byte" | "binary") => ScalarType::Bytes,
366        // uuid and email stay strings; the format is preserved in constraints
367        _ => ScalarType::String,
368    }
369}
370
371/// Map an integer `format` to a width. JSON Schema does not bound integers by
372/// default, so the wider type is the safe assumption.
373fn integer_scalar(format: Option<&str>) -> ScalarType {
374    match format {
375        Some("int32" | "uint32") => ScalarType::Int32,
376        _ => ScalarType::Int64,
377    }
378}
379
380/// Extract the trailing name from a local `$ref` pointer.
381fn ref_name(reference: &str) -> String {
382    reference
383        .rsplit('/')
384        .next()
385        .map_or_else(|| sanitize_name(reference), sanitize_name)
386}
387
388/// Whether a subschema is exactly the null type.
389fn is_null_schema(schema: &Value) -> bool {
390    schema.get("type").and_then(Value::as_str) == Some("null")
391}
392
393/// Collect validation keywords ODK can represent.
394fn constraints(schema: &Value) -> Option<FieldConstraints> {
395    let num = |key: &str| schema.get(key).and_then(Value::as_f64);
396    let uint = |key: &str| schema.get(key).and_then(Value::as_u64);
397
398    // `format` is only carried for strings: TypeSpec's @format targets strings,
399    // and a numeric format (schemars stamps uint32, double, and friends) has
400    // already been folded into the scalar choice
401    let is_string = match schema.get("type") {
402        Some(Value::String(s)) => s == "string",
403        Some(Value::Array(types)) => types.iter().any(|t| t.as_str() == Some("string")),
404        _ => false,
405    };
406
407    let format = schema
408        .get("format")
409        .and_then(Value::as_str)
410        .filter(|_| is_string)
411        // formats that became a scalar carry no extra information here
412        .filter(|f| {
413            !matches!(
414                *f,
415                "date-time" | "date" | "time" | "duration" | "uri" | "url" | "byte" | "binary"
416            )
417        })
418        .map(ToString::to_string);
419
420    let constraints = FieldConstraints {
421        min_length: uint("minLength"),
422        max_length: uint("maxLength"),
423        min_value: num("minimum"),
424        max_value: num("maximum"),
425        pattern: schema
426            .get("pattern")
427            .and_then(Value::as_str)
428            .map(ToString::to_string),
429        format,
430        multiple_of: num("multipleOf"),
431    };
432
433    let empty = constraints.min_length.is_none()
434        && constraints.max_length.is_none()
435        && constraints.min_value.is_none()
436        && constraints.max_value.is_none()
437        && constraints.pattern.is_none()
438        && constraints.format.is_none()
439        && constraints.multiple_of.is_none();
440
441    if empty { None } else { Some(constraints) }
442}
443
444/// Make a name safe to emit as a TypeSpec identifier.
445fn sanitize_name(name: &str) -> String {
446    let cleaned: String = name
447        .chars()
448        .map(|c| if c.is_alphanumeric() { c } else { '_' })
449        .collect();
450
451    // An identifier cannot lead with a digit
452    if cleaned.chars().next().is_some_and(char::is_numeric) {
453        format!("_{cleaned}")
454    } else {
455        cleaned
456    }
457}
458
459/// Named lookup of a schema's models, for tests and callers that want one.
460#[allow(dead_code)]
461pub fn models_by_name(schema: &CompiledSchema) -> HashMap<&str, &CompiledModel> {
462    schema.models.iter().map(|m| (m.name.as_str(), m)).collect()
463}
464
465#[cfg(test)]
466mod tests {
467    use super::*;
468
469    fn load(json: &str) -> CompiledSchema {
470        parse_json_schema(json, "Fallback").expect("schema parses")
471    }
472
473    fn field<'a>(model: &'a CompiledModel, name: &str) -> &'a CompiledField {
474        model
475            .fields
476            .iter()
477            .find(|f| f.name == name)
478            .unwrap_or_else(|| panic!("field {name} missing"))
479    }
480
481    #[test]
482    fn detects_json_schema_and_rejects_odk_schema() {
483        assert!(is_json_schema(
484            r#"{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object","properties":{}}"#
485        ));
486        assert!(is_json_schema(r#"{"$defs":{"A":{"type":"object"}}}"#));
487        assert!(is_json_schema(
488            r#"{"type":"object","properties":{"a":{"type":"string"}}}"#
489        ));
490
491        // ODK's own format must keep winning
492        assert!(!is_json_schema(
493            r#"{"name":"API","models":{"User":{"fields":{}}}}"#
494        ));
495        assert!(!is_json_schema("not json"));
496        assert!(!is_json_schema("[]"));
497    }
498
499    #[test]
500    fn root_object_becomes_a_model_named_after_the_title() {
501        let schema = load(
502            r#"{
503              "title": "ProjectDocument",
504              "type": "object",
505              "properties": { "name": { "type": "string" } },
506              "required": ["name"]
507            }"#,
508        );
509
510        assert_eq!(schema.name, "ProjectDocument");
511        assert_eq!(schema.models.len(), 1);
512        assert_eq!(schema.models[0].name, "ProjectDocument");
513    }
514
515    #[test]
516    fn falls_back_to_the_given_name_when_untitled() {
517        let schema = load(r#"{"type":"object","properties":{"a":{"type":"string"}}}"#);
518        assert_eq!(schema.name, "Fallback");
519    }
520
521    #[test]
522    fn required_drives_optionality() {
523        let schema = load(
524            r#"{
525              "title": "T", "type": "object",
526              "properties": { "a": { "type": "string" }, "b": { "type": "string" } },
527              "required": ["a"]
528            }"#,
529        );
530        let model = &schema.models[0];
531
532        assert_eq!(field(model, "a").optional, None);
533        assert_eq!(field(model, "b").optional, Some(true));
534    }
535
536    #[test]
537    fn a_nullable_type_is_optional_even_when_required() {
538        let schema = load(
539            r#"{
540              "title": "T", "type": "object",
541              "properties": { "a": { "type": ["string", "null"] } },
542              "required": ["a"]
543            }"#,
544        );
545
546        let a = field(&schema.models[0], "a");
547        assert_eq!(a.optional, Some(true));
548        assert!(matches!(
549            a.field_type,
550            CompiledType::Scalar {
551                name: ScalarType::String
552            }
553        ));
554    }
555
556    #[test]
557    fn scalars_and_formats_map_to_the_narrowest_type() {
558        let schema = load(
559            r#"{
560              "title": "T", "type": "object",
561              "properties": {
562                "s": { "type": "string" },
563                "stamp": { "type": "string", "format": "date-time" },
564                "id": { "type": "string", "format": "uuid" },
565                "i": { "type": "integer" },
566                "i32": { "type": "integer", "format": "int32" },
567                "f": { "type": "number" },
568                "b": { "type": "boolean" }
569              }
570            }"#,
571        );
572        let m = &schema.models[0];
573
574        assert!(matches!(
575            field(m, "s").field_type,
576            CompiledType::Scalar {
577                name: ScalarType::String
578            }
579        ));
580        assert!(matches!(
581            field(m, "stamp").field_type,
582            CompiledType::Scalar {
583                name: ScalarType::UtcDateTime
584            }
585        ));
586        assert!(matches!(
587            field(m, "i").field_type,
588            CompiledType::Scalar {
589                name: ScalarType::Int64
590            }
591        ));
592        assert!(matches!(
593            field(m, "i32").field_type,
594            CompiledType::Scalar {
595                name: ScalarType::Int32
596            }
597        ));
598        assert!(matches!(
599            field(m, "f").field_type,
600            CompiledType::Scalar {
601                name: ScalarType::Float64
602            }
603        ));
604        assert!(matches!(
605            field(m, "b").field_type,
606            CompiledType::Scalar {
607                name: ScalarType::Boolean
608            }
609        ));
610
611        // uuid stays a string but keeps the format as a constraint
612        let id = field(m, "id");
613        assert!(matches!(
614            id.field_type,
615            CompiledType::Scalar {
616                name: ScalarType::String
617            }
618        ));
619        assert_eq!(
620            id.constraints.as_ref().unwrap().format.as_deref(),
621            Some("uuid")
622        );
623    }
624
625    #[test]
626    fn refs_resolve_to_the_definition_name() {
627        let schema = load(
628            r##"{
629              "title": "T", "type": "object",
630              "properties": { "track": { "$ref": "#/$defs/TrackManifest" } },
631              "$defs": { "TrackManifest": { "type": "object", "properties": { "id": { "type": "string" } } } }
632            }"##,
633        );
634
635        let root = schema.models.iter().find(|m| m.name == "T").unwrap();
636        assert!(matches!(
637            &field(root, "track").field_type,
638            CompiledType::Ref { name } if name == "TrackManifest"
639        ));
640        assert!(schema.models.iter().any(|m| m.name == "TrackManifest"));
641    }
642
643    #[test]
644    fn a_single_branch_all_of_unwraps_to_its_ref() {
645        // the shape schemars emits for a described $ref field
646        let schema = load(
647            r##"{
648              "title": "T", "type": "object",
649              "properties": {
650                "project": {
651                  "description": "the manifest",
652                  "allOf": [{ "$ref": "#/definitions/ProjectManifest" }]
653                }
654              },
655              "definitions": { "ProjectManifest": { "type": "object", "properties": {} } }
656            }"##,
657        );
658
659        let root = schema.models.iter().find(|m| m.name == "T").unwrap();
660        let project = field(root, "project");
661        assert!(matches!(
662            &project.field_type,
663            CompiledType::Ref { name } if name == "ProjectManifest"
664        ));
665        assert_eq!(project.description.as_deref(), Some("the manifest"));
666    }
667
668    #[test]
669    fn arrays_carry_their_item_type() {
670        let schema = load(
671            r##"{
672              "title": "T", "type": "object",
673              "properties": { "tracks": { "type": "array", "items": { "$ref": "#/$defs/Track" } } },
674              "$defs": { "Track": { "type": "object", "properties": {} } }
675            }"##,
676        );
677
678        let root = schema.models.iter().find(|m| m.name == "T").unwrap();
679        let CompiledType::Array { items, .. } = &field(root, "tracks").field_type else {
680            panic!("expected an array");
681        };
682        assert!(matches!(items.as_ref(), CompiledType::Ref { name } if name == "Track"));
683    }
684
685    #[test]
686    fn a_string_enum_definition_becomes_a_union() {
687        let schema = load(
688            r#"{
689              "title": "T",
690              "$defs": { "TrackType": { "enum": ["audio", "midi", "bus", "master"] } }
691            }"#,
692        );
693
694        assert_eq!(schema.unions.len(), 1);
695        let union = &schema.unions[0];
696        assert_eq!(union.name, "TrackType");
697        let names: Vec<&str> = union.variants.iter().map(|v| v.name.as_str()).collect();
698        assert_eq!(names, ["audio", "midi", "bus", "master"]);
699    }
700
701    #[test]
702    fn option_shaped_one_of_collapses_to_its_branch() {
703        let schema = load(
704            r#"{
705              "title": "T", "type": "object",
706              "properties": { "region": { "oneOf": [{ "type": "string" }, { "type": "null" }] } },
707              "required": ["region"]
708            }"#,
709        );
710
711        let region = field(&schema.models[0], "region");
712        assert_eq!(region.optional, Some(true));
713        assert!(matches!(
714            region.field_type,
715            CompiledType::Scalar {
716                name: ScalarType::String
717            }
718        ));
719    }
720
721    #[test]
722    fn a_multi_branch_one_of_stays_a_union() {
723        let schema = load(
724            r#"{
725              "title": "T", "type": "object",
726              "properties": { "v": { "oneOf": [{ "type": "string" }, { "type": "integer" }] } }
727            }"#,
728        );
729
730        let CompiledType::Union { variants } = &field(&schema.models[0], "v").field_type else {
731            panic!("expected a union");
732        };
733        assert_eq!(variants.len(), 2);
734    }
735
736    #[test]
737    fn inline_objects_become_structural_types() {
738        let schema = load(
739            r#"{
740              "title": "T", "type": "object",
741              "properties": {
742                "point": {
743                  "type": "object",
744                  "properties": { "x": { "type": "number" }, "y": { "type": "number" } },
745                  "required": ["x", "y"]
746                }
747              }
748            }"#,
749        );
750
751        let CompiledType::Object { fields } = &field(&schema.models[0], "point").field_type else {
752            panic!("expected an inline object");
753        };
754        assert_eq!(fields.len(), 2);
755    }
756
757    #[test]
758    fn validation_keywords_become_constraints() {
759        let schema = load(
760            r#"{
761              "title": "T", "type": "object",
762              "properties": {
763                "tempo": { "type": "number", "minimum": 20.0, "maximum": 300.0 },
764                "name": { "type": "string", "minLength": 1, "maxLength": 64, "pattern": "^[a-z]+$" }
765              }
766            }"#,
767        );
768        let m = &schema.models[0];
769
770        let tempo = field(m, "tempo").constraints.as_ref().unwrap();
771        assert_eq!(tempo.min_value, Some(20.0));
772        assert_eq!(tempo.max_value, Some(300.0));
773
774        let name = field(m, "name").constraints.as_ref().unwrap();
775        assert_eq!(name.min_length, Some(1));
776        assert_eq!(name.max_length, Some(64));
777        assert_eq!(name.pattern.as_deref(), Some("^[a-z]+$"));
778
779        // a field with no validation keywords carries no constraints at all
780        assert!(field(m, "tempo").description.is_none());
781    }
782
783    #[test]
784    fn draft_07_definitions_are_read_like_defs() {
785        let schema = load(
786            r#"{
787              "title": "T",
788              "definitions": { "Marker": { "type": "object", "properties": { "id": { "type": "string" } } } }
789            }"#,
790        );
791
792        assert!(schema.models.iter().any(|m| m.name == "Marker"));
793    }
794
795    #[test]
796    fn descriptions_carry_through() {
797        let schema = load(
798            r#"{
799              "title": "T", "type": "object", "description": "A project",
800              "properties": { "a": { "type": "string", "description": "the a" } }
801            }"#,
802        );
803
804        assert_eq!(schema.models[0].description.as_deref(), Some("A project"));
805        assert_eq!(
806            field(&schema.models[0], "a").description.as_deref(),
807            Some("the a")
808        );
809    }
810
811    #[test]
812    fn names_that_are_not_identifiers_are_sanitized() {
813        let schema = load(r#"{"$defs": { "foo-bar": { "type": "object", "properties": {} } }}"#);
814        assert!(schema.models.iter().any(|m| m.name == "foo_bar"));
815
816        assert_eq!(sanitize_name("2fast"), "_2fast");
817    }
818
819    #[test]
820    fn a_defs_only_document_contributes_no_root_model() {
821        let schema = load(r#"{"title": "T", "$defs": {"A": {"type":"object","properties":{}}}}"#);
822
823        assert_eq!(schema.models.len(), 1);
824        assert_eq!(schema.models[0].name, "A");
825    }
826
827    #[test]
828    fn a_non_object_root_is_rejected() {
829        assert!(parse_json_schema("[]", "X").is_err());
830        assert!(parse_json_schema("{", "X").is_err());
831    }
832}