Skip to main content

nitr_std/validate/
schema_json.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2// This file is part of Nitr.
3// See https://nitrweb.com/ for more information
4// Copyright (C) 2024-present Jose Quintana <joseluisq.net>
5
6//! JSON Schema (2020-12) export of a compiled schema: the document view
7//! of what the checker enforces, for the OpenAPI generator.
8//!
9//! Every rule key maps to its standard keyword where one exists and to an
10//! `x-nitr-*` extension otherwise, so nothing the checker does is
11//! invisible in the document and nothing the document claims is
12//! unenforced. Literal text rules become regex-escaped `pattern`s, so a
13//! downstream validator matches the literal, never a metacharacter.
14//! Custom checks cannot be serialized: their mandatory `description` is
15//! their representation, marked `x-nitr-enforced: "custom"`.
16//!
17//! Output is deterministic: `serde_json::Map` is a `BTreeMap` in this
18//! workspace (`preserve_order` is off), and every list keeps the order the
19//! schema declared.
20
21use std::collections::BTreeMap;
22
23use serde_json::{Map, Value as Json, json};
24
25use super::format::{Format, FormatRule};
26use super::{Group, Kind, Literal, Rule, SchemaDef, TimeBound, TypePattern};
27
28/// Named component schemas collected while exporting: a titled schema
29/// is emitted once under `components/schemas/<title>` and referenced
30/// everywhere else.
31pub type Components = BTreeMap<String, Json>;
32
33/// The `$ref` a titled component is reached through.
34fn reference(title: &str) -> Json {
35    json!({ "$ref": format!("#/components/schemas/{title}") })
36}
37
38/// Exports a schema, registering it and any titled schema nested in it
39/// in `components`. A titled schema comes back as a `$ref`, an untitled
40/// one inline. Two *different* schemas sharing a title cannot share a
41/// component name, and the title is the script author's choice, so the
42/// later one takes a numbered suffix (`Note_2`) rather than failing a
43/// build that may not even serve the document. Deterministic: the order
44/// is the route order the generator walks.
45pub(crate) fn export(def: &SchemaDef, components: &mut Components) -> Result<Json, String> {
46    let object = object_schema(def, components)?;
47    let Some(title) = &def.title else {
48        return Ok(object);
49    };
50    let mut name = title.clone();
51    let mut n = 1;
52    loop {
53        match components.get(&name) {
54            Some(existing) if *existing == object => return Ok(reference(&name)),
55            Some(_) => {
56                n += 1;
57                name = format!("{title}_{n}");
58            }
59            None => {
60                let mut object = object;
61                if let Some(map) = object.as_object_mut() {
62                    map.insert("title".into(), json!(name));
63                }
64                components.insert(name.clone(), object);
65                return Ok(reference(&name));
66            }
67        }
68    }
69}
70
71/// The object schema of a `SchemaDef`, without the `$ref` indirection.
72fn object_schema(def: &SchemaDef, components: &mut Components) -> Result<Json, String> {
73    let mut out = Map::new();
74    out.insert("type".into(), json!("object"));
75    if let Some(title) = &def.title {
76        out.insert("title".into(), json!(title));
77    }
78    let mut properties = Map::new();
79    let mut required = Vec::new();
80    for (name, rule) in &def.fields {
81        properties.insert(name.clone(), rule_schema(rule, components)?);
82        if rule.required {
83            required.push(json!(name));
84        }
85    }
86    out.insert("properties".into(), Json::Object(properties));
87    if !required.is_empty() {
88        out.insert("required".into(), Json::Array(required));
89    }
90    // Truthful: `check_fields` strips undeclared fields (or reports them
91    // in strict mode); either way an extra property is never data.
92    out.insert("additionalProperties".into(), json!(false));
93
94    cross_field(def, &mut out);
95
96    if !def.checks.is_empty() {
97        let mut description = String::from("Constraints:");
98        let mut list = Vec::with_capacity(def.checks.len());
99        for check in &def.checks {
100            description.push_str("\n- ");
101            description.push_str(&check.description);
102            list.push(json!(check.description));
103        }
104        out.insert("description".into(), json!(description));
105        out.insert("x-nitr-checks".into(), Json::Array(list));
106        out.insert("x-nitr-enforced".into(), json!("custom"));
107    }
108    Ok(Json::Object(out))
109}
110
111/// The declarative cross-field rules: standard keywords where JSON Schema
112/// has them, extensions where it does not.
113fn cross_field(def: &SchemaDef, out: &mut Map<String, Json>) {
114    let names = |group: &Group| -> Vec<Json> { group.fields.iter().map(|f| json!(f)).collect() };
115    // "At least one of a, b" is `anyOf` over single `required`s; several
116    // groups combine under `allOf`, since `anyOf` can only appear once.
117    let any_ofs: Vec<Json> = def
118        .at_least_one
119        .iter()
120        .map(|group| {
121            json!({ "anyOf": group.fields.iter().map(|f| json!({ "required": [f] })).collect::<Vec<_>>() })
122        })
123        .collect();
124    match any_ofs.len() {
125        0 => {}
126        1 => {
127            if let Some(Json::Object(one)) = any_ofs.into_iter().next() {
128                out.extend(one);
129            }
130        }
131        _ => {
132            out.insert("allOf".into(), Json::Array(any_ofs));
133        }
134    }
135    if !def.dependent_required.is_empty() {
136        let mut map = Map::new();
137        // The group carries the trigger field itself first; the keyword
138        // lists only what it requires.
139        for (field, group) in &def.dependent_required {
140            let deps: Vec<Json> = group
141                .fields
142                .iter()
143                .filter(|f| *f != field)
144                .map(|f| json!(f))
145                .collect();
146            map.insert(field.clone(), Json::Array(deps));
147        }
148        out.insert("dependentRequired".into(), Json::Object(map));
149    }
150    for (key, groups) in [
151        ("x-nitr-mutually-exclusive", &def.mutually_exclusive),
152        ("x-nitr-equal-fields", &def.equal_fields),
153        ("x-nitr-ordered", &def.ordered),
154    ] {
155        if !groups.is_empty() {
156            out.insert(
157                key.into(),
158                Json::Array(groups.iter().map(|g| Json::Array(names(g))).collect()),
159            );
160        }
161    }
162}
163
164/// One rule as a JSON Schema.
165fn rule_schema(rule: &Rule, components: &mut Components) -> Result<Json, String> {
166    let mut out = Map::new();
167    match rule.kind {
168        Kind::String => {
169            out.insert("type".into(), json!("string"));
170        }
171        Kind::Number => {
172            out.insert("type".into(), json!("number"));
173        }
174        Kind::Integer => {
175            out.insert("type".into(), json!("integer"));
176        }
177        Kind::Boolean => {
178            out.insert("type".into(), json!("boolean"));
179        }
180        Kind::Array => {
181            out.insert("type".into(), json!("array"));
182        }
183        Kind::Table => {
184            // A nested compiled schema keeps its own title, so it may
185            // become a `$ref` of its own; a bare field table inlines.
186            if let Some(fields) = &rule.fields {
187                let nested = export(fields, components)?;
188                match nested {
189                    Json::Object(map) => out.extend(map),
190                    other => return Ok(with_common(other, rule)),
191                }
192            } else {
193                out.insert("type".into(), json!("object"));
194            }
195        }
196        Kind::Map => {
197            out.insert("type".into(), json!("object"));
198            if let Some(keys) = &rule.keys {
199                out.insert("propertyNames".into(), rule_schema(keys, components)?);
200            }
201            if let Some(values) = &rule.values {
202                out.insert(
203                    "additionalProperties".into(),
204                    rule_schema(values, components)?,
205                );
206            }
207        }
208        // `{}` accepts anything; the size bound is what the checker adds.
209        Kind::Any => {}
210        Kind::File => file_schema(rule, components, &mut out)?,
211    }
212
213    if let Some(v) = &rule.default {
214        out.insert("default".into(), literal(v, rule.kind));
215    }
216    if let Some(v) = &rule.equals {
217        out.insert("const".into(), literal(v, rule.kind));
218    }
219    if let Some(list) = &rule.one_of {
220        out.insert("enum".into(), literals(list, rule.kind));
221    }
222    if let Some(list) = &rule.not_one_of {
223        out.insert("not".into(), json!({ "enum": literals(list, rule.kind) }));
224    }
225
226    // Strings.
227    let mut transforms = Vec::new();
228    if rule.trim {
229        transforms.push(json!("trim"));
230    }
231    match rule.case {
232        Some(super::Case::Lower) => transforms.push(json!("lower")),
233        Some(super::Case::Upper) => transforms.push(json!("upper")),
234        None => {}
235    }
236    if rule.transform.is_some() {
237        transforms.push(json!("custom"));
238    }
239    if !transforms.is_empty() {
240        out.insert("x-nitr-transform".into(), Json::Array(transforms));
241    }
242    if let Some(n) = rule.len {
243        out.insert("minLength".into(), json!(n));
244        out.insert("maxLength".into(), json!(n));
245    }
246    if let Some(n) = rule.min_len {
247        out.insert("minLength".into(), json!(n));
248    }
249    if let Some(n) = rule.max_len {
250        out.insert("maxLength".into(), json!(n));
251    }
252    if let Some(format) = &rule.format {
253        format_keywords(format, &mut out);
254    }
255    patterns(rule, &mut out);
256    if let Some(bound) = &rule.after {
257        out.insert("x-nitr-after".into(), time_bound(bound));
258    }
259    if let Some(bound) = &rule.before {
260        out.insert("x-nitr-before".into(), time_bound(bound));
261    }
262
263    // Numbers.
264    for (key, value) in [
265        ("minimum", rule.min),
266        ("maximum", rule.max),
267        ("exclusiveMinimum", rule.exclusive_min),
268        ("exclusiveMaximum", rule.exclusive_max),
269        ("multipleOf", rule.multiple_of),
270    ] {
271        if let Some(n) = value {
272            out.insert(key.into(), number(n, rule.kind));
273        }
274    }
275    if let Some(n) = rule.decimals {
276        out.insert("x-nitr-decimals".into(), json!(n));
277    }
278
279    // Arrays.
280    if let Some(items) = &rule.items {
281        out.insert("items".into(), rule_schema(items, components)?);
282    }
283    if let Some(n) = rule.min_items {
284        out.insert("minItems".into(), json!(n));
285    }
286    if let Some(n) = rule.max_items {
287        out.insert("maxItems".into(), json!(n));
288    }
289    if rule.unique {
290        out.insert("uniqueItems".into(), json!(true));
291    }
292    let item_kind = rule.items.as_ref().map_or(Kind::Any, |i| i.kind);
293    let mut contains = Vec::new();
294    if let Some(v) = &rule.contains_item {
295        contains.push(json!({ "contains": { "const": literal(v, item_kind) } }));
296    }
297    if let Some(list) = &rule.contains_any {
298        contains.push(json!({ "contains": { "enum": literals(list, item_kind) } }));
299    }
300    if let Some(list) = &rule.contains_all {
301        for v in list {
302            contains.push(json!({ "contains": { "const": literal(v, item_kind) } }));
303        }
304    }
305    merge_all_of(contains, &mut out);
306    if let Some(n) = rule.max_total_bytes {
307        out.insert("x-nitr-max-total-bytes".into(), json!(n));
308    }
309
310    // Maps.
311    if let Some(n) = rule.min_keys {
312        out.insert("minProperties".into(), json!(n));
313    }
314    if let Some(n) = rule.max_keys {
315        out.insert("maxProperties".into(), json!(n));
316    }
317    if let Some(n) = rule.max_bytes
318        && rule.kind != Kind::File
319    {
320        out.insert("x-nitr-max-bytes".into(), json!(n));
321    }
322
323    Ok(with_common(Json::Object(out), rule))
324}
325
326/// `title`, `description` and the custom-check marker, added last so a
327/// nested `$ref` still carries the field's own prose.
328fn with_common(schema: Json, rule: &Rule) -> Json {
329    let Json::Object(mut out) = schema else {
330        return schema;
331    };
332    if let Some(label) = &rule.label {
333        out.insert("title".into(), json!(label));
334    }
335    if let Some(description) = &rule.description {
336        // A custom format's description was merged first; the field's own
337        // words lead.
338        let merged = match out.get("description").and_then(Json::as_str) {
339            Some(existing) if existing != description => {
340                format!("{description}\n\n{existing}")
341            }
342            _ => description.clone(),
343        };
344        out.insert("description".into(), json!(merged));
345    }
346    if rule.check.is_some() {
347        out.insert("x-nitr-enforced".into(), json!("custom"));
348    }
349    Json::Object(out)
350}
351
352/// A built-in format maps to the OpenAPI/JSON Schema format name when a
353/// standard one exists; everything else, and every custom format, is an
354/// `x-nitr-format` with the custom format's documentation beside it.
355fn format_keywords(format: &FormatRule, out: &mut Map<String, Json>) {
356    match format {
357        FormatRule::Builtin(builtin) => match standard_format(*builtin) {
358            Some(name) => {
359                out.insert("format".into(), json!(name));
360            }
361            None => {
362                out.insert("x-nitr-format".into(), json!(builtin.name()));
363            }
364        },
365        FormatRule::Custom(custom) => {
366            out.insert("x-nitr-format".into(), json!(custom.name));
367            out.insert("description".into(), json!(custom.description));
368            if let Some(pattern) = &custom.pattern {
369                out.insert("pattern".into(), json!(pattern));
370            }
371            if let Some(example) = &custom.example {
372                out.insert("example".into(), json!(example));
373            }
374            out.insert("x-nitr-enforced".into(), json!("custom"));
375        }
376    }
377}
378
379/// The formats OpenAPI 3.1 / JSON Schema name themselves.
380pub(crate) fn standard_format(format: Format) -> Option<&'static str> {
381    Some(match format {
382        Format::Email => "email",
383        Format::Uuid => "uuid",
384        Format::Url => "uri",
385        Format::Datetime => "date-time",
386        Format::Date => "date",
387        Format::Time => "time",
388        Format::Ipv4 => "ipv4",
389        Format::Ipv6 => "ipv6",
390        Format::Hostname => "hostname",
391        _ => return None,
392    })
393}
394
395/// The literal text rules as anchored, escaped patterns.
396fn patterns(rule: &Rule, out: &mut Map<String, Json>) {
397    let mut all = Vec::new();
398    if let Some(s) = &rule.starts_with {
399        all.push(format!("^{}", regex_escape(s)));
400    }
401    if let Some(s) = &rule.ends_with {
402        all.push(format!("{}$", regex_escape(s)));
403    }
404    if let Some(s) = &rule.contains {
405        all.push(regex_escape(s));
406    }
407    let not = rule
408        .does_not_contain
409        .as_ref()
410        .map(|s| json!({ "not": { "pattern": regex_escape(s) } }));
411    match (all.len(), not) {
412        (0, None) => {}
413        (1, None) => {
414            out.insert("pattern".into(), json!(all[0]));
415        }
416        (_, not) => {
417            let mut parts: Vec<Json> = all.into_iter().map(|p| json!({ "pattern": p })).collect();
418            parts.extend(not);
419            merge_all_of(parts, out);
420        }
421    }
422}
423
424/// Adds clauses to an `allOf`, creating or extending it.
425fn merge_all_of(clauses: Vec<Json>, out: &mut Map<String, Json>) {
426    if clauses.is_empty() {
427        return;
428    }
429    match out.get_mut("allOf") {
430        Some(Json::Array(existing)) => existing.extend(clauses),
431        _ => {
432            out.insert("allOf".into(), Json::Array(clauses));
433        }
434    }
435}
436
437/// Escapes every regex metacharacter so a literal stays a literal.
438pub fn regex_escape(text: &str) -> String {
439    let mut out = String::with_capacity(text.len());
440    for c in text.chars() {
441        if matches!(
442            c,
443            '\\' | '.'
444                | '+'
445                | '*'
446                | '?'
447                | '('
448                | ')'
449                | '|'
450                | '['
451                | ']'
452                | '{'
453                | '}'
454                | '^'
455                | '$'
456                | '/'
457        ) {
458            out.push('\\');
459        }
460        out.push(c);
461    }
462    out
463}
464
465fn time_bound(bound: &TimeBound) -> Json {
466    match bound {
467        TimeBound::Now => json!("now"),
468        TimeBound::Literal(s) => json!(s),
469    }
470}
471
472/// A literal rendered for the rule's kind: an integer rule's `3` is `3`,
473/// not `3.0`.
474fn literal(value: &Literal, kind: Kind) -> Json {
475    match value {
476        Literal::Str(s) => json!(s),
477        Literal::Num(n) => number(*n, kind),
478        Literal::Bool(b) => json!(b),
479    }
480}
481
482fn literals(values: &[Literal], kind: Kind) -> Json {
483    Json::Array(values.iter().map(|v| literal(v, kind)).collect())
484}
485
486fn number(n: f64, kind: Kind) -> Json {
487    if kind == Kind::Integer && n.fract() == 0.0 && n.abs() < 9.0e15 {
488        return json!(n as i64);
489    }
490    json!(n)
491}
492
493/// A `file` rule: a binary string, typed by its media types.
494fn file_schema(
495    rule: &Rule,
496    components: &mut Components,
497    out: &mut Map<String, Json>,
498) -> Result<(), String> {
499    // Invariant: a `file` rule always carries its file part (the
500    // compiler builds them together).
501    let Some(file) = &rule.file else {
502        out.insert("type".into(), json!("string"));
503        out.insert("format".into(), json!("binary"));
504        return Ok(());
505    };
506    out.insert("type".into(), json!("string"));
507    let mut names: Vec<Json> = Vec::new();
508    let mut single: Option<&str> = None;
509    for pattern in &file.types {
510        match pattern {
511            TypePattern::Any => names.push(json!("*/*")),
512            TypePattern::Family(f) => names.push(json!(format!("{f}/*"))),
513            TypePattern::Exact(name) => {
514                single = Some(name);
515                names.push(json!(name));
516            }
517        }
518    }
519    match (names.len(), single) {
520        (1, Some(exact)) => {
521            out.insert("contentMediaType".into(), json!(exact));
522        }
523        _ => {
524            out.insert("format".into(), json!("binary"));
525            if !names.is_empty() {
526                out.insert("x-nitr-types".into(), Json::Array(names));
527            }
528        }
529    }
530    if let Some(n) = rule.max_bytes {
531        out.insert("x-nitr-max-bytes".into(), json!(n));
532    }
533    if file.min_bytes > 0 {
534        out.insert("x-nitr-min-bytes".into(), json!(file.min_bytes));
535    }
536    if !file.extensions.is_empty() {
537        out.insert("x-nitr-extensions".into(), json!(file.extensions));
538    }
539    if file.match_extension {
540        out.insert("x-nitr-match-extension".into(), json!(true));
541    }
542    if file.allow_executables {
543        out.insert("x-nitr-allow-executables".into(), json!(true));
544    }
545    for (key, value) in [
546        ("x-nitr-min-width", file.min_width),
547        ("x-nitr-max-width", file.max_width),
548        ("x-nitr-min-height", file.min_height),
549        ("x-nitr-max-height", file.max_height),
550    ] {
551        if let Some(n) = value {
552            out.insert(key.into(), json!(n));
553        }
554    }
555    if let Some(n) = file.max_pixels {
556        out.insert("x-nitr-max-pixels".into(), json!(n));
557    }
558    if let Some(aspect) = &file.aspect {
559        out.insert("x-nitr-aspect".into(), json!(aspect.label));
560    }
561    if file.utf8 {
562        out.insert("x-nitr-utf8".into(), json!(true));
563    }
564    if let Some(filename) = &file.filename {
565        out.insert("x-nitr-filename".into(), rule_schema(filename, components)?);
566    }
567    Ok(())
568}
569
570#[cfg(test)]
571mod tests {
572    use super::*;
573    use crate::validate::tests::schema;
574    use mlua::Lua;
575    use serde_json::json;
576
577    fn export_of(source: &str) -> (Json, Components) {
578        let lua = Lua::new();
579        let s = schema(&lua, source);
580        let compiled = crate::validate::compile_schema(&lua, mlua::Value::UserData(s), "test")
581            .expect("compiles");
582        let mut components = Components::new();
583        let out = compiled.json_schema(&mut components).expect("exports");
584        (out, components)
585    }
586
587    #[test]
588    fn every_rule_key_has_its_keyword_or_extension() {
589        let (out, _) = export_of(
590            r#"{
591                name = { type = "string", required = true, trim = true, case = "lower",
592                         min_len = 1, max_len = 20, format = "email", label = "Name",
593                         description = "who" },
594                nick = { type = "string", default = "x" },
595                code = { type = "string", starts_with = "N-", ends_with = "x", contains = ".",
596                         does_not_contain = " " },
597                n = { type = "integer", min = 1, max = 5, multiple_of = 1, default = 3, one_of = { 1, 2, 3 } },
598                f = { type = "number", exclusive_min = 0, exclusive_max = 1, decimals = 2 },
599                on = { type = "boolean", equals = true },
600                tags = { type = "array", items = { type = "string", format = "slug" }, min_items = 1,
601                         max_items = 5, unique = true, contains = "a", contains_any = { "b", "c" },
602                         contains_all = { "d" } },
603                meta = { type = "map", keys = { type = "string", max_len = 8 }, values = { type = "integer" },
604                         min_keys = 0, max_keys = 10 },
605                blob = { type = "any", max_bytes = 100 },
606                role = { type = "string", not_one_of = { "root" } },
607                due = { type = "string", format = "date", after = "now", before = "2030-01-01" },
608                len = { type = "string", len = 4 },
609            }"#,
610        );
611        let p = &out["properties"];
612        assert_eq!(out["type"], "object");
613        assert_eq!(out["required"], json!(["name"]));
614        assert_eq!(out["additionalProperties"], false);
615        assert_eq!(p["name"]["format"], "email");
616        assert_eq!(p["name"]["x-nitr-transform"], json!(["trim", "lower"]));
617        assert_eq!(p["name"]["minLength"], 1);
618        assert_eq!(p["name"]["maxLength"], 20);
619        assert_eq!(p["name"]["title"], "Name");
620        assert_eq!(p["name"]["description"], "who");
621        assert_eq!(p["nick"]["default"], "x");
622        assert_eq!(
623            p["code"]["allOf"],
624            json!([
625                { "pattern": "^N-" },
626                { "pattern": "x$" },
627                { "pattern": "\\." },
628                { "not": { "pattern": " " } }
629            ])
630        );
631        assert_eq!(p["n"]["minimum"], 1);
632        assert_eq!(p["n"]["maximum"], 5);
633        assert_eq!(p["n"]["multipleOf"], 1);
634        assert_eq!(p["n"]["default"], 3);
635        assert_eq!(p["n"]["enum"], json!([1, 2, 3]));
636        assert_eq!(p["f"]["exclusiveMinimum"], 0.0);
637        assert_eq!(p["f"]["exclusiveMaximum"], 1.0);
638        assert_eq!(p["f"]["x-nitr-decimals"], 2);
639        assert_eq!(p["on"]["const"], true);
640        assert_eq!(p["tags"]["items"]["x-nitr-format"], "slug");
641        assert_eq!(p["tags"]["minItems"], 1);
642        assert_eq!(p["tags"]["maxItems"], 5);
643        assert_eq!(p["tags"]["uniqueItems"], true);
644        assert_eq!(
645            p["tags"]["allOf"],
646            json!([
647                { "contains": { "const": "a" } },
648                { "contains": { "enum": ["b", "c"] } },
649                { "contains": { "const": "d" } }
650            ])
651        );
652        assert_eq!(p["meta"]["propertyNames"]["maxLength"], 8);
653        assert_eq!(p["meta"]["additionalProperties"]["type"], "integer");
654        assert_eq!(p["meta"]["minProperties"], 0);
655        assert_eq!(p["meta"]["maxProperties"], 10);
656        assert_eq!(p["blob"], json!({ "x-nitr-max-bytes": 100 }));
657        assert_eq!(p["role"]["not"], json!({ "enum": ["root"] }));
658        assert_eq!(p["due"]["format"], "date");
659        assert_eq!(p["due"]["x-nitr-after"], "now");
660        assert_eq!(p["due"]["x-nitr-before"], "2030-01-01");
661        assert_eq!(p["len"]["minLength"], 4);
662        assert_eq!(p["len"]["maxLength"], 4);
663    }
664
665    #[test]
666    fn every_builtin_format_is_named_once() {
667        for (name, format) in crate::validate::format::FORMATS {
668            let (out, _) = export_of(&format!(
669                r#"{{ v = {{ type = "string", format = "{name}" }} }}"#
670            ));
671            let v = &out["properties"]["v"];
672            match standard_format(*format) {
673                Some(std) => {
674                    assert_eq!(v["format"], std, "{name}");
675                    assert!(v.get("x-nitr-format").is_none(), "{name}");
676                }
677                None => {
678                    assert_eq!(v["x-nitr-format"], *name, "{name}");
679                    assert!(v.get("format").is_none(), "{name}");
680                }
681            }
682        }
683    }
684
685    #[test]
686    fn metacharacters_in_literals_are_escaped() {
687        let (out, _) = export_of(
688            r#"{ a = { type = "string", starts_with = "(", ends_with = "$", contains = ".*+?[]{}|^/\\" } }"#,
689        );
690        assert_eq!(
691            out["properties"]["a"]["allOf"],
692            json!([
693                { "pattern": "^\\(" },
694                { "pattern": "\\$$" },
695                { "pattern": "\\.\\*\\+\\?\\[\\]\\{\\}\\|\\^\\/\\\\" }
696            ])
697        );
698    }
699
700    #[test]
701    fn titled_schemas_become_components_and_nest_by_reference() {
702        let lua = Lua::new();
703        let inner = schema(&lua, r#"{ id = { type = "integer", required = true } }"#);
704        lua.globals().set("Inner", inner).unwrap();
705        let s = lua
706            .load(
707                r#"nitr.validate.schema({
708                    item = { type = "table", fields = Inner, required = true },
709                    items = { type = "array", items = { type = "table", fields = Inner } },
710                }, { title = "Outer" })"#,
711            )
712            .eval::<mlua::AnyUserData>()
713            .expect("outer");
714        let compiled =
715            crate::validate::compile_schema(&lua, mlua::Value::UserData(s), "test").unwrap();
716        let mut components = Components::new();
717        let out = compiled.json_schema(&mut components).unwrap();
718        assert_eq!(out, json!({ "$ref": "#/components/schemas/Outer" }));
719        let outer = &components["Outer"];
720        assert_eq!(outer["title"], "Outer");
721        // Untitled inner schemas inline.
722        assert_eq!(outer["properties"]["item"]["type"], "object");
723        assert_eq!(
724            outer["properties"]["items"]["items"]["properties"]["id"]["type"],
725            "integer"
726        );
727        assert_eq!(components.len(), 1);
728    }
729
730    #[test]
731    fn a_title_shared_by_two_schemas_gets_a_suffix() {
732        let lua = Lua::new();
733        let a = schema(&lua, r#"{ a = { type = "string" } }"#);
734        lua.globals().set("A", a).unwrap();
735        let s = lua
736            .load(r#"nitr.validate.schema({ b = { type = "string" } }, { title = "Dup" })"#)
737            .eval::<mlua::AnyUserData>()
738            .unwrap();
739        let t = lua
740            .load(r#"nitr.validate.schema({ c = { type = "string" } }, { title = "Dup" })"#)
741            .eval::<mlua::AnyUserData>()
742            .unwrap();
743        let mut components = Components::new();
744        let mut refs = Vec::new();
745        for ud in [s, t] {
746            let compiled =
747                crate::validate::compile_schema(&lua, mlua::Value::UserData(ud), "test").unwrap();
748            refs.push(compiled.json_schema(&mut components).unwrap());
749        }
750        assert_eq!(refs[0], json!({ "$ref": "#/components/schemas/Dup" }));
751        assert_eq!(refs[1], json!({ "$ref": "#/components/schemas/Dup_2" }));
752        assert_eq!(components["Dup"]["properties"]["b"]["type"], "string");
753        assert_eq!(components["Dup_2"]["properties"]["c"]["type"], "string");
754        assert_eq!(components["Dup_2"]["title"], "Dup_2");
755        // The same schema again reuses its component.
756        let again = crate::validate::compile_schema(
757            &lua,
758            lua.load(r#"nitr.validate.schema({ b = { type = "string" } }, { title = "Dup" })"#)
759                .eval::<mlua::Value>()
760                .unwrap(),
761            "test",
762        )
763        .unwrap();
764        assert_eq!(
765            again.json_schema(&mut components).unwrap(),
766            json!({ "$ref": "#/components/schemas/Dup" })
767        );
768        assert_eq!(components.len(), 2);
769    }
770
771    #[test]
772    fn custom_checks_and_formats_are_marked_and_described() {
773        let lua = Lua::new();
774        crate::validate::tests::validate(&lua);
775        lua.load(
776            r#"nitr.validate.format("note_ref", {
777                description = "A note reference", pattern = "^N-[0-9]+$", example = "N-1",
778                check = function(s) return s:match("^N%-%d+$") ~= nil end,
779            })"#,
780        )
781        .exec()
782        .unwrap();
783        let s = lua
784            .load(
785                r#"nitr.validate.schema({
786                    r = { type = "string", format = "note_ref", description = "which note" },
787                    pw = { type = "string", description = "not common", check = function(s) return true end },
788                    t = { type = "string", transform = function(s) return s end },
789                    a = { type = "string" }, b = { type = "string" }, c = { type = "string" },
790                    lo = { type = "integer" }, hi = { type = "integer" },
791                }, {
792                    at_least_one = { { "a", "b" } },
793                    mutually_exclusive = { { "a", "c" } },
794                    dependent_required = { a = { "b" } },
795                    equal_fields = { { "b", "c" } },
796                    ordered = { { "lo", "hi" } },
797                    checks = { { description = "the pair is unique", check = function() return true end } },
798                })"#,
799            )
800            .eval::<mlua::AnyUserData>()
801            .unwrap();
802        let compiled =
803            crate::validate::compile_schema(&lua, mlua::Value::UserData(s), "test").unwrap();
804        let out = compiled.json_schema(&mut Components::new()).unwrap();
805        let p = &out["properties"];
806        assert_eq!(p["r"]["x-nitr-format"], "note_ref");
807        assert_eq!(p["r"]["pattern"], "^N-[0-9]+$");
808        assert_eq!(p["r"]["example"], "N-1");
809        assert_eq!(p["r"]["x-nitr-enforced"], "custom");
810        assert_eq!(p["r"]["description"], "which note\n\nA note reference");
811        assert_eq!(p["pw"]["x-nitr-enforced"], "custom");
812        assert_eq!(p["pw"]["description"], "not common");
813        assert_eq!(p["t"]["x-nitr-transform"], json!(["custom"]));
814        assert_eq!(
815            out["anyOf"],
816            json!([{ "required": ["a"] }, { "required": ["b"] }])
817        );
818        assert_eq!(out["x-nitr-mutually-exclusive"], json!([["a", "c"]]));
819        assert_eq!(out["dependentRequired"], json!({ "a": ["b"] }));
820        assert_eq!(out["x-nitr-equal-fields"], json!([["b", "c"]]));
821        assert_eq!(out["x-nitr-ordered"], json!([["lo", "hi"]]));
822        assert_eq!(out["x-nitr-checks"], json!(["the pair is unique"]));
823        assert_eq!(out["description"], "Constraints:\n- the pair is unique");
824        assert_eq!(out["x-nitr-enforced"], "custom");
825    }
826
827    #[test]
828    fn file_rules_render_as_binary_strings_with_their_bounds() {
829        let lua = Lua::new();
830        crate::validate::tests::validate(&lua);
831        let s = lua
832            .load(
833                r#"nitr.validate.schema({
834                    one = { type = "file", types = { "image/png" }, max_bytes = 1024, min_bytes = 1,
835                            extensions = { "png" }, max_width = 100, max_pixels = 1000, aspect = "1:1" },
836                    many = { type = "file", types = { "image/*", "application/pdf" }, max_bytes = 2048,
837                             allow_executables = true, utf8 = true, filename = { type = "string", max_len = 20 } },
838                    any = { type = "file", types = { "*/*" }, max_bytes = 10 },
839                })"#,
840            )
841            .eval::<mlua::AnyUserData>()
842            .unwrap();
843        let compiled =
844            crate::validate::compile_schema(&lua, mlua::Value::UserData(s), "test").unwrap();
845        let out = compiled.json_schema(&mut Components::new()).unwrap();
846        let p = &out["properties"];
847        assert_eq!(p["one"]["type"], "string");
848        assert_eq!(p["one"]["contentMediaType"], "image/png");
849        assert!(p["one"].get("format").is_none());
850        assert_eq!(p["one"]["x-nitr-max-bytes"], 1024);
851        assert_eq!(p["one"]["x-nitr-min-bytes"], 1);
852        assert_eq!(p["one"]["x-nitr-extensions"], json!(["png"]));
853        assert_eq!(p["one"]["x-nitr-max-width"], 100);
854        assert_eq!(p["one"]["x-nitr-max-pixels"], 1000);
855        assert_eq!(p["one"]["x-nitr-aspect"], "1:1");
856        assert_eq!(p["many"]["format"], "binary");
857        assert_eq!(
858            p["many"]["x-nitr-types"],
859            json!(["image/*", "application/pdf"])
860        );
861        assert_eq!(p["many"]["x-nitr-allow-executables"], true);
862        assert_eq!(p["many"]["x-nitr-utf8"], true);
863        assert_eq!(p["many"]["x-nitr-filename"]["maxLength"], 20);
864        assert_eq!(p["any"]["x-nitr-types"], json!(["*/*"]));
865    }
866
867    #[test]
868    fn export_is_deterministic_across_states() {
869        let source = r#"{
870            z = { type = "string" }, a = { type = "integer", one_of = { 3, 1, 2 } },
871            m = { type = "map", keys = { type = "string" }, values = { type = "string" }, max_keys = 2 },
872        }"#;
873        let first = serde_json::to_string(&export_of(source).0).unwrap();
874        for _ in 0..3 {
875            assert_eq!(serde_json::to_string(&export_of(source).0).unwrap(), first);
876        }
877        assert!(first.find("\"a\"").unwrap() < first.find("\"z\"").unwrap());
878    }
879}