Skip to main content

zenkey_model/
schema.rs

1//! Schema artifacts and type resolution (r3 §3.9, r3.3 D5–D7).
2//!
3//! - **Protobuf:** every listed `.proto` file is compiled on its own with
4//!   `protox` into a `FileDescriptorSet` that includes its imports, without
5//!   source info. That set is the file's artifact. A message type resolves
6//!   to the listed file that defines it. The well-known types
7//!   (`google.protobuf.*`) are always available; one that no listed file
8//!   defines is compiled on demand and becomes an artifact of its own.
9//! - **JSON Schema:** every listed file is one artifact, hashed over its
10//!   JCS form. `json:<Name>` names a `$defs` entry that is unique across
11//!   the listed files; `json:<stem>#<Name>` names one in the file whose stem
12//!   is `<stem>`. A cross-file `$ref` may point only at listed files, and
13//!   in a bundle it resolves by the file stem of its path, so stems are
14//!   unique per contract, and so are ids: two listed files with one JCS
15//!   form would be one artifact under one name (spec §9.4, 0.6).
16//! - **Packed** (core §7.6, §9.4, 0.75): every listed file is one
17//!   artifact, read and hashed as a JSON Schema file is. `packed:<Name>`
18//!   names a `types` entry unique across the listed packed files, and
19//!   `packed:<stem>#<Name>` one in the file of that stem. Its declarations
20//!   are linted by [`crate::packed`] (E038 to E045).
21//! - **Raw:** a media type (`image/jpeg`) or family (`video/*`), with no
22//!   artifact.
23//!
24//! An artifact's id is `sha256:<hex>` of its bytes (protobuf) or of its JCS
25//! form (JSON Schema). A type's identity is (kind, name, artifact id).
26
27use std::collections::BTreeMap;
28use std::fmt::Write as _;
29use std::path::{Component, Path, PathBuf};
30
31use base64::Engine as _;
32use prost_reflect::DescriptorPool;
33use serde_json::Value;
34use sha2::{Digest, Sha256};
35
36use crate::authoring::{RawType, SchemasSection, TypeRef};
37use crate::diag::{Diagnostic, Report};
38
39/// A schema artifact's kind, by MCAP's spellings.
40#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
41pub enum SchemaKind {
42    Protobuf,
43    JsonSchema,
44    /// A packed file (core §7.6): strict JSON, carried as
45    /// [`ArtifactData::Json`].
46    Packed,
47}
48
49impl SchemaKind {
50    #[must_use]
51    pub fn as_str(self) -> &'static str {
52        match self {
53            Self::Protobuf => "protobuf",
54            Self::JsonSchema => "jsonschema",
55            Self::Packed => "packed",
56        }
57    }
58}
59
60/// One schema artifact, as a bundle carries it.
61#[derive(Debug, Clone, PartialEq)]
62pub struct Artifact {
63    pub kind: SchemaKind,
64    /// The protobuf file name (include-relative, as imports spell it) or
65    /// the JSON Schema file stem.
66    pub name: String,
67    pub data: ArtifactData,
68}
69
70#[derive(Debug, Clone, PartialEq)]
71pub enum ArtifactData {
72    /// An encoded `FileDescriptorSet`.
73    Protobuf(Vec<u8>),
74    /// A JSON Schema document, or a packed one.
75    Json(Value),
76}
77
78impl Artifact {
79    /// `sha256:<hex>` over the artifact's bytes, or its JCS form.
80    #[must_use]
81    pub fn id(&self) -> String {
82        match &self.data {
83            ArtifactData::Protobuf(b) => sha256_id(b),
84            ArtifactData::Json(v) => sha256_id(&jcs(v)),
85        }
86    }
87
88    /// The `data` member of the artifact's bundle entry: base64 of a
89    /// descriptor set, or the JSON Schema document itself.
90    #[must_use]
91    pub fn data_value(&self) -> Value {
92        match &self.data {
93            ArtifactData::Protobuf(b) => {
94                Value::String(base64::engine::general_purpose::STANDARD.encode(b))
95            }
96            ArtifactData::Json(v) => v.clone(),
97        }
98    }
99}
100
101/// A resolved type identity.
102#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
103pub enum TypeId {
104    Protobuf {
105        name: String,
106        schema: String,
107    },
108    JsonSchema {
109        name: String,
110        schema: String,
111    },
112    /// A packed type (core §7.6): a `types` entry of a packed artifact.
113    Packed {
114        name: String,
115        schema: String,
116    },
117    Raw {
118        media_type: String,
119        media_param: Option<String>,
120    },
121}
122
123impl TypeId {
124    #[must_use]
125    pub fn kind_str(&self) -> &'static str {
126        match self {
127            Self::Protobuf { .. } => "protobuf",
128            Self::JsonSchema { .. } => "jsonschema",
129            Self::Packed { .. } => "packed",
130            Self::Raw { .. } => "raw",
131        }
132    }
133    #[must_use]
134    pub fn is_json(&self) -> bool {
135        matches!(self, Self::JsonSchema { .. })
136    }
137    #[must_use]
138    pub fn is_packed(&self) -> bool {
139        matches!(self, Self::Packed { .. })
140    }
141}
142
143struct ProtoFile {
144    /// The include-relative name (`nav/v2/nav.proto`).
145    name: String,
146    pool: DescriptorPool,
147    artifact: String,
148}
149
150struct JsonFile {
151    stem: String,
152    doc: Value,
153    artifact: String,
154}
155
156struct PackedFile {
157    stem: String,
158    doc: crate::packed::PackedDoc,
159    artifact: String,
160}
161
162/// The compiled schemas of one contract.
163pub struct SchemaSet {
164    artifacts: BTreeMap<String, Artifact>,
165    proto: Vec<ProtoFile>,
166    json: Vec<JsonFile>,
167    packed: Vec<PackedFile>,
168    /// Set when a listed file failed to load, so unresolved references of
169    /// that kind are not reported twice.
170    proto_failed: bool,
171    json_failed: bool,
172    packed_failed: bool,
173}
174
175/// The well-known types, by the file that defines them.
176const WELL_KNOWN: &[(&str, &[&str])] = &[
177    ("google/protobuf/any.proto", &["Any"]),
178    ("google/protobuf/duration.proto", &["Duration"]),
179    ("google/protobuf/empty.proto", &["Empty"]),
180    ("google/protobuf/field_mask.proto", &["FieldMask"]),
181    (
182        "google/protobuf/struct.proto",
183        &["Struct", "Value", "ListValue"],
184    ),
185    ("google/protobuf/timestamp.proto", &["Timestamp"]),
186    (
187        "google/protobuf/wrappers.proto",
188        &[
189            "DoubleValue",
190            "FloatValue",
191            "Int64Value",
192            "UInt64Value",
193            "Int32Value",
194            "UInt32Value",
195            "BoolValue",
196            "StringValue",
197            "BytesValue",
198        ],
199    ),
200];
201
202impl SchemaSet {
203    /// Loads and compiles every listed schema file, relative to `dir`.
204    pub fn load(dir: &Path, sec: &SchemasSection, report: &mut Report) -> Self {
205        let mut set = Self {
206            artifacts: BTreeMap::new(),
207            proto: Vec::new(),
208            json: Vec::new(),
209            packed: Vec::new(),
210            proto_failed: false,
211            json_failed: false,
212            packed_failed: false,
213        };
214        set.load_proto(dir, sec, report);
215        set.load_json(dir, sec, report);
216        set.load_packed(dir, sec, report);
217        set
218    }
219
220    /// Packed files (core §7.6, §9.4): read as JSON Schema files are, then
221    /// linted by [`crate::packed::PackedDoc::read`]. A stem is unique among
222    /// the packed files, and an id among the JSON Schema and packed files,
223    /// both E024.
224    fn load_packed(&mut self, dir: &Path, sec: &SchemasSection, report: &mut Report) {
225        for f in &sec.packed {
226            let at = format!("schemas.packed {f:?}");
227            let doc = match std::fs::read_to_string(dir.join(f)) {
228                Ok(text) => match crate::strict::parse_json(&text) {
229                    Ok(v) => v,
230                    Err(e) => {
231                        report.push(Diagnostic::error(
232                            "E029",
233                            at,
234                            format!("is not valid JSON: {e}"),
235                        ));
236                        self.packed_failed = true;
237                        continue;
238                    }
239                },
240                Err(e) => {
241                    report.push(Diagnostic::error(
242                        "E029",
243                        at,
244                        format!("cannot be read: {e}"),
245                    ));
246                    self.packed_failed = true;
247                    continue;
248                }
249            };
250            if let Some(n) = unsafe_integer(&doc) {
251                report.push(Diagnostic::error(
252                    "E028",
253                    at.clone(),
254                    format!("{n} is outside ±(2^53−1), so the artifact has no portable id"),
255                ));
256            }
257            let stem = file_stem(f);
258            if self.packed.iter().any(|p| p.stem == stem) {
259                report.push(Diagnostic::error(
260                    "E024",
261                    at,
262                    format!(
263                        "a second listed packed file has the stem {stem:?}; stems are unique per contract"
264                    ),
265                ));
266                continue;
267            }
268            let art = Artifact {
269                kind: SchemaKind::Packed,
270                name: stem.clone(),
271                data: ArtifactData::Json(doc.clone()),
272            };
273            let id = art.id();
274            let taken = self
275                .json
276                .iter()
277                .map(|j| (&j.artifact, &j.stem))
278                .chain(self.packed.iter().map(|p| (&p.artifact, &p.stem)))
279                .find(|(a, _)| **a == id);
280            if let Some((_, first)) = taken {
281                report.push(Diagnostic::error(
282                    "E024",
283                    at,
284                    format!("the same document as {first:?} (one id); list it once"),
285                ));
286                continue;
287            }
288            let read = crate::packed::PackedDoc::read(&doc);
289            for x in &read.findings {
290                let place = if x.at.is_empty() {
291                    at.clone()
292                } else {
293                    format!("{at} {}", x.at)
294                };
295                report.push(Diagnostic::error(x.code, place, x.message.clone()));
296            }
297            self.artifacts.insert(id.clone(), art);
298            self.packed.push(PackedFile {
299                stem,
300                doc: read,
301                artifact: id,
302            });
303        }
304    }
305
306    /// The layout of a packed type this set resolved, when its declaration
307    /// has no finding.
308    #[must_use]
309    pub fn packed_layout(&self, t: &TypeId) -> Option<&crate::packed::Layout> {
310        let TypeId::Packed { name, schema } = t else {
311            return None;
312        };
313        self.packed
314            .iter()
315            .find(|p| &p.artifact == schema)?
316            .doc
317            .types
318            .get(name)?
319            .as_ref()
320    }
321
322    fn load_proto(&mut self, dir: &Path, sec: &SchemasSection, report: &mut Report) {
323        if sec.protobuf.is_empty() {
324            return;
325        }
326        let includes: Vec<PathBuf> = match &sec.proto_include {
327            Some(v) => v.iter().map(|p| dir.join(p)).collect(),
328            None if dir.join("proto").is_dir() => vec![dir.join("proto")],
329            None => vec![dir.to_path_buf()],
330        };
331        for f in &sec.protobuf {
332            let at = format!("schemas.protobuf {f:?}");
333            let compiled = protox::Compiler::new(&includes).and_then(|mut c| {
334                c.include_imports(true).include_source_info(false);
335                c.open_file(dir.join(f))?;
336                Ok(c)
337            });
338            let c = match compiled {
339                Ok(c) => c,
340                Err(e) => {
341                    report.push(Diagnostic::error(
342                        "E029",
343                        at,
344                        format!("does not compile: {e}"),
345                    ));
346                    self.proto_failed = true;
347                    continue;
348                }
349            };
350            let Some(name) = c
351                .files()
352                .find(|m| !m.is_import())
353                .map(|m| m.name().to_owned())
354            else {
355                report.push(Diagnostic::error("E029", at, "compiled to no file"));
356                self.proto_failed = true;
357                continue;
358            };
359            let art = Artifact {
360                kind: SchemaKind::Protobuf,
361                name: name.clone(),
362                data: ArtifactData::Protobuf(c.encode_file_descriptor_set()),
363            };
364            let id = art.id();
365            self.artifacts.insert(id.clone(), art);
366            self.proto.push(ProtoFile {
367                name,
368                pool: c.descriptor_pool(),
369                artifact: id,
370            });
371        }
372    }
373
374    fn load_json(&mut self, dir: &Path, sec: &SchemasSection, report: &mut Report) {
375        let mut paths = Vec::new();
376        for f in &sec.jsonschema {
377            let at = format!("schemas.jsonschema {f:?}");
378            let path = dir.join(f);
379            let doc = match std::fs::read_to_string(&path) {
380                Ok(text) => match crate::strict::parse_json(&text) {
381                    Ok(v) => v,
382                    Err(e) => {
383                        report.push(Diagnostic::error(
384                            "E029",
385                            at,
386                            format!("is not valid JSON: {e}"),
387                        ));
388                        self.json_failed = true;
389                        continue;
390                    }
391                },
392                Err(e) => {
393                    report.push(Diagnostic::error(
394                        "E029",
395                        at,
396                        format!("cannot be read: {e}"),
397                    ));
398                    self.json_failed = true;
399                    continue;
400                }
401            };
402            if let Some(n) = unsafe_integer(&doc) {
403                report.push(Diagnostic::error(
404                    "E028",
405                    at.clone(),
406                    format!("{n} is outside ±(2^53−1), so the artifact has no portable id"),
407                ));
408            }
409            let mut refused = std::collections::BTreeSet::new();
410            refused_keywords(&doc, &mut refused);
411            for k in refused {
412                report.push(Diagnostic::error(
413                    "E037",
414                    at.clone(),
415                    format!("keyword {k:?} is outside the zk2 JSON Schema subset"),
416                ));
417            }
418            let stem = file_stem(f);
419            if self.json.iter().any(|j| j.stem == stem) {
420                report.push(Diagnostic::error(
421                    "E024",
422                    at,
423                    format!(
424                        "a second listed file has the stem {stem:?}; stems are unique per contract"
425                    ),
426                ));
427                continue;
428            }
429            let art = Artifact {
430                kind: SchemaKind::JsonSchema,
431                name: stem.clone(),
432                data: ArtifactData::Json(doc.clone()),
433            };
434            let id = art.id();
435            // One id, one name (spec §9.4, 0.6): a later file with an earlier
436            // one's JCS bytes would share its id, and the canonical form
437            // could list it under one name only, so a bundle `$ref` naming
438            // the other stem would resolve to nothing.
439            if let Some(first) = self.json.iter().find(|j| j.artifact == id) {
440                report.push(Diagnostic::error(
441                    "E024",
442                    at,
443                    format!(
444                        "the same document as {:?} (one id); list it once",
445                        first.stem
446                    ),
447                ));
448                continue;
449            }
450            self.artifacts.insert(id.clone(), art);
451            self.json.push(JsonFile {
452                stem,
453                doc,
454                artifact: id,
455            });
456            paths.push((f.clone(), normalize(&path)));
457        }
458        // Cross-file `$ref`s: listed files only, existing definitions only.
459        for (i, (f, path)) in paths.iter().enumerate() {
460            let mut refs = Vec::new();
461            collect_refs(&self.json[i].doc, &mut refs);
462            for r in refs {
463                let at = format!("schemas.jsonschema {f:?}");
464                let (file_part, pointer) = r.split_once('#').unwrap_or((r.as_str(), ""));
465                let target = if file_part.is_empty() {
466                    Some(i)
467                } else if file_part.contains(':') {
468                    None
469                } else {
470                    let p = normalize(&path.parent().unwrap_or(Path::new("")).join(file_part));
471                    paths.iter().position(|(_, q)| *q == p)
472                };
473                let Some(t) = target else {
474                    report.push(Diagnostic::error(
475                        "E032",
476                        at,
477                        format!("$ref {r:?} points outside the listed files"),
478                    ));
479                    continue;
480                };
481                if !pointer.is_empty() && self.json[t].doc.pointer(pointer).is_none() {
482                    report.push(Diagnostic::error(
483                        "E032",
484                        at,
485                        format!("$ref {r:?} points at a missing definition"),
486                    ));
487                }
488            }
489        }
490    }
491
492    /// Resolves a type reference, reporting E023/E024 at `at`.
493    pub fn resolve(&mut self, r: &TypeRef, at: &str, report: &mut Report) -> Option<TypeId> {
494        match r {
495            TypeRef::Raw(raw) => resolve_raw(raw, at, report),
496            TypeRef::Named(s) => {
497                if let Some(rest) = s.strip_prefix("json:") {
498                    self.resolve_json(s, rest, at, report)
499                } else if let Some(rest) = s.strip_prefix("packed:") {
500                    self.resolve_packed(s, rest, at, report)
501                } else {
502                    self.resolve_proto(s, at, report)
503                }
504            }
505        }
506    }
507
508    fn resolve_json(
509        &self,
510        full: &str,
511        rest: &str,
512        at: &str,
513        report: &mut Report,
514    ) -> Option<TypeId> {
515        let (stem, name) = match rest.split_once('#') {
516            Some((stem, name)) => (Some(stem), name),
517            None => (None, rest),
518        };
519        let has = |j: &JsonFile| j.doc.get("$defs").and_then(|d| d.get(name)).is_some();
520        let found: Vec<&JsonFile> = self
521            .json
522            .iter()
523            .filter(|j| stem.is_none_or(|s| j.stem == s) && has(j))
524            .collect();
525        match found.as_slice() {
526            [j] => Some(TypeId::JsonSchema {
527                name: name.to_owned(),
528                schema: j.artifact.clone(),
529            }),
530            [] => {
531                if !self.json_failed {
532                    report.push(Diagnostic::error(
533                        "E023",
534                        at,
535                        format!("{full:?}: no listed JSON Schema file defines $defs/{name}"),
536                    ));
537                }
538                None
539            }
540            many => {
541                let stems: Vec<&str> = many.iter().map(|j| j.stem.as_str()).collect();
542                report.push(Diagnostic::error(
543                    "E024",
544                    at,
545                    format!("{full:?} is defined in {stems:?}; qualify it as json:<stem>#{name}"),
546                ));
547                None
548            }
549        }
550    }
551
552    fn resolve_packed(
553        &self,
554        full: &str,
555        rest: &str,
556        at: &str,
557        report: &mut Report,
558    ) -> Option<TypeId> {
559        let (stem, name) = match rest.split_once('#') {
560            Some((stem, name)) => (Some(stem), name),
561            None => (None, rest),
562        };
563        let found: Vec<&PackedFile> = self
564            .packed
565            .iter()
566            .filter(|p| stem.is_none_or(|s| p.stem == s) && p.doc.types.contains_key(name))
567            .collect();
568        match found.as_slice() {
569            [p] => Some(TypeId::Packed {
570                name: name.to_owned(),
571                schema: p.artifact.clone(),
572            }),
573            [] => {
574                if !self.packed_failed {
575                    report.push(Diagnostic::error(
576                        "E023",
577                        at,
578                        format!("{full:?}: no listed packed file defines types/{name}"),
579                    ));
580                }
581                None
582            }
583            many => {
584                let stems: Vec<&str> = many.iter().map(|p| p.stem.as_str()).collect();
585                report.push(Diagnostic::error(
586                    "E024",
587                    at,
588                    format!("{full:?} is defined in {stems:?}; qualify it as packed:<stem>#{name}"),
589                ));
590                None
591            }
592        }
593    }
594
595    fn resolve_proto(&mut self, name: &str, at: &str, report: &mut Report) -> Option<TypeId> {
596        let found: Vec<&ProtoFile> = self
597            .proto
598            .iter()
599            .filter(|p| {
600                p.pool
601                    .get_message_by_name(name)
602                    .is_some_and(|m| m.parent_file().name() == p.name)
603            })
604            .collect();
605        match found.as_slice() {
606            [p] => {
607                return Some(TypeId::Protobuf {
608                    name: name.to_owned(),
609                    schema: p.artifact.clone(),
610                });
611            }
612            [] => {}
613            _ => {
614                report.push(Diagnostic::error(
615                    "E023",
616                    at,
617                    format!("{name:?} is defined by more than one listed .proto file"),
618                ));
619                return None;
620            }
621        }
622        if let Some(short) = name.strip_prefix("google.protobuf.")
623            && let Some((file, _)) = WELL_KNOWN.iter().find(|(_, ms)| ms.contains(&short))
624        {
625            return self.well_known(file, name);
626        }
627        if !self.proto_failed {
628            let hint = if self
629                .proto
630                .iter()
631                .any(|p| p.pool.get_message_by_name(name).is_some())
632            {
633                " (it is defined by an imported file: list that file)"
634            } else {
635                ""
636            };
637            report.push(Diagnostic::error(
638                "E023",
639                at,
640                format!("{name:?}: no listed .proto file defines this message{hint}"),
641            ));
642        }
643        None
644    }
645
646    fn well_known(&mut self, file: &str, name: &str) -> Option<TypeId> {
647        if let Some(p) = self.proto.iter().find(|p| p.name == file) {
648            return Some(TypeId::Protobuf {
649                name: name.to_owned(),
650                schema: p.artifact.clone(),
651            });
652        }
653        let mut c = protox::Compiler::new::<_, &Path>([]).ok()?;
654        c.include_imports(true).include_source_info(false);
655        c.open_file(file).ok()?;
656        let art = Artifact {
657            kind: SchemaKind::Protobuf,
658            name: file.to_owned(),
659            data: ArtifactData::Protobuf(c.encode_file_descriptor_set()),
660        };
661        let id = art.id();
662        self.artifacts.insert(id.clone(), art);
663        self.proto.push(ProtoFile {
664            name: file.to_owned(),
665            pool: c.descriptor_pool(),
666            artifact: id.clone(),
667        });
668        Some(TypeId::Protobuf {
669            name: name.to_owned(),
670            schema: id,
671        })
672    }
673
674    /// The top-level field names of a message or object type, for the D21
675    /// lint. `None` for raw types, or when the shape is not plain.
676    #[must_use]
677    pub fn field_names(&self, t: &TypeId) -> Option<Vec<String>> {
678        match t {
679            TypeId::Protobuf { name, schema } => {
680                let p = self.proto.iter().find(|p| &p.artifact == schema)?;
681                let m = p.pool.get_message_by_name(name)?;
682                Some(m.fields().map(|f| f.name().to_owned()).collect())
683            }
684            TypeId::JsonSchema { name, schema } => {
685                let j = self.json.iter().find(|j| &j.artifact == schema)?;
686                let props = j
687                    .doc
688                    .get("$defs")?
689                    .get(name)?
690                    .get("properties")?
691                    .as_object()?;
692                Some(props.keys().cloned().collect())
693            }
694            TypeId::Packed { .. } | TypeId::Raw { .. } => None,
695        }
696    }
697
698    /// Every artifact, by id.
699    #[must_use]
700    pub fn artifacts(&self) -> &BTreeMap<String, Artifact> {
701        &self.artifacts
702    }
703}
704
705fn resolve_raw(raw: &RawType, at: &str, report: &mut Report) -> Option<TypeId> {
706    if !is_media_type(&raw.raw) {
707        report.push(Diagnostic::error(
708            "E023",
709            at,
710            format!(
711                "{:?} is not a lowercase media type <type>/<subtype> or family <type>/*",
712                raw.raw
713            ),
714        ));
715        return None;
716    }
717    Some(TypeId::Raw {
718        media_type: raw.raw.clone(),
719        media_param: raw.media_param.clone(),
720    })
721}
722
723fn is_media_type(s: &str) -> bool {
724    let tok = |t: &str| {
725        let mut cs = t.chars();
726        cs.next()
727            .is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
728            && cs.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || "!#$&-^_.+".contains(c))
729    };
730    match s.split_once('/') {
731        Some((t, sub)) => tok(t) && (sub == "*" || tok(sub)),
732        None => false,
733    }
734}
735
736fn file_stem(f: &str) -> String {
737    let base = f.rsplit('/').next().unwrap_or(f);
738    base.strip_suffix(".json").unwrap_or(base).to_owned()
739}
740
741/// Lexically normalizes a path (`.` and `..` folded), without touching the
742/// filesystem.
743fn normalize(p: &Path) -> PathBuf {
744    let mut out = PathBuf::new();
745    for c in p.components() {
746        match c {
747            Component::CurDir => {}
748            Component::ParentDir => {
749                if !out.pop() {
750                    out.push("..");
751                }
752            }
753            other => out.push(other),
754        }
755    }
756    out
757}
758
759/// Visits every schema object at a schema position (spec §7.3): the
760/// document root; each value of `properties` and `$defs`; each element of
761/// `prefixItems`, `oneOf` and `anyOf`; the value of `items` and
762/// `additionalProperties`. The value of a refused keyword is not a schema
763/// position, and neither is data (`enum`, `const`, `default`, `examples`):
764/// a `$ref` or a keyword written there is not one.
765pub(crate) fn visit_schemas<'a>(
766    schema: &'a Value,
767    f: &mut dyn FnMut(&'a serde_json::Map<String, Value>),
768) {
769    let Value::Object(m) = schema else { return };
770    f(m);
771    for (k, v) in m {
772        match (k.as_str(), v) {
773            ("properties" | "$defs", Value::Object(subs)) => {
774                subs.values().for_each(|s| visit_schemas(s, f));
775            }
776            ("prefixItems" | "oneOf" | "anyOf", Value::Array(subs)) => {
777                subs.iter().for_each(|s| visit_schemas(s, f));
778            }
779            ("items" | "additionalProperties", sub) => visit_schemas(sub, f),
780            _ => {}
781        }
782    }
783}
784
785/// Every `$ref` at a schema position, in document order.
786fn collect_refs(v: &Value, out: &mut Vec<String>) {
787    visit_schemas(v, &mut |m| {
788        if let Some(Value::String(r)) = m.get("$ref") {
789            out.push(r.clone());
790        }
791    });
792}
793
794/// RFC 8785 (JCS) bytes of a JSON value.
795///
796/// # Panics
797/// Never for a `serde_json::Value`, which always serializes.
798#[must_use]
799pub fn jcs(v: &Value) -> Vec<u8> {
800    serde_json_canonicalizer::to_vec(v).expect("a serde_json::Value always serializes")
801}
802
803/// `sha256:<lowercase hex>` of some bytes.
804#[must_use]
805pub fn sha256_id(bytes: &[u8]) -> String {
806    let digest = Sha256::digest(bytes);
807    let mut s = String::with_capacity(71);
808    s.push_str("sha256:");
809    for b in digest {
810        let _ = write!(s, "{b:02x}");
811    }
812    s
813}
814
815/// The first number outside ±(2^53−1) in a JSON document, if any: an
816/// integer, or a float JCS writes as one
817/// ([`crate::canonical::outside_safe_range`]). JCS implementations disagree
818/// beyond it (Python's `rfc8785` raises).
819pub(crate) fn unsafe_integer(v: &Value) -> Option<String> {
820    match v {
821        Value::Number(n) => crate::canonical::outside_safe_range(n).then(|| n.to_string()),
822        Value::Array(a) => a.iter().find_map(unsafe_integer),
823        Value::Object(m) => m.values().find_map(unsafe_integer),
824        _ => None,
825    }
826}
827
828/// The zk2 JSON Schema subset (spec `core.md` §7.3): the keywords a schema
829/// may use. Annotations are carried and ignored.
830const SUBSET: &[&str] = &[
831    "type",
832    "properties",
833    "required",
834    "additionalProperties",
835    "items",
836    "prefixItems",
837    "enum",
838    "const",
839    "minimum",
840    "maximum",
841    "exclusiveMinimum",
842    "exclusiveMaximum",
843    "minLength",
844    "maxLength",
845    "minItems",
846    "maxItems",
847    "$ref",
848    "oneOf",
849    "anyOf",
850];
851const ANNOTATIONS: &[&str] = &[
852    "$schema",
853    "$id",
854    "$defs",
855    "$comment",
856    "title",
857    "description",
858    "default",
859    "examples",
860    "format",
861    "deprecated",
862    "readOnly",
863    "writeOnly",
864];
865
866/// Every keyword outside the subset at a schema position of a JSON Schema
867/// document ([`visit_schemas`]: never property names, which are data, and
868/// never inside a refused keyword, whose content is not walked).
869fn refused_keywords(schema: &Value, out: &mut std::collections::BTreeSet<String>) {
870    visit_schemas(schema, &mut |m| {
871        for k in m.keys() {
872            if !SUBSET.contains(&k.as_str()) && !ANNOTATIONS.contains(&k.as_str()) {
873                out.insert(k.clone());
874            }
875        }
876    });
877}
878
879#[cfg(test)]
880mod tests {
881    use super::*;
882
883    #[test]
884    fn media_types() {
885        for ok in [
886            "image/jpeg",
887            "video/*",
888            "application/vnd.foo+cbor",
889            "audio/l16",
890        ] {
891            assert!(is_media_type(ok), "{ok}");
892        }
893        for bad in ["image", "Image/jpeg", "*/*", "image/", "image/jpeg; q=1"] {
894            assert!(!is_media_type(bad), "{bad}");
895        }
896    }
897
898    #[test]
899    fn well_known_types_compile_on_demand() {
900        let mut report = Report::default();
901        let mut set = SchemaSet::load(Path::new("."), &SchemasSection::default(), &mut report);
902        let t = set
903            .resolve(
904                &TypeRef::Named("google.protobuf.Empty".into()),
905                "x",
906                &mut report,
907            )
908            .unwrap();
909        assert!(report.0.is_empty(), "{report}");
910        let TypeId::Protobuf { schema, .. } = t else {
911            panic!()
912        };
913        assert_eq!(set.artifacts()[&schema].name, "google/protobuf/empty.proto");
914        assert!(
915            set.resolve(
916                &TypeRef::Named("google.protobuf.Nope".into()),
917                "x",
918                &mut report
919            )
920            .is_none()
921        );
922        assert_eq!(report.codes(), ["E023"]);
923    }
924
925    /// Spec §9.4 (0.6, F-62): a later listed file with an earlier one's id
926    /// (equal JCS bytes, whatever the file bytes) is E024 and not loaded, so
927    /// every name a `$ref` can use stays one artifact's in the bundle.
928    #[test]
929    fn a_listed_file_with_a_taken_id_is_e024() {
930        let dir = std::env::temp_dir().join(format!("zk2-schema-ids-{}", std::process::id()));
931        std::fs::create_dir_all(&dir).unwrap();
932        std::fs::write(
933            dir.join("a.json"),
934            r#"{"$defs": {"X": {"type": "string"}}}"#,
935        )
936        .unwrap();
937        std::fs::write(
938            dir.join("b.json"),
939            "{\"$defs\":{\"X\":{\"type\":\"string\"}}}\n",
940        )
941        .unwrap();
942        std::fs::write(
943            dir.join("c.json"),
944            r#"{"$defs": {"Y": {"$ref": "a.json#/$defs/X"}}}"#,
945        )
946        .unwrap();
947        let sec = SchemasSection {
948            jsonschema: vec!["a.json".into(), "b.json".into(), "c.json".into()],
949            ..SchemasSection::default()
950        };
951        let mut report = Report::default();
952        let set = SchemaSet::load(&dir, &sec, &mut report);
953        std::fs::remove_dir_all(&dir).unwrap();
954        assert_eq!(report.codes(), ["E024"], "{report}");
955        let names: Vec<&str> = set.artifacts().values().map(|a| a.name.as_str()).collect();
956        assert_eq!(names.len(), 2);
957        assert!(names.contains(&"a") && names.contains(&"c"), "{names:?}");
958    }
959
960    #[test]
961    fn normalize_folds_dots() {
962        assert_eq!(
963            normalize(Path::new("a/./b/../c.json")),
964            PathBuf::from("a/c.json")
965        );
966        assert_eq!(normalize(Path::new("../x")), PathBuf::from("../x"));
967    }
968}