ash_jsonschema/lib.rs
1//! # ash-jsonschema
2//!
3//! **Chain the keywords, call `.build()`, get a schema.**
4//!
5//! A typed builder for [JSON Schema 2020-12]. One dialect, deliberately: the
6//! latest standard is the only thing this crate emits, so there is no draft
7//! selector to thread through the API and no keyword that means one thing here
8//! and another there.
9//!
10//! ```
11//! use ash_jsonschema::{Format, Schema, SchemaError};
12//!
13//! # fn main() -> Result<(), SchemaError> {
14//! let schema = Schema::object()
15//! .dialect()
16//! .id("https://example.com/schemas/user")
17//! .title("User")
18//! .required_property("id", Schema::string().format(Format::Uuid))
19//! .required_property("email", Schema::string().format(Format::Email))
20//! .property("age", Schema::integer().minimum(0).nullable())
21//! .property("tags", Schema::array().items(Schema::string()).unique_items(true))
22//! .additional_properties(false)
23//! .build()?;
24//!
25//! println!("{}", schema.to_json_pretty());
26//! # Ok(())
27//! # }
28//! ```
29//!
30//! ## The shape of the API
31//!
32//! [`Schema`] is both the output type and the entry point. Each constructor
33//! returns a builder that has already committed the `type` keyword:
34//!
35//! | Entry point | `type` | Builder |
36//! |---|---|---|
37//! | [`Schema::string`] | `string` | [`StringBuilder`] |
38//! | [`Schema::number`] / [`Schema::integer`] | `number` / `integer` | [`NumericBuilder`] |
39//! | [`Schema::object`] | `object` | [`ObjectBuilder`] |
40//! | [`Schema::array`] | `array` | [`ArrayBuilder`] |
41//! | [`Schema::boolean`] / [`Schema::null`] | `boolean` / `null` | [`AnyBuilder`] |
42//! | [`Schema::builder`], [`Schema::all_of`], [`Schema::reference`], … | *(none)* | [`AnyBuilder`] |
43//!
44//! The type is not decoration. The keywords of the core, metadata, and
45//! applicator vocabularies are available on every builder, but a type-specific
46//! assertion is only reachable from the builder it applies to — `.min_length()`
47//! exists on a string schema and nowhere else, so a keyword that a validator
48//! would silently ignore does not compile in the first place.
49//!
50//! ## Nesting
51//!
52//! Only the outermost chain needs `.build()`. Every keyword that takes a
53//! subschema accepts `impl Into<Schema>`, which a builder satisfies directly —
54//! and so does a bare `bool`, since `true` and `false` are themselves schemas:
55//!
56//! ```
57//! # use ash_jsonschema::Schema;
58//! let schema = Schema::object()
59//! .property("nested", Schema::object().additional_properties(false))
60//! .property("anything", true)
61//! .build()
62//! .unwrap();
63//! ```
64//!
65//! ## `.build()` checks its work
66//!
67//! The 2020-12 meta-schema — all eight of its documents — is vendored into the
68//! crate and parsed once into memory on first use. Nothing is fetched at
69//! runtime. [`build`](Builder::build) runs the document you just assembled
70//! against it and returns a [`SchemaError`] rather than a `Schema` if it does
71//! not hold up.
72//!
73//! The check is a depth-first walk, so the root and every subschema beneath it
74//! are validated in turn, each in its own right — a nested builder needs no
75//! `.build()` of its own and is checked all the same. A [`Violation`] names the
76//! JSON Pointer of the offending subschema and the meta-schema rule it broke:
77//!
78//! ```
79//! # use ash_jsonschema::Schema;
80//! let error = Schema::object()
81//! .property("inner", Schema::string().anchor("not a valid anchor"))
82//! .build()
83//! .unwrap_err();
84//!
85//! assert_eq!(error.first().location, "/properties/inner/$anchor");
86//! assert_eq!(error.first().rule, "meta/core#/$defs/anchorString/pattern");
87//! ```
88//!
89//! [`build_unchecked`](Builder::build_unchecked) skips the check, and
90//! [`Schema::validate`] runs it on demand.
91//!
92//! ## Reading a schema back in
93//!
94//! [`Schema::parse`] reads a document that already exists, and
95//! [`Schema::parse_checked`] reads and validates in one step. Keywords outside
96//! the dialect are kept in [`SchemaObject::extensions`] rather than dropped, so
97//! a document parsed and rendered back out is unchanged;
98//! [`keyword`](Builder::keyword) writes one from the builder side.
99//!
100//! ```
101//! # use ash_jsonschema::Schema;
102//! let schema = Schema::parse(r#"{"type":"object","properties":{"id":{"type":"string"}}}"#)
103//! .unwrap();
104//!
105//! assert!(schema.property("id").is_some());
106//! assert_eq!(schema.pointer("/properties/id/type"), Some(serde_json::json!("string")));
107//! ```
108//!
109//! [`Schema::into_builder`] picks such a schema back up and resumes the chain
110//! on it; [`Schema::into_typed`] does the same under a type marker, reopening
111//! that type's vocabulary.
112//!
113//! ## Rendering
114//!
115//! [`Schema`] is [`serde::Serialize`], so it drops into any serializer.
116//! [`to_json`](Schema::to_json), [`to_json_pretty`](Schema::to_json_pretty),
117//! and [`to_value`](Schema::to_value) are the shorthands. Output is
118//! deterministic: keywords render in the specification's own grouping order,
119//! and `properties`, `$defs`, and the other named-subschema maps render in the
120//! order the builder calls declared them.
121//!
122//! ## `$ref` resolves against a [`Registry`]
123//!
124//! Following a reference needs a base URI to resolve against and somewhere to
125//! look the result up. A [`Registry`] is that somewhere: schemas go in under
126//! the `$id` they declare, and references resolve across documents, not only
127//! within one.
128//!
129//! ```
130//! # use ash_jsonschema::{Registry, Schema};
131//! let address = Schema::object()
132//! .id("https://example.com/schemas/address")
133//! .required_property("city", Schema::string())
134//! .build()?;
135//!
136//! let user = Schema::object()
137//! .id("https://example.com/schemas/user")
138//! .required_property("address", Schema::reference("address"))
139//! .build()?;
140//!
141//! let mut registry = Registry::new();
142//! registry.insert(&address)?;
143//! registry.insert(&user)?;
144//!
145//! registry.check_references()?;
146//! # Ok::<(), Box<dyn std::error::Error>>(())
147//! ```
148//!
149//! Nothing is fetched: a registry resolves against what it was given, so a
150//! reference to a document nobody inserted dangles rather than reaching the
151//! network.
152//!
153//! ## A schema is a source, not just an output
154//!
155//! [`diff()`] compares two versions and says what the change breaks — separately
156//! for whoever writes the data and whoever reads it, since a change lands on
157//! those two in opposite directions:
158//!
159//! ```
160//! # use ash_jsonschema::{Schema, diff::{diff, Role}};
161//! let v1 = Schema::object().required_property("id", Schema::string()).build()?;
162//! let v2 = Schema::object()
163//! .required_property("id", Schema::string())
164//! .required_property("email", Schema::string())
165//! .build()?;
166//!
167//! let report = diff(&v1, &v2);
168//! assert!(report.is_breaking_for(Role::Writer));
169//! assert!(!report.is_breaking_for(Role::Reader));
170//! # Ok::<(), ash_jsonschema::SchemaError>(())
171//! ```
172//!
173//! [`bundle()`] collapses a set of schemas into one self-contained document,
174//! embedding each referenced document under `$defs` with its `$id` intact so
175//! the references that named it still resolve.
176//!
177//! ## Macros
178//!
179//! [`object!`] writes `properties` and `required` from one list — the
180//! duplication object schemas otherwise force — and yields an ordinary builder:
181//!
182//! ```
183//! # use ash_jsonschema::{Schema, object};
184//! let user = object! {
185//! required "id": Schema::string().format("uuid"),
186//! "age": Schema::integer().minimum(0),
187//! }
188//! .closed()
189//! .build()?;
190//!
191//! assert!(user.requires("id"));
192//! # Ok::<(), ash_jsonschema::SchemaError>(())
193//! ```
194//!
195//! [`defs!`] takes a block of definitions; [`one_of_tagged!`] writes the tagged
196//! union the dialect has no keyword for. They exist for shapes that repeat
197//! *structure*, not to shorten single keywords.
198//!
199//! ## Getting a copy out
200//!
201//! [`Schema::export`] returns a detached copy, and
202//! [`Schema::export_at`] lifts a subschema out as a [`Schema`] rather than a
203//! bare [`serde_json::Value`]. Both are on [`FrozenSchema`] too, and `export`
204//! is on every builder — where it takes a copy without ending the chain.
205//!
206//! ## Validating instances
207//!
208//! Behind the **`validation`** feature, on by default: the `validator` module
209//! answers the other question — does this JSON satisfy the schema?
210//!
211#![cfg_attr(
212 feature = "validation",
213 doc = r#"
214```
215# use ash_jsonschema::{Schema, Validator, object};
216# use ash_jsonschema::validator::Mode;
217let validator = Validator::new(&object! {
218 required "id": Schema::string().min_length(1),
219}.build()?)?;
220
221assert!(validator.is_valid(&serde_json::json!({"id": "a1"})));
222
223let outcome = validator.validate(&serde_json::json!({}), Mode::All);
224assert_eq!(outcome.first().unwrap().message(), "`id` is required");
225# Ok::<(), Box<dyn std::error::Error>>(())
226```
227"#
228)]
229//!
230// The passage below names types that exist only with the `validation`
231// feature, so it is gated with them — an intra-doc link to a type that was
232// configured out is a hard rustdoc error, not a warning.
233#![cfg_attr(
234 feature = "validation",
235 doc = r#"
236A validator's schema is fixed for its life. `Mode::All` reports every error
237and `Mode::FailFast` stops at the first; both give an [`Outcome`] whose
238errors name where in the instance the problem is *and* which schema keyword
239rejected it.
240
241## Output the specification defines
242
243An [`Outcome`] is the specification's output tree, not a shape of this
244crate's invention. [`Outcome::output`] renders it as any of the four
245formats 2020-12 describes — [`Flag`](OutputFormat::Flag),
246[`Basic`](OutputFormat::Basic), [`Detailed`](OutputFormat::Detailed),
247[`Verbose`](OutputFormat::Verbose) — and the result validates against
248`https://json-schema.org/draft/2020-12/output/schema`, so it can be read by
249tooling that knows the standard rather than this crate.
250
251Nesting is what makes a branching schema debuggable: a failed `anyOf` says
252only "no alternative matched", so the evaluator keeps *why each alternative
253was rejected* beneath it. [`Outcome::errors`] is the flat view of the same
254run, and [`Outcome::unit`] is the tree.
255
256[`Validator::annotate`] collects what the annotation keywords —
257`title`, `description`, `default`, `readOnly` — attached to each location.
258[`Validator::validate`] does not, since the usual question is whether an
259instance is valid and it should not pay for an answer it will not read.
260"#
261)]
262//!
263//! Coverage is every assertion and applicator of the dialect, including
264//! `unevaluated*` and `$dynamicRef`.
265//!
266//! `format` is an annotation by default, as 2020-12 specifies. Asking for it —
267//! `Validator::builder(&schema).assert_formats()` — turns on checks for the
268//! temporal, address, and pointer formats, and `.format(name, check)` registers
269//! a rule of your own under any name. `validator::tld` answers whether a
270//! hostname's suffix is shaped like a TLD, or (behind `iana-tlds`) is one that
271//! exists.
272//!
273//! Turn the feature off — `default-features = false` — for a build that only
274//! writes and reads schemas. No dependency goes with it: `regex-lite` is needed
275//! either way, since the meta-schema check `.build()` runs asserts patterns of
276//! its own. What goes is the evaluator, about a fifth of the crate.
277//!
278//! ## What this crate does not do
279//!
280//! It **builds**, **reads**, and **checks against** schemas. What it does not
281//! do is fetch — no `$ref` is retrieved over the network. The
282//! meta-schema check `.build()` runs constrains a schema's *shape* — that
283//! `$anchor` is a plain name, that `required` holds unique strings, that
284//! `minLength` is not negative — and says nothing about whether the schema
285//! makes sense. A `minLength` above its `maxLength`, or a `then` without an
286//! `if`, is a legal 2020-12 document and builds without complaint.
287//!
288//! References are followed only when asked: `.build()` does not resolve them,
289//! and a [`Registry`] does.
290//!
291//! [JSON Schema 2020-12]: https://json-schema.org/draft/2020-12/release-notes
292
293#![deny(missing_docs)]
294#![deny(rustdoc::broken_intra_doc_links)]
295
296pub mod builder;
297pub mod bundle;
298pub mod diff;
299pub mod error;
300pub mod format;
301pub mod frozen;
302pub mod macros;
303pub mod map;
304pub mod meta;
305pub mod registry;
306pub mod schema;
307pub mod uri;
308mod validate;
309#[cfg(feature = "validation")]
310pub mod validator;
311pub mod walk;
312
313pub use builder::{
314 AnyBuilder, ArrayBuilder, Builder, NumericBuilder, ObjectBuilder, StringBuilder, kind,
315};
316pub use bundle::{BundleError, bundle};
317pub use diff::{Change, ChangeKind, Effect, Report, Role, diff, diff_resolved};
318pub use error::{ErrorKind, ParseError, SchemaError, Violation};
319pub use format::Format;
320pub use frozen::FrozenSchema;
321pub use map::OrderedMap;
322pub use meta::MetaSchema;
323pub use registry::{Reference, Registry, RegistryError};
324pub use schema::{
325 DIALECT, DIALECT_KEYWORDS, Num, Schema, SchemaObject, SchemaType, TypeSet, UnknownSchemaType,
326 is_dialect_keyword,
327};
328pub use validate::validate_document;
329#[cfg(feature = "validation")]
330pub use validator::{CompileError, Mode, Outcome, OutputFormat, Unit, ValidationError, Validator};
331
332/// The types a typical caller wants in scope.
333///
334/// ```
335/// use ash_jsonschema::prelude::*;
336///
337/// let schema = Schema::object().property("name", Schema::string()).build().unwrap();
338/// ```
339pub mod prelude {
340 pub use crate::{
341 Format, Num, ParseError, Schema, SchemaError, SchemaObject, SchemaType, TypeSet, Violation,
342 };
343}