Debian Codegraph @

src/lib.rs

raw symbols SCIP
1 #![allow(clippy::unnecessary_wraps)]
2 //! A high-performance JSON Schema validator for Rust.
3 //!
4 //! - 📚 Support for popular JSON Schema drafts
5 //! - 🔧 Custom keywords and format validators
6 //! - 🌐 Blocking & non-blocking remote reference fetching (network/file)
7 //! - 🎨 Structured Output v1 reports (flag/list/hierarchical)
8 //! - ✨ Meta-schema validation for schema documents
9 //! - 🚀 WebAssembly support
10 //!
11 //! ## Supported drafts
12 //!
13 //! Compliance levels vary across drafts, with newer versions having some unimplemented keywords.
14 //!
15 //! - ![Draft 2020-12](https://img.shields.io/endpoint?url=https%3A%2F%2Fbowtie.report%2Fbadges%2Frust-jsonschema%2Fcompliance%2Fdraft2020-12.json)
16 //! - ![Draft 2019-09](https://img.shields.io/endpoint?url=https%3A%2F%2Fbowtie.report%2Fbadges%2Frust-jsonschema%2Fcompliance%2Fdraft2019-09.json)
17 //! - ![Draft 7](https://img.shields.io/endpoint?url=https%3A%2F%2Fbowtie.report%2Fbadges%2Frust-jsonschema%2Fcompliance%2Fdraft7.json)
18 //! - ![Draft 6](https://img.shields.io/endpoint?url=https%3A%2F%2Fbowtie.report%2Fbadges%2Frust-jsonschema%2Fcompliance%2Fdraft6.json)
19 //! - ![Draft 4](https://img.shields.io/endpoint?url=https%3A%2F%2Fbowtie.report%2Fbadges%2Frust-jsonschema%2Fcompliance%2Fdraft4.json)
20 //!
21 //! # Validation
22 //!
23 //! The `jsonschema` crate offers two main approaches to validation: one-off validation and reusable validators.
24 //! When external references are involved, the validator can be constructed using either blocking or non-blocking I/O.
25 //!
26 //!
27 //! For simple use cases where you need to validate an instance against a schema once, use [`is_valid`] or [`validate`] functions:
28 //!
29 //! ```rust
30 //! use serde_json::json;
31 //!
32 //! let schema = json!({"type": "string"});
33 //! let instance = json!("Hello, world!");
34 //!
35 //! assert!(jsonschema::is_valid(&schema, &instance));
36 //! assert!(jsonschema::validate(&schema, &instance).is_ok());
37 //! ```
38 //!
39 //! For better performance, especially when validating multiple instances against the same schema, build a validator once and reuse it:
40 //! If your schema contains external references, you can choose between blocking and non-blocking construction:
41 //!
42 //! ```rust
43 //! # fn main() -> Result<(), Box<dyn std::error::Error>> {
44 //! use serde_json::json;
45 //!
46 //! let schema = json!({"type": "string"});
47 //! // Blocking construction - will fetch external references synchronously
48 //! let validator = jsonschema::validator_for(&schema)?;
49 //! // Non-blocking construction - will fetch external references asynchronously
50 //! # #[cfg(feature = "resolve-async")]
51 //! # async fn async_example() -> Result<(), Box<dyn std::error::Error>> {
52 //! # let schema = json!({"type": "string"});
53 //! let validator = jsonschema::async_validator_for(&schema).await?;
54 //! # Ok(())
55 //! # }
56 //!
57 //! // Once constructed, validation is always synchronous as it works with in-memory data
58 //! assert!(validator.is_valid(&json!("Hello, world!")));
59 //! assert!(!validator.is_valid(&json!(42)));
60 //! assert!(validator.validate(&json!(42)).is_err());
61 //!
62 //! // Iterate over all errors
63 //! let instance = json!(42);
64 //! for error in validator.iter_errors(&instance) {
65 //! eprintln!("Error: {}", error);
66 //! eprintln!("Location: {}", error.instance_path());
67 //! }
68 //! # Ok(())
69 //! # }
70 //! ```
71 //!
72 //! ### Note on `format` keyword
73 //!
74 //! By default, format validation is draft‑dependent. To opt in for format checks, you can configure your validator like this:
75 //!
76 //! ```rust
77 //! # fn main() -> Result<(), Box<dyn std::error::Error>> {
78 //! # use serde_json::json;
79 //! #
80 //! # let schema = json!({"type": "string"});
81 //! let validator = jsonschema::draft202012::options()
82 //! .should_validate_formats(true)
83 //! .build(&schema)?;
84 //! # Ok(())
85 //! # }
86 //! ```
87 //!
88 //! Once built, any `format` keywords in your schema will be actively validated according to the chosen draft.
89 //!
90 //! # Structured Output
91 //!
92 //! The `evaluate()` method provides access to structured validation output formats defined by
93 //! [JSON Schema Output v1](https://github.com/json-schema-org/json-schema-spec/blob/main/specs/output/jsonschema-validation-output-machines.md).
94 //! This is useful when you need detailed information about the validation process beyond simple pass/fail results.
95 //!
96 //! ```rust
97 //! # fn main() -> Result<(), Box<dyn std::error::Error>> {
98 //! use serde_json::json;
99 //!
100 //! let schema = json!({
101 //! "type": "object",
102 //! "properties": {
103 //! "name": {"type": "string"},
104 //! "age": {"type": "number", "minimum": 0}
105 //! },
106 //! "required": ["name"]
107 //! });
108 //!
109 //! let validator = jsonschema::validator_for(&schema)?;
110 //! let instance = json!({"name": "Alice", "age": 30});
111 //!
112 //! // Evaluate the instance
113 //! let evaluation = validator.evaluate(&instance);
114 //!
115 //! // Flag format: Simple boolean validity
116 //! let flag = evaluation.flag();
117 //! assert!(flag.valid);
118 //!
119 //! // List format: Flat list of all evaluation steps
120 //! let list_output = serde_json::to_value(evaluation.list())?;
121 //! println!("List output: {}", serde_json::to_string_pretty(&list_output)?);
122 //!
123 //! // Hierarchical format: Nested tree structure
124 //! let hierarchical_output = serde_json::to_value(evaluation.hierarchical())?;
125 //! println!(
126 //! "Hierarchical output: {}",
127 //! serde_json::to_string_pretty(&hierarchical_output)?
128 //! );
129 //!
130 //! // Iterate over annotations collected during validation
131 //! for annotation in evaluation.iter_annotations() {
132 //! println!("Annotation at {}: {:?}",
133 //! annotation.instance_location,
134 //! annotation.annotations
135 //! );
136 //! }
137 //!
138 //! // Iterate over errors (if any)
139 //! for error in evaluation.iter_errors() {
140 //! println!("Error: {}", error.error);
141 //! }
142 //! # Ok(())
143 //! # }
144 //! ```
145 //!
146 //! The structured output formats are particularly useful for:
147 //! - **Debugging**: Understanding exactly which schema keywords matched or failed
148 //! - **User feedback**: Providing detailed, actionable error messages
149 //! - **Annotations**: Collecting metadata produced by successful validation
150 //! - **Tooling**: Building development tools that work with JSON Schema
151 //!
152 //! For example, validating `["hello", "oops"]` against a schema with both `prefixItems` and
153 //! `items` produces list output similar to:
154 //!
155 //! ```json
156 //! {
157 //! "valid": false,
158 //! "details": [
159 //! {"valid": false, "evaluationPath": "", "schemaLocation": "", "instanceLocation": ""},
160 //! {
161 //! "valid": false,
162 //! "evaluationPath": "/items",
163 //! "schemaLocation": "/items",
164 //! "instanceLocation": "",
165 //! "droppedAnnotations": true
166 //! },
167 //! {
168 //! "valid": false,
169 //! "evaluationPath": "/items",
170 //! "schemaLocation": "/items",
171 //! "instanceLocation": "/1"
172 //! },
173 //! {
174 //! "valid": false,
175 //! "evaluationPath": "/items/type",
176 //! "schemaLocation": "/items/type",
177 //! "instanceLocation": "/1",
178 //! "errors": {"type": "\"oops\" is not of type \"integer\""}
179 //! },
180 //! {"valid": true, "evaluationPath": "/prefixItems", "schemaLocation": "/prefixItems", "instanceLocation": "", "annotations": 0}
181 //! ]
182 //! }
183 //! ```
184 //!
185 //! ## Output Formats
186 //!
187 //! ### Flag Format
188 //!
189 //! The simplest format, containing only a boolean validity indicator:
190 //!
191 //! ```rust
192 //! # fn main() -> Result<(), Box<dyn std::error::Error>> {
193 //! # use serde_json::json;
194 //! # let schema = json!({"type": "string"});
195 //! # let validator = jsonschema::validator_for(&schema)?;
196 //! let evaluation = validator.evaluate(&json!("hello"));
197 //! let flag = evaluation.flag();
198 //!
199 //! let output = serde_json::to_value(flag)?;
200 //! // Output: {"valid": true}
201 //! # Ok(())
202 //! # }
203 //! ```
204 //!
205 //! ### List Format
206 //!
207 //! A flat list of all evaluation units, where each unit describes a validation step:
208 //!
209 //! ```rust
210 //! # fn main() -> Result<(), Box<dyn std::error::Error>> {
211 //! # use serde_json::json;
212 //! let schema = json!({
213 //! "allOf": [
214 //! {"type": "number"},
215 //! {"minimum": 0}
216 //! ]
217 //! });
218 //! let validator = jsonschema::validator_for(&schema)?;
219 //! let evaluation = validator.evaluate(&json!(42));
220 //!
221 //! let list = evaluation.list();
222 //! let output = serde_json::to_value(list)?;
223 //! // Output includes all evaluation steps in a flat array
224 //! # Ok(())
225 //! # }
226 //! ```
227 //!
228 //! ### Hierarchical Format
229 //!
230 //! A nested tree structure that mirrors the schema's logical structure:
231 //!
232 //! ```rust
233 //! # fn main() -> Result<(), Box<dyn std::error::Error>> {
234 //! # use serde_json::json;
235 //! let schema = json!({
236 //! "allOf": [
237 //! {"type": "number"},
238 //! {"minimum": 0}
239 //! ]
240 //! });
241 //! let validator = jsonschema::validator_for(&schema)?;
242 //! let evaluation = validator.evaluate(&json!(42));
243 //!
244 //! let hierarchical = evaluation.hierarchical();
245 //! let output = serde_json::to_value(hierarchical)?;
246 //! // Output has nested "details" arrays for sub-schema evaluations
247 //! # Ok(())
248 //! # }
249 //! ```
250 //!
251 //! # Meta-Schema Validation
252 //!
253 //! The crate provides functionality to validate JSON Schema documents themselves against their meta-schemas.
254 //! This ensures your schema documents are valid according to the JSON Schema specification.
255 //!
256 //! ```rust
257 //! use serde_json::json;
258 //!
259 //! let schema = json!({
260 //! "type": "object",
261 //! "properties": {
262 //! "name": {"type": "string"},
263 //! "age": {"type": "integer", "minimum": 0}
264 //! }
265 //! });
266 //!
267 //! // Validate schema with automatic draft detection
268 //! assert!(jsonschema::meta::is_valid(&schema));
269 //! assert!(jsonschema::meta::validate(&schema).is_ok());
270 //!
271 //! // Invalid schema example
272 //! let invalid_schema = json!({
273 //! "type": "invalid_type", // must be one of the valid JSON Schema types
274 //! "minimum": "not_a_number"
275 //! });
276 //! assert!(!jsonschema::meta::is_valid(&invalid_schema));
277 //! assert!(jsonschema::meta::validate(&invalid_schema).is_err());
278 //! ```
279 //!
280 //! # Configuration
281 //!
282 //! `jsonschema` provides several ways to configure and use JSON Schema validation.
283 //!
284 //! ## Draft-specific Modules
285 //!
286 //! The library offers modules for specific JSON Schema draft versions:
287 //!
288 //! - [`draft4`]
289 //! - [`draft6`]
290 //! - [`draft7`]
291 //! - [`draft201909`]
292 //! - [`draft202012`]
293 //!
294 //! Each module provides:
295 //! - A `new` function to create a validator
296 //! - An `is_valid` function for validation with a boolean result
297 //! - An `validate` function for getting the first validation error
298 //! - An `options` function to create a draft-specific configuration builder
299 //! - A `meta` module for draft-specific meta-schema validation
300 //!
301 //! Here's how you can explicitly use a specific draft version:
302 //!
303 //! ```rust
304 //! # fn main() -> Result<(), Box<dyn std::error::Error>> {
305 //! use serde_json::json;
306 //!
307 //! let schema = json!({"type": "string"});
308 //!
309 //! // Instance validation
310 //! let validator = jsonschema::draft7::new(&schema)?;
311 //! assert!(validator.is_valid(&json!("Hello")));
312 //!
313 //! // Meta-schema validation
314 //! assert!(jsonschema::draft7::meta::is_valid(&schema));
315 //! # Ok(())
316 //! # }
317 //! ```
318 //!
319 //! You can also use the convenience [`is_valid`] and [`validate`] functions:
320 //!
321 //! ```rust
322 //! use serde_json::json;
323 //!
324 //! let schema = json!({"type": "number", "minimum": 0});
325 //! let instance = json!(42);
326 //!
327 //! assert!(jsonschema::draft202012::is_valid(&schema, &instance));
328 //! assert!(jsonschema::draft202012::validate(&schema, &instance).is_ok());
329 //! ```
330 //!
331 //! For more advanced configuration, you can use the draft-specific `options` function:
332 //!
333 //! ```rust
334 //! # fn main() -> Result<(), Box<dyn std::error::Error>> {
335 //! use serde_json::json;
336 //!
337 //! let schema = json!({"type": "string", "format": "ends-with-42"});
338 //! let validator = jsonschema::draft202012::options()
339 //! .with_format("ends-with-42", |s| s.ends_with("42"))
340 //! .should_validate_formats(true)
341 //! .build(&schema)?;
342 //!
343 //! assert!(validator.is_valid(&json!("Hello 42")));
344 //! assert!(!validator.is_valid(&json!("No!")));
345 //! # Ok(())
346 //! # }
347 //! ```
348 //!
349 //! ## General Configuration
350 //!
351 //! For configuration options that are not draft-specific, `jsonschema` provides a builder via `jsonschema::options()`.
352 //!
353 //! Here's an example:
354 //!
355 //! ```rust
356 //! # fn main() -> Result<(), Box<dyn std::error::Error>> {
357 //! use serde_json::json;
358 //!
359 //! let schema = json!({"type": "string"});
360 //! let validator = jsonschema::options()
361 //! // Add configuration options here
362 //! .build(&schema)?;
363 //!
364 //! assert!(validator.is_valid(&json!("Hello")));
365 //! # Ok(())
366 //! # }
367 //! ```
368 //!
369 //! For a complete list of configuration options and their usage, please refer to the [`ValidationOptions`] struct.
370 //!
371 //! ## Automatic Draft Detection
372 //!
373 //! If you don't need to specify a particular draft version, you can use `jsonschema::validator_for`
374 //! which automatically detects the appropriate draft:
375 //!
376 //! ```rust
377 //! # fn main() -> Result<(), Box<dyn std::error::Error>> {
378 //! use serde_json::json;
379 //!
380 //! let schema = json!({"$schema": "http://json-schema.org/draft-07/schema#", "type": "string"});
381 //! let validator = jsonschema::validator_for(&schema)?;
382 //!
383 //! assert!(validator.is_valid(&json!("Hello")));
384 //! # Ok(())
385 //! # }
386 //! ```
387 //!
388 //! # External References
389 //!
390 //! By default, `jsonschema` resolves HTTP references using `reqwest` and file references from the local file system.
391 //! Both blocking and non-blocking retrieval is supported during validator construction. Note that the validation
392 //! itself is always synchronous as it operates on in-memory data only.
393 //!
394 //! ```rust
395 //! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
396 //! use serde_json::json;
397 //!
398 //! let schema = json!({"$schema": "http://json-schema.org/draft-07/schema#", "type": "string"});
399 //!
400 //! // Building a validator with blocking retrieval (default)
401 //! let validator = jsonschema::validator_for(&schema)?;
402 //!
403 //! // Building a validator with non-blocking retrieval (requires `resolve-async` feature)
404 //! # #[cfg(feature = "resolve-async")]
405 //! let validator = jsonschema::async_validator_for(&schema).await?;
406 //!
407 //! // Validation is always synchronous
408 //! assert!(validator.is_valid(&json!("Hello")));
409 //! # Ok(())
410 //! # }
411 //! ```
412 //!
413 //! To enable HTTPS support, add the `rustls-tls` feature to `reqwest` in your `Cargo.toml`:
414 //!
415 //! ```toml
416 //! reqwest = { version = "*", features = ["rustls-tls"] }
417 //! ```
418 //!
419 //! You can disable the default behavior using crate features:
420 //!
421 //! - Disable HTTP resolving: `default-features = false, features = ["resolve-file"]`
422 //! - Disable file resolving: `default-features = false, features = ["resolve-http"]`
423 //! - Enable async resolution: `features = ["resolve-async"]`
424 //! - Disable all resolving: `default-features = false`
425 //!
426 //! ## Custom retrievers
427 //!
428 //! You can implement custom retrievers for both blocking and non-blocking retrieval:
429 //!
430 //! ```rust
431 //! # fn main() -> Result<(), Box<dyn std::error::Error>> {
432 //! use std::{collections::HashMap, sync::Arc};
433 //! use jsonschema::{Retrieve, Uri};
434 //! use serde_json::{json, Value};
435 //!
436 //! struct InMemoryRetriever {
437 //! schemas: HashMap<String, Value>,
438 //! }
439 //!
440 //! impl Retrieve for InMemoryRetriever {
441 //!
442 //! fn retrieve(
443 //! &self,
444 //! uri: &Uri<String>,
445 //! ) -> Result<Value, Box<dyn std::error::Error + Send + Sync>> {
446 //! self.schemas
447 //! .get(uri.as_str())
448 //! .cloned()
449 //! .ok_or_else(|| format!("Schema not found: {uri}").into())
450 //! }
451 //! }
452 //!
453 //! let mut schemas = HashMap::new();
454 //! schemas.insert(
455 //! "https://example.com/person.json".to_string(),
456 //! json!({
457 //! "type": "object",
458 //! "properties": {
459 //! "name": { "type": "string" },
460 //! "age": { "type": "integer" }
461 //! },
462 //! "required": ["name", "age"]
463 //! }),
464 //! );
465 //!
466 //! let retriever = InMemoryRetriever { schemas };
467 //!
468 //! let schema = json!({
469 //! "$ref": "https://example.com/person.json"
470 //! });
471 //!
472 //! let validator = jsonschema::options()
473 //! .with_retriever(retriever)
474 //! .build(&schema)?;
475 //!
476 //! assert!(validator.is_valid(&json!({
477 //! "name": "Alice",
478 //! "age": 30
479 //! })));
480 //!
481 //! assert!(!validator.is_valid(&json!({
482 //! "name": "Bob"
483 //! })));
484 //! # Ok(())
485 //! # }
486 //! ```
487 //!
488 //! And non-blocking version with the `resolve-async` feature enabled:
489 //!
490 //! ```rust
491 //! # #[cfg(feature = "resolve-async")]
492 //! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
493 //! use jsonschema::{AsyncRetrieve, Registry, Resource, Uri};
494 //! use serde_json::{Value, json};
495 //!
496 //! struct HttpRetriever;
497 //!
498 //! #[cfg_attr(target_family = "wasm", async_trait::async_trait(?Send))]
499 //! #[cfg_attr(not(target_family = "wasm"), async_trait::async_trait)]
500 //! impl AsyncRetrieve for HttpRetriever {
501 //! async fn retrieve(
502 //! &self,
503 //! uri: &Uri<String>,
504 //! ) -> Result<Value, Box<dyn std::error::Error + Send + Sync>> {
505 //! reqwest::get(uri.as_str())
506 //! .await?
507 //! .json()
508 //! .await
509 //! .map_err(Into::into)
510 //! }
511 //! }
512 //!
513 //! // Then use it to build a validator
514 //! let validator = jsonschema::async_options()
515 //! .with_retriever(HttpRetriever)
516 //! .build(&json!({"$ref": "https://example.com/user.json"}))
517 //! .await?;
518 //! # Ok(())
519 //! # }
520 //! ```
521 //!
522 //! On `wasm32` targets, use `async_trait::async_trait(?Send)` so your retriever can rely on `Rc`, `JsFuture`, or other non-thread-safe types.
523 //!
524 //! ## Validating against schema definitions
525 //!
526 //! When working with large schemas containing multiple definitions (e.g., Open API schemas, DAP schemas),
527 //! you may want to validate data against a specific definition rather than the entire schema. This can be
528 //! achieved by registering the root schema as a resource and creating a wrapper schema that references
529 //! the target definition:
530 //!
531 //! ```rust
532 //! # fn main() -> Result<(), Box<dyn std::error::Error>> {
533 //! use serde_json::json;
534 //! use jsonschema::Resource;
535 //!
536 //! // Root schema with multiple definitions
537 //! let root_schema = json!({
538 //! "$id": "https://example.com/root",
539 //! "definitions": {
540 //! "User": {
541 //! "type": "object",
542 //! "properties": {
543 //! "name": {"type": "string"},
544 //! "age": {"type": "integer", "minimum": 0}
545 //! },
546 //! "required": ["name"]
547 //! },
548 //! "Product": {
549 //! "type": "object",
550 //! "properties": {
551 //! "id": {"type": "integer"},
552 //! "title": {"type": "string"}
553 //! },
554 //! "required": ["id", "title"]
555 //! }
556 //! }
557 //! });
558 //!
559 //! // Create a schema that references the specific definition you want to validate against
560 //! let user_schema = json!({"$ref": "https://example.com/root#/definitions/User"});
561 //!
562 //! // Register the root schema and build validator for the specific definition
563 //! let validator = jsonschema::options()
564 //! .with_resource("https://example.com/root", Resource::from_contents(root_schema))
565 //! .build(&user_schema)?;
566 //!
567 //! // Now validate data against just the User definition
568 //! assert!(validator.is_valid(&json!({"name": "Alice", "age": 30})));
569 //! assert!(!validator.is_valid(&json!({"age": 25}))); // Missing required "name"
570 //! # Ok(())
571 //! # }
572 //! ```
573 //!
574 //! This pattern is particularly useful when:
575 //! - Working with API schemas that define multiple request/response types
576 //! - Validating configuration snippets against specific sections of a larger schema
577 //! - Testing individual schema components in isolation
578 //!
579 //! # Regular Expression Configuration
580 //!
581 //! The `jsonschema` crate allows configuring the regular expression engine used for validating
582 //! keywords like `pattern` or `patternProperties`.
583 //!
584 //! By default, the crate uses [`fancy-regex`](https://docs.rs/fancy-regex), which supports advanced
585 //! regular expression features such as lookaround and backreferences.
586 //!
587 //! The primary motivation for switching to the `regex` engine is security and performance:
588 //! it guarantees linear-time matching, preventing potential Denial of Service attacks from malicious patterns
589 //! in user-provided schemas while offering better performance with a smaller feature set.
590 //!
591 //! You can configure the engine at **runtime** using the [`PatternOptions`] API:
592 //!
593 //! ### Example: Configure `fancy-regex` with Backtracking Limit
594 //!
595 //! ```rust
596 //! use serde_json::json;
597 //! use jsonschema::PatternOptions;
598 //!
599 //! let schema = json!({
600 //! "type": "string",
601 //! "pattern": "^(a+)+$"
602 //! });
603 //!
604 //! let validator = jsonschema::options()
605 //! .with_pattern_options(
606 //! PatternOptions::fancy_regex()
607 //! .backtrack_limit(10_000)
608 //! )
609 //! .build(&schema)
610 //! .expect("A valid schema");
611 //! ```
612 //!
613 //! ### Example: Use the `regex` Engine Instead
614 //!
615 //! ```rust
616 //! use serde_json::json;
617 //! use jsonschema::PatternOptions;
618 //!
619 //! let schema = json!({
620 //! "type": "string",
621 //! "pattern": "^a+$"
622 //! });
623 //!
624 //! let validator = jsonschema::options()
625 //! .with_pattern_options(PatternOptions::regex())
626 //! .build(&schema)
627 //! .expect("A valid schema");
628 //! ```
629 //!
630 //! ### Notes
631 //!
632 //! - If neither engine is explicitly set, `fancy-regex` is used by default.
633 //! - Regular expressions that rely on advanced features like `(?<=...)` (lookbehind) or backreferences (`\1`) will fail with the `regex` engine.
634 //!
635 //! # Custom Keywords
636 //!
637 //! `jsonschema` allows you to extend its functionality by implementing custom validation logic through custom keywords.
638 //! This feature is particularly useful when you need to validate against domain-specific rules that aren't covered by the standard JSON Schema keywords.
639 //!
640 //! To implement a custom keyword, you need to:
641 //! 1. Create a struct that implements the [`Keyword`] trait
642 //! 2. Create a factory function or closure that produces instances of your custom keyword
643 //! 3. Register the custom keyword with the [`Validator`] instance using the [`ValidationOptions::with_keyword`] method
644 //!
645 //! Here's a complete example:
646 //!
647 //! ```rust
648 //! use jsonschema::{
649 //! paths::{LazyLocation, Location},
650 //! Keyword, ValidationError,
651 //! };
652 //! use serde_json::{json, Map, Value};
653 //! use std::iter::once;
654 //!
655 //! // Step 1: Implement the Keyword trait
656 //! struct EvenNumberValidator;
657 //!
658 //! impl Keyword for EvenNumberValidator {
659 //! fn validate<'i>(
660 //! &self,
661 //! instance: &'i Value,
662 //! location: &LazyLocation,
663 //! ) -> Result<(), ValidationError<'i>> {
664 //! if let Value::Number(n) = instance {
665 //! if n.as_u64().map_or(false, |n| n % 2 == 0) {
666 //! Ok(())
667 //! } else {
668 //! return Err(ValidationError::custom(
669 //! Location::new(),
670 //! location.into(),
671 //! instance,
672 //! "Number must be even",
673 //! ));
674 //! }
675 //! } else {
676 //! Err(ValidationError::custom(
677 //! Location::new(),
678 //! location.into(),
679 //! instance,
680 //! "Value must be a number",
681 //! ))
682 //! }
683 //! }
684 //!
685 //! fn is_valid(&self, instance: &Value) -> bool {
686 //! instance.as_u64().map_or(false, |n| n % 2 == 0)
687 //! }
688 //! }
689 //!
690 //! // Step 2: Create a factory function
691 //! fn even_number_validator_factory<'a>(
692 //! _parent: &'a Map<String, Value>,
693 //! value: &'a Value,
694 //! path: Location,
695 //! ) -> Result<Box<dyn Keyword>, ValidationError<'a>> {
696 //! // You can use the `value` parameter to configure your validator if needed
697 //! if value.as_bool() == Some(true) {
698 //! Ok(Box::new(EvenNumberValidator))
699 //! } else {
700 //! Err(ValidationError::custom(
701 //! Location::new(),
702 //! path,
703 //! value,
704 //! "The 'even-number' keyword must be set to true",
705 //! ))
706 //! }
707 //! }
708 //!
709 //! // Step 3: Use the custom keyword
710 //! fn main() -> Result<(), Box<dyn std::error::Error>> {
711 //! let schema = json!({"even-number": true, "type": "integer"});
712 //! let validator = jsonschema::options()
713 //! .with_keyword("even-number", even_number_validator_factory)
714 //! .build(&schema)?;
715 //!
716 //! assert!(validator.is_valid(&json!(2)));
717 //! assert!(!validator.is_valid(&json!(3)));
718 //! assert!(!validator.is_valid(&json!("not a number")));
719 //!
720 //! Ok(())
721 //! }
722 //! ```
723 //!
724 //! In this example, we've created a custom `even-number` keyword that validates whether a number is even.
725 //! The `EvenNumberValidator` implements the actual validation logic, while the `even_number_validator_factory`
726 //! creates instances of the validator and allows for additional configuration based on the keyword's value in the schema.
727 //!
728 //! You can also use a closure instead of a factory function for simpler cases:
729 //!
730 //! ```rust
731 //! # use jsonschema::{
732 //! # paths::LazyLocation,
733 //! # Keyword, ValidationError,
734 //! # };
735 //! # use serde_json::{json, Map, Value};
736 //! # use std::iter::once;
737 //! #
738 //! # struct EvenNumberValidator;
739 //! #
740 //! # impl Keyword for EvenNumberValidator {
741 //! # fn validate<'i>(
742 //! # &self,
743 //! # instance: &'i Value,
744 //! # location: &LazyLocation,
745 //! # ) -> Result<(), ValidationError<'i>> {
746 //! # Ok(())
747 //! # }
748 //! #
749 //! # fn is_valid(&self, instance: &Value) -> bool {
750 //! # true
751 //! # }
752 //! # }
753 //! # fn main() -> Result<(), Box<dyn std::error::Error>> {
754 //! let schema = json!({"even-number": true, "type": "integer"});
755 //! let validator = jsonschema::options()
756 //! .with_keyword("even-number", |_, _, _| {
757 //! Ok(Box::new(EvenNumberValidator))
758 //! })
759 //! .build(&schema)?;
760 //! # Ok(())
761 //! # }
762 //! ```
763 //!
764 //! # Custom Formats
765 //!
766 //! JSON Schema allows for format validation through the `format` keyword. While `jsonschema`
767 //! provides built-in validators for standard formats, you can also define custom format validators
768 //! for domain-specific string formats.
769 //!
770 //! To implement a custom format validator:
771 //!
772 //! 1. Define a function or a closure that takes a `&str` and returns a `bool`.
773 //! 2. Register the function with `jsonschema::options().with_format()`.
774 //!
775 //! ```rust
776 //! use serde_json::json;
777 //!
778 //! // Step 1: Define the custom format validator function
779 //! fn ends_with_42(s: &str) -> bool {
780 //! s.ends_with("42!")
781 //! }
782 //!
783 //! # fn main() -> Result<(), Box<dyn std::error::Error>> {
784 //! // Step 2: Create a schema using the custom format
785 //! let schema = json!({
786 //! "type": "string",
787 //! "format": "ends-with-42"
788 //! });
789 //!
790 //! // Step 3: Build the validator with the custom format
791 //! let validator = jsonschema::options()
792 //! .with_format("ends-with-42", ends_with_42)
793 //! .with_format("ends-with-43", |s| s.ends_with("43!"))
794 //! .should_validate_formats(true)
795 //! .build(&schema)?;
796 //!
797 //! // Step 4: Validate instances
798 //! assert!(validator.is_valid(&json!("Hello42!")));
799 //! assert!(!validator.is_valid(&json!("Hello43!")));
800 //! assert!(!validator.is_valid(&json!(42))); // Not a string
801 //! # Ok(())
802 //! # }
803 //! ```
804 //!
805 //! ### Notes on Custom Format Validators
806 //!
807 //! - Custom format validators are only called for string instances.
808 //! - In newer drafts, `format` is purely an annotation and won’t do any checking unless you
809 //! opt in by calling `.should_validate_formats(true)` on your options builder. If you omit
810 //! it, all `format` keywords are ignored at validation time.
811 //!
812 //! # Arbitrary Precision Numbers
813 //!
814 //! Enable the `arbitrary-precision` feature for exact validation of numbers beyond standard numeric ranges:
815 //!
816 //! ```toml
817 //! jsonschema = { version = "x.y.z", features = ["arbitrary-precision"] }
818 //! ```
819 //!
820 //! This provides:
821 //! - Arbitrarily large integers (e.g., `18446744073709551616`)
822 //! - Exact decimal precision without `f64` rounding (e.g., `0.1`, `0.3`)
823 //!
824 //! **Important**: Precision is only preserved when parsing JSON from strings. Using Rust literals
825 //! or the `json!()` macro converts numbers to `f64`, losing precision.
826 //!
827 //! ```rust
828 //! # use jsonschema::Validator;
829 //! // Precision preserved - parsed from JSON string
830 //! let schema = serde_json::from_str(r#"{"minimum": 0.1}"#)?;
831 //! let instance = serde_json::from_str("0.3")?;
832 //! let validator = Validator::new(&schema)?;
833 //! assert!(validator.is_valid(&instance));
834 //! # Ok::<(), Box<dyn std::error::Error>>(())
835 //! ```
836 //!
837 //! # WebAssembly support
838 //!
839 //! `jsonschema` supports WebAssembly with different capabilities based on the target platform:
840 //!
841 //! ## Browser/JavaScript (`wasm32-unknown-unknown`)
842 //!
843 //! When targeting browser or JavaScript environments, external reference resolution is not
844 //! supported by default due to platform limitations:
845 //! - No filesystem access (`resolve-file` feature is not available)
846 //! - No synchronous HTTP requests (`resolve-http` feature is not available)
847 //!
848 //! To use `jsonschema` in these environments, disable default features:
849 //!
850 //! ```toml
851 //! jsonschema = { version = "x.y.z", default-features = false }
852 //! ```
853 //!
854 //! Note: Attempting to compile with `resolve-http` or `resolve-file` features on
855 //! `wasm32-unknown-unknown` will result in a compile error.
856 //!
857 //! For external references in browser environments, implement a custom retriever that uses
858 //! browser APIs (like `fetch`). See the [External References](#external-references) section.
859 //!
860 //! ## WASI (`wasm32-wasip1` / `wasm32-wasip2`)
861 //!
862 //! WASI environments (preview 1 and preview 2) can compile schemas and run validators, but the bundled
863 //! HTTP retriever depends on `reqwest`’s blocking client, which isn't available on these targets. Use
864 //! file access and custom retrievers instead.
865 //!
866 //! **Supported:**
867 //! - Blocking file resolution (`resolve-file` feature)
868 //! - Custom blocking retrievers (including wrapping async operations)
869 //! - Custom async retrievers via the `resolve-async` feature (for example, `jsonschema::async_options`
870 //! together with your own async runtime)
871 //!
872 //! **Not Supported:**
873 //! - The bundled HTTP retriever (depends on `reqwest`’s blocking client)
874 //!
875 //! ```toml
876 //! jsonschema = { version = "x.y.z", default-features = false, features = ["resolve-file"] }
877 //! ```
878 //!
879 //! **Workaround for HTTP:** Implement a custom blocking or async [`Retrieve`] that uses your preferred
880 //! HTTP client, and enable `resolve-async` if you want to build validators through `async_options()`
881 //! on WASI.
882
883 #[cfg(all(
884 target_arch = "wasm32",
885 target_os = "unknown",
886 any(feature = "resolve-file", feature = "resolve-http")
887 ))]
888 compile_error!(
889 "Features 'resolve-http' and 'resolve-file' are not supported on wasm32-unknown-unknown"
890 );
891
892 pub(crate) mod compiler;
893 mod content_encoding;
894 mod content_media_type;
895 mod ecma;
896 pub mod error;
897 mod evaluation;
898 #[doc(hidden)]
899 pub mod ext;
900 mod keywords;
901 mod node;
902 mod options;
903 pub mod output;
904 pub mod paths;
905 pub(crate) mod properties;
906 pub(crate) mod regex;
907 mod retriever;
908 pub(crate) mod thread;
909 pub mod types;
910 mod validator;
911
912 pub use error::{ErrorIterator, MaskedValidationError, ValidationError, ValidationErrors};
913 pub use evaluation::{
914 AnnotationEntry, ErrorEntry, Evaluation, FlagOutput, HierarchicalOutput, ListOutput,
915 };
916 pub use keywords::custom::Keyword;
917 pub use options::{FancyRegex, PatternOptions, Regex, ValidationOptions};
918 pub use referencing::{
919 Draft, Error as ReferencingError, Registry, RegistryOptions, Resource, Retrieve, Uri,
920 };
921 pub use types::{JsonType, JsonTypeSet, JsonTypeSetIterator};
922 pub use validator::Validator;
923
924 #[cfg(feature = "resolve-async")]
925 pub use referencing::AsyncRetrieve;
926
927 use serde_json::Value;
928
929 /// Validate `instance` against `schema` and get a `true` if the instance is valid and `false`
930 /// otherwise. Draft is detected automatically.
931 ///
932 /// # Examples
933 ///
934 /// ```rust
935 /// use serde_json::json;
936 ///
937 /// let schema = json!({"maxLength": 5});
938 /// let instance = json!("foo");
939 /// assert!(jsonschema::is_valid(&schema, &instance));
940 /// ```
941 ///
942 /// # Panics
943 ///
944 /// This function panics if an invalid schema is passed.
945 #[must_use]
946 #[inline]
947 pub fn is_valid(schema: &Value, instance: &Value) -> bool {
948 validator_for(schema)
949 .expect("Invalid schema")
950 .is_valid(instance)
951 }
952
953 /// Validate `instance` against `schema` and return the first error if any. Draft is detected automatically.
954 ///
955 /// # Examples
956 ///
957 /// ```rust
958 /// use serde_json::json;
959 ///
960 /// let schema = json!({"maxLength": 5});
961 /// let instance = json!("foo");
962 /// assert!(jsonschema::validate(&schema, &instance).is_ok());
963 /// ```
964 ///
965 /// # Errors
966 ///
967 /// Returns the first [`ValidationError`] encountered when `instance` violates `schema`.
968 ///
969 /// # Panics
970 ///
971 /// This function panics if an invalid schema is passed.
972 #[inline]
973 pub fn validate<'i>(schema: &Value, instance: &'i Value) -> Result<(), ValidationError<'i>> {
974 validator_for(schema)
975 .expect("Invalid schema")
976 .validate(instance)
977 }
978
979 /// Evaluate `instance` against `schema` and return structured validation output. Draft is detected automatically.
980 ///
981 /// Returns an [`Evaluation`] containing detailed validation results in JSON Schema Output v1 format,
982 /// including annotations and errors across the entire validation tree.
983 ///
984 /// # Examples
985 ///
986 /// ```rust
987 /// use serde_json::json;
988 ///
989 /// let schema = json!({"type": "string", "minLength": 3});
990 /// let instance = json!("foo");
991 /// let evaluation = jsonschema::evaluate(&schema, &instance);
992 /// assert!(evaluation.flag().valid);
993 /// ```
994 ///
995 /// # Panics
996 ///
997 /// This function panics if an invalid schema is passed.
998 #[must_use]
999 #[inline]
1000 pub fn evaluate(schema: &Value, instance: &Value) -> Evaluation {
1001 validator_for(schema)
1002 .expect("Invalid schema")
1003 .evaluate(instance)
1004 }
1005
1006 /// Create a validator for the input schema with automatic draft detection and default options.
1007 ///
1008 /// # Examples
1009 ///
1010 /// ```rust
1011 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
1012 /// use serde_json::json;
1013 ///
1014 /// let schema = json!({"minimum": 5});
1015 /// let instance = json!(42);
1016 ///
1017 /// let validator = jsonschema::validator_for(&schema)?;
1018 /// assert!(validator.is_valid(&instance));
1019 /// # Ok(())
1020 /// # }
1021 /// ```
1022 ///
1023 /// # Errors
1024 ///
1025 /// Returns an error if the schema is invalid or external references cannot be resolved.
1026 pub fn validator_for(schema: &Value) -> Result<Validator, ValidationError<'static>> {
1027 Validator::new(schema)
1028 }
1029
1030 /// Create a validator for the input schema with automatic draft detection and default options,
1031 /// using non-blocking retrieval for external references.
1032 ///
1033 /// This is the async counterpart to [`validator_for`]. Note that only the construction is
1034 /// asynchronous - validation itself is always synchronous.
1035 ///
1036 /// # Examples
1037 ///
1038 /// ```rust
1039 /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
1040 /// use serde_json::json;
1041 ///
1042 /// let schema = json!({
1043 /// "type": "object",
1044 /// "properties": {
1045 /// "user": { "$ref": "https://example.com/user.json" }
1046 /// }
1047 /// });
1048 ///
1049 /// let validator = jsonschema::async_validator_for(&schema).await?;
1050 /// assert!(validator.is_valid(&json!({"user": {"name": "Alice"}})));
1051 /// # Ok(())
1052 /// # }
1053 /// ```
1054 ///
1055 /// # Errors
1056 ///
1057 /// Returns an error if the schema is invalid or external references cannot be resolved.
1058 #[cfg(feature = "resolve-async")]
1059 pub async fn async_validator_for(schema: &Value) -> Result<Validator, ValidationError<'static>> {
1060 Validator::async_new(schema).await
1061 }
1062
1063 /// Create a builder for configuring JSON Schema validation options.
1064 ///
1065 /// This function returns a [`ValidationOptions`] struct, which allows you to set various
1066 /// options for JSON Schema validation. You can use this builder to specify
1067 /// the draft version, set custom formats, and more.
1068 ///
1069 /// # Examples
1070 ///
1071 /// Basic usage with draft specification:
1072 ///
1073 /// ```
1074 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
1075 /// use serde_json::json;
1076 /// use jsonschema::Draft;
1077 ///
1078 /// let schema = json!({"type": "string"});
1079 /// let validator = jsonschema::options()
1080 /// .with_draft(Draft::Draft7)
1081 /// .build(&schema)?;
1082 ///
1083 /// assert!(validator.is_valid(&json!("Hello")));
1084 /// # Ok(())
1085 /// # }
1086 /// ```
1087 ///
1088 /// Advanced configuration:
1089 ///
1090 /// ```
1091 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
1092 /// use serde_json::json;
1093 ///
1094 /// let schema = json!({"type": "string", "format": "custom"});
1095 /// let validator = jsonschema::options()
1096 /// .with_format("custom", |value| value.len() == 3)
1097 /// .should_validate_formats(true)
1098 /// .build(&schema)?;
1099 ///
1100 /// assert!(validator.is_valid(&json!("abc")));
1101 /// assert!(!validator.is_valid(&json!("abcd")));
1102 /// # Ok(())
1103 /// # }
1104 /// ```
1105 ///
1106 /// See [`ValidationOptions`] for all available configuration options.
1107 #[must_use]
1108 pub fn options() -> ValidationOptions {
1109 Validator::options()
1110 }
1111
1112 /// Create a builder for configuring JSON Schema validation options.
1113 ///
1114 /// This function returns a [`ValidationOptions`] struct which allows you to set various options for JSON Schema validation.
1115 /// External references will be retrieved using non-blocking I/O.
1116 ///
1117 /// # Examples
1118 ///
1119 /// Basic usage with external references:
1120 ///
1121 /// ```rust
1122 /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
1123 /// use serde_json::json;
1124 ///
1125 /// let schema = json!({
1126 /// "$ref": "https://example.com/user.json"
1127 /// });
1128 ///
1129 /// let validator = jsonschema::async_options()
1130 /// .build(&schema)
1131 /// .await?;
1132 ///
1133 /// assert!(validator.is_valid(&json!({"name": "Alice"})));
1134 /// # Ok(())
1135 /// # }
1136 /// ```
1137 ///
1138 /// Advanced configuration:
1139 ///
1140 /// ```rust
1141 /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
1142 /// use serde_json::{Value, json};
1143 /// use jsonschema::{Draft, AsyncRetrieve, Uri};
1144 ///
1145 /// // Custom async retriever
1146 /// struct MyRetriever;
1147 ///
1148 /// #[cfg_attr(target_family = "wasm", async_trait::async_trait(?Send))]
1149 /// #[cfg_attr(not(target_family = "wasm"), async_trait::async_trait)]
1150 /// impl AsyncRetrieve for MyRetriever {
1151 /// async fn retrieve(&self, uri: &Uri<String>) -> Result<Value, Box<dyn std::error::Error + Send + Sync>> {
1152 /// // Custom retrieval logic
1153 /// Ok(json!({}))
1154 /// }
1155 /// }
1156 ///
1157 /// let schema = json!({
1158 /// "$ref": "https://example.com/user.json"
1159 /// });
1160 /// let validator = jsonschema::async_options()
1161 /// .with_draft(Draft::Draft202012)
1162 /// .with_retriever(MyRetriever)
1163 /// .build(&schema)
1164 /// .await?;
1165 /// # Ok(())
1166 /// # }
1167 /// ```
1168 ///
1169 /// On `wasm32` targets, annotate your implementation with `async_trait::async_trait(?Send)` to drop the `Send + Sync` requirement.
1170 ///
1171 /// See [`ValidationOptions`] for all available configuration options.
1172 #[cfg(feature = "resolve-async")]
1173 #[must_use]
1174 pub fn async_options() -> ValidationOptions<std::sync::Arc<dyn AsyncRetrieve>> {
1175 Validator::async_options()
1176 }
1177
1178 /// Functionality for validating JSON Schema documents against their meta-schemas.
1179 pub mod meta {
1180 use crate::{error::ValidationError, Draft};
1181 use ahash::AHashSet;
1182 use referencing::{Registry, Retrieve};
1183 use serde_json::Value;
1184
1185 pub use validator_handle::MetaValidator;
1186
1187 /// Create a meta-validation options builder.
1188 ///
1189 /// # Examples
1190 ///
1191 /// ```rust
1192 /// use serde_json::json;
1193 /// use jsonschema::{Registry, Resource};
1194 ///
1195 /// let custom_meta = Resource::from_contents(json!({
1196 /// "$schema": "https://json-schema.org/draft/2020-12/schema",
1197 /// "type": "object"
1198 /// }));
1199 ///
1200 /// let registry = Registry::try_new(
1201 /// "http://example.com/meta",
1202 /// custom_meta
1203 /// ).unwrap();
1204 ///
1205 /// let schema = json!({
1206 /// "$schema": "http://example.com/meta",
1207 /// "type": "string"
1208 /// });
1209 ///
1210 /// assert!(jsonschema::meta::options()
1211 /// .with_registry(registry)
1212 /// .is_valid(&schema));
1213 /// ```
1214 #[must_use]
1215 pub fn options() -> MetaSchemaOptions {
1216 MetaSchemaOptions::default()
1217 }
1218
1219 /// Options for meta-schema validation.
1220 #[derive(Clone, Default)]
1221 pub struct MetaSchemaOptions {
1222 registry: Option<Registry>,
1223 }
1224
1225 impl MetaSchemaOptions {
1226 /// Use a registry for resolving custom meta-schemas.
1227 ///
1228 /// # Examples
1229 ///
1230 /// ```rust
1231 /// use serde_json::json;
1232 /// use jsonschema::{Registry, Resource};
1233 ///
1234 /// let custom_meta = Resource::from_contents(json!({
1235 /// "$schema": "https://json-schema.org/draft/2020-12/schema",
1236 /// "type": "object"
1237 /// }));
1238 ///
1239 /// let registry = Registry::try_new(
1240 /// "http://example.com/meta",
1241 /// custom_meta
1242 /// ).unwrap();
1243 ///
1244 /// let options = jsonschema::meta::options()
1245 /// .with_registry(registry);
1246 /// ```
1247 #[must_use]
1248 pub fn with_registry(mut self, registry: Registry) -> Self {
1249 self.registry = Some(registry);
1250 self
1251 }
1252
1253 /// Check if a schema is valid according to its meta-schema.
1254 ///
1255 /// # Panics
1256 ///
1257 /// Panics if the meta-schema cannot be resolved.
1258 #[must_use]
1259 pub fn is_valid(&self, schema: &Value) -> bool {
1260 match try_meta_validator_for(schema, self.registry.as_ref()) {
1261 Ok(validator) => validator.as_ref().is_valid(schema),
1262 Err(e) => panic!("Failed to resolve meta-schema: {e}"),
1263 }
1264 }
1265
1266 /// Validate a schema according to its meta-schema.
1267 ///
1268 /// # Errors
1269 ///
1270 /// Returns [`ValidationError`] if the schema is invalid or if the meta-schema cannot be resolved.
1271 pub fn validate<'a>(&self, schema: &'a Value) -> Result<(), ValidationError<'a>> {
1272 let validator = try_meta_validator_for(schema, self.registry.as_ref())?;
1273 validator.as_ref().validate(schema)
1274 }
1275 }
1276
1277 mod validator_handle {
1278 use crate::Validator;
1279 use std::{marker::PhantomData, ops::Deref};
1280
1281 /// Handle to a draft-specific meta-schema [`Validator`]. Borrows cached validators on native
1282 /// targets and owns validators on `wasm32`.
1283 pub struct MetaValidator<'a>(MetaValidatorInner<'a>);
1284
1285 // Native builds can hand out references to cached validators or own dynamic ones,
1286 // while wasm targets need owned instances because the validator type does not implement `Sync` there.
1287 enum MetaValidatorInner<'a> {
1288 #[cfg(not(target_family = "wasm"))]
1289 Borrowed(&'a Validator),
1290 Owned(Box<Validator>, PhantomData<&'a Validator>),
1291 }
1292
1293 #[cfg_attr(target_family = "wasm", allow(clippy::elidable_lifetime_names))]
1294 impl<'a> MetaValidator<'a> {
1295 #[cfg(not(target_family = "wasm"))]
1296 pub(crate) fn borrowed(validator: &'a Validator) -> Self {
1297 Self(MetaValidatorInner::Borrowed(validator))
1298 }
1299
1300 pub(crate) fn owned(validator: Validator) -> Self {
1301 Self(MetaValidatorInner::Owned(Box::new(validator), PhantomData))
1302 }
1303 }
1304
1305 impl AsRef<Validator> for MetaValidator<'_> {
1306 fn as_ref(&self) -> &Validator {
1307 match &self.0 {
1308 #[cfg(not(target_family = "wasm"))]
1309 MetaValidatorInner::Borrowed(validator) => validator,
1310 MetaValidatorInner::Owned(validator, _) => validator,
1311 }
1312 }
1313 }
1314
1315 impl Deref for MetaValidator<'_> {
1316 type Target = Validator;
1317
1318 fn deref(&self) -> &Self::Target {
1319 self.as_ref()
1320 }
1321 }
1322 }
1323
1324 pub(crate) mod validators {
1325 use crate::Validator;
1326 #[cfg(not(target_family = "wasm"))]
1327 use std::sync::LazyLock;
1328
1329 fn build_validator(schema: &serde_json::Value) -> Validator {
1330 crate::options()
1331 .without_schema_validation()
1332 .build(schema)
1333 .expect("Meta-schema should be valid")
1334 }
1335
1336 #[cfg(not(target_family = "wasm"))]
1337 pub(crate) static DRAFT4_META_VALIDATOR: LazyLock<Validator> =
1338 LazyLock::new(|| build_validator(&referencing::meta::DRAFT4));
1339 #[cfg(target_family = "wasm")]
1340 pub(crate) fn draft4_meta_validator() -> Validator {
1341 build_validator(&referencing::meta::DRAFT4)
1342 }
1343
1344 #[cfg(not(target_family = "wasm"))]
1345 pub(crate) static DRAFT6_META_VALIDATOR: LazyLock<Validator> =
1346 LazyLock::new(|| build_validator(&referencing::meta::DRAFT6));
1347 #[cfg(target_family = "wasm")]
1348 pub(crate) fn draft6_meta_validator() -> Validator {
1349 build_validator(&referencing::meta::DRAFT6)
1350 }
1351
1352 #[cfg(not(target_family = "wasm"))]
1353 pub(crate) static DRAFT7_META_VALIDATOR: LazyLock<Validator> =
1354 LazyLock::new(|| build_validator(&referencing::meta::DRAFT7));
1355 #[cfg(target_family = "wasm")]
1356 pub(crate) fn draft7_meta_validator() -> Validator {
1357 build_validator(&referencing::meta::DRAFT7)
1358 }
1359
1360 #[cfg(not(target_family = "wasm"))]
1361 pub(crate) static DRAFT201909_META_VALIDATOR: LazyLock<Validator> =
1362 LazyLock::new(|| build_validator(&referencing::meta::DRAFT201909));
1363 #[cfg(target_family = "wasm")]
1364 pub(crate) fn draft201909_meta_validator() -> Validator {
1365 build_validator(&referencing::meta::DRAFT201909)
1366 }
1367
1368 #[cfg(not(target_family = "wasm"))]
1369 pub(crate) static DRAFT202012_META_VALIDATOR: LazyLock<Validator> =
1370 LazyLock::new(|| build_validator(&referencing::meta::DRAFT202012));
1371 #[cfg(target_family = "wasm")]
1372 pub(crate) fn draft202012_meta_validator() -> Validator {
1373 build_validator(&referencing::meta::DRAFT202012)
1374 }
1375 }
1376
1377 pub(crate) fn validator_for_draft(draft: Draft) -> MetaValidator<'static> {
1378 #[cfg(not(target_family = "wasm"))]
1379 {
1380 match draft {
1381 Draft::Draft4 => MetaValidator::borrowed(&validators::DRAFT4_META_VALIDATOR),
1382 Draft::Draft6 => MetaValidator::borrowed(&validators::DRAFT6_META_VALIDATOR),
1383 Draft::Draft7 => MetaValidator::borrowed(&validators::DRAFT7_META_VALIDATOR),
1384 Draft::Draft201909 => {
1385 MetaValidator::borrowed(&validators::DRAFT201909_META_VALIDATOR)
1386 }
1387 // Draft202012, Unknown, or any future draft variants
1388 _ => MetaValidator::borrowed(&validators::DRAFT202012_META_VALIDATOR),
1389 }
1390 }
1391 #[cfg(target_family = "wasm")]
1392 {
1393 let validator = match draft {
1394 Draft::Draft4 => validators::draft4_meta_validator(),
1395 Draft::Draft6 => validators::draft6_meta_validator(),
1396 Draft::Draft7 => validators::draft7_meta_validator(),
1397 Draft::Draft201909 => validators::draft201909_meta_validator(),
1398 // Draft202012, Unknown, or any future draft variants
1399 _ => validators::draft202012_meta_validator(),
1400 };
1401 MetaValidator::owned(validator)
1402 }
1403 }
1404
1405 /// Validate a JSON Schema document against its meta-schema and get a `true` if the schema is valid
1406 /// and `false` otherwise. Draft version is detected automatically.
1407 ///
1408 /// # Examples
1409 ///
1410 /// ```rust
1411 /// use serde_json::json;
1412 ///
1413 /// let schema = json!({
1414 /// "type": "string",
1415 /// "maxLength": 5
1416 /// });
1417 /// assert!(jsonschema::meta::is_valid(&schema));
1418 /// ```
1419 ///
1420 /// # Panics
1421 ///
1422 /// This function panics if the meta-schema can't be detected.
1423 ///
1424 /// # Note
1425 ///
1426 /// This helper only works with the built-in JSON Schema drafts. For schemas that declare a
1427 /// custom `$schema`, construct a registry that contains your meta-schema and use
1428 /// [`meta::options().with_registry(...)`](crate::meta::options) to validate it.
1429 #[must_use]
1430 pub fn is_valid(schema: &Value) -> bool {
1431 match try_meta_validator_for(schema, None) {
1432 Ok(validator) => validator.as_ref().is_valid(schema),
1433 Err(error) => panic!("Failed to resolve meta-schema: {error}"),
1434 }
1435 }
1436 /// Validate a JSON Schema document against its meta-schema and return the first error if any.
1437 /// Draft version is detected automatically.
1438 ///
1439 /// # Examples
1440 ///
1441 /// ```rust
1442 /// use serde_json::json;
1443 ///
1444 /// let schema = json!({
1445 /// "type": "string",
1446 /// "maxLength": 5
1447 /// });
1448 /// assert!(jsonschema::meta::validate(&schema).is_ok());
1449 ///
1450 /// // Invalid schema
1451 /// let invalid_schema = json!({
1452 /// "type": "invalid_type"
1453 /// });
1454 /// assert!(jsonschema::meta::validate(&invalid_schema).is_err());
1455 /// ```
1456 ///
1457 /// # Errors
1458 ///
1459 /// Returns the first [`ValidationError`] describing why the schema violates the detected meta-schema.
1460 ///
1461 /// # Panics
1462 ///
1463 /// This function panics if the meta-schema can't be detected.
1464 ///
1465 /// # Note
1466 ///
1467 /// Like [`is_valid`], this helper only handles the bundled JSON
1468 /// Schema drafts. For custom meta-schemas, use [`meta::options().with_registry(...)`](crate::meta::options)
1469 /// so the registry can supply the meta-schema.
1470 pub fn validate(schema: &Value) -> Result<(), ValidationError<'_>> {
1471 let validator = try_meta_validator_for(schema, None)?;
1472 validator.as_ref().validate(schema)
1473 }
1474
1475 /// Build a validator for a JSON Schema's meta-schema.
1476 /// Draft version is detected automatically.
1477 ///
1478 /// Returns a [`MetaValidator`] that can be used to validate the schema or access
1479 /// structured validation output via the evaluate API.
1480 ///
1481 /// # Examples
1482 ///
1483 /// ```rust
1484 /// use serde_json::json;
1485 ///
1486 /// let schema = json!({
1487 /// "type": "string",
1488 /// "maxLength": 5
1489 /// });
1490 ///
1491 /// let validator = jsonschema::meta::validator_for(&schema)
1492 /// .expect("Valid meta-schema");
1493 ///
1494 /// // Use evaluate API for structured output
1495 /// let evaluation = validator.evaluate(&schema);
1496 /// assert!(evaluation.flag().valid);
1497 /// ```
1498 ///
1499 /// # Errors
1500 ///
1501 /// Returns [`ValidationError`] if the meta-schema cannot be resolved or built.
1502 ///
1503 /// # Panics
1504 ///
1505 /// This function panics if the meta-schema can't be detected.
1506 ///
1507 /// # Note
1508 ///
1509 /// This helper only handles the bundled JSON Schema drafts. For custom meta-schemas,
1510 /// use [`meta::options().with_registry(...)`](crate::meta::options).
1511 pub fn validator_for(
1512 schema: &Value,
1513 ) -> Result<MetaValidator<'static>, ValidationError<'static>> {
1514 try_meta_validator_for(schema, None)
1515 }
1516
1517 fn try_meta_validator_for<'a>(
1518 schema: &Value,
1519 registry: Option<&Registry>,
1520 ) -> Result<MetaValidator<'a>, ValidationError<'static>> {
1521 let draft = Draft::default().detect(schema);
1522
1523 // For custom meta-schemas (Draft::Unknown), attempt to resolve the meta-schema
1524 if draft == Draft::Unknown {
1525 if let Some(meta_schema_uri) = schema
1526 .as_object()
1527 .and_then(|obj| obj.get("$schema"))
1528 .and_then(|s| s.as_str())
1529 {
1530 // Try registry first if available
1531 if let Some(registry) = registry {
1532 let (custom_meta_schema, resolved_draft) =
1533 resolve_meta_schema_with_registry(meta_schema_uri, registry)?;
1534 let validator = crate::options()
1535 .with_draft(resolved_draft)
1536 .with_registry(registry.clone())
1537 .without_schema_validation()
1538 .build(&custom_meta_schema)?;
1539 return Ok(MetaValidator::owned(validator));
1540 }
1541
1542 // Use default retriever
1543 let (custom_meta_schema, resolved_draft) =
1544 resolve_meta_schema_chain(meta_schema_uri)?;
1545 let validator = crate::options()
1546 .with_draft(resolved_draft)
1547 .without_schema_validation()
1548 .build(&custom_meta_schema)?;
1549 return Ok(MetaValidator::owned(validator));
1550 }
1551 }
1552
1553 Ok(validator_for_draft(draft))
1554 }
1555
1556 fn resolve_meta_schema_with_registry(
1557 uri: &str,
1558 registry: &Registry,
1559 ) -> Result<(Value, Draft), ValidationError<'static>> {
1560 let resolver = registry.try_resolver(uri)?;
1561 let first_resolved = resolver.lookup("")?;
1562 let first_meta_schema = first_resolved.contents().clone();
1563
1564 let draft = walk_meta_schema_chain(uri, |current_uri| {
1565 let resolver = registry.try_resolver(current_uri)?;
1566 let resolved = resolver.lookup("")?;
1567 Ok(resolved.contents().clone())
1568 })?;
1569
1570 Ok((first_meta_schema, draft))
1571 }
1572
1573 fn resolve_meta_schema_chain(uri: &str) -> Result<(Value, Draft), ValidationError<'static>> {
1574 let retriever = crate::retriever::DefaultRetriever;
1575 let first_meta_uri = referencing::uri::from_str(uri)?;
1576 let first_meta_schema = retriever
1577 .retrieve(&first_meta_uri)
1578 .map_err(|e| referencing::Error::unretrievable(uri, e))?;
1579
1580 let draft = walk_meta_schema_chain(uri, |current_uri| {
1581 let meta_uri = referencing::uri::from_str(current_uri)?;
1582 Ok(retriever
1583 .retrieve(&meta_uri)
1584 .map_err(|e| referencing::Error::unretrievable(current_uri, e))?)
1585 })?;
1586
1587 Ok((first_meta_schema, draft))
1588 }
1589
1590 pub(crate) fn walk_meta_schema_chain(
1591 start_uri: &str,
1592 mut fetch: impl FnMut(&str) -> Result<Value, ValidationError<'static>>,
1593 ) -> Result<Draft, ValidationError<'static>> {
1594 let mut visited = AHashSet::new();
1595 let mut current_uri = start_uri.to_string();
1596
1597 loop {
1598 if !visited.insert(current_uri.clone()) {
1599 return Err(referencing::Error::circular_metaschema(current_uri).into());
1600 }
1601
1602 let meta_schema = fetch(&current_uri)?;
1603 let draft = Draft::default().detect(&meta_schema);
1604
1605 if draft != Draft::Unknown {
1606 return Ok(draft);
1607 }
1608
1609 current_uri = meta_schema
1610 .get("$schema")
1611 .and_then(|s| s.as_str())
1612 .expect("`$schema` must exist when draft is Unknown")
1613 .to_string();
1614 }
1615 }
1616 }
1617
1618 /// Functionality specific to JSON Schema Draft 4.
1619 ///
1620 /// [![Draft 4](https://img.shields.io/endpoint?url=https%3A%2F%2Fbowtie.report%2Fbadges%2Frust-jsonschema%2Fcompliance%2Fdraft4.json)](https://bowtie.report/#/implementations/rust-jsonschema)
1621 ///
1622 /// This module provides functions for creating validators and performing validation
1623 /// according to the JSON Schema Draft 4 specification.
1624 ///
1625 /// # Examples
1626 ///
1627 /// ```rust
1628 /// use serde_json::json;
1629 ///
1630 /// let schema = json!({"type": "number", "multipleOf": 2});
1631 /// let instance = json!(4);
1632 ///
1633 /// assert!(jsonschema::draft4::is_valid(&schema, &instance));
1634 /// ```
1635 pub mod draft4 {
1636 use super::{Draft, ValidationError, ValidationOptions, Validator, Value};
1637
1638 /// Create a new JSON Schema validator using Draft 4 specifications.
1639 ///
1640 /// # Examples
1641 ///
1642 /// ```rust
1643 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
1644 /// use serde_json::json;
1645 ///
1646 /// let schema = json!({"minimum": 5});
1647 /// let instance = json!(42);
1648 ///
1649 /// let validator = jsonschema::draft4::new(&schema)?;
1650 /// assert!(validator.is_valid(&instance));
1651 /// # Ok(())
1652 /// # }
1653 /// ```
1654 ///
1655 /// # Errors
1656 ///
1657 /// Returns an error if the schema is not a valid Draft 4 document or if referenced resources
1658 /// cannot be resolved.
1659 pub fn new(schema: &Value) -> Result<Validator, ValidationError<'static>> {
1660 options().build(schema)
1661 }
1662 /// Validate an instance against a schema using Draft 4 specifications without creating a validator.
1663 ///
1664 /// # Examples
1665 ///
1666 /// ```rust
1667 /// use serde_json::json;
1668 ///
1669 /// let schema = json!({"minimum": 5});
1670 /// let valid = json!(42);
1671 /// let invalid = json!(3);
1672 ///
1673 /// assert!(jsonschema::draft4::is_valid(&schema, &valid));
1674 /// assert!(!jsonschema::draft4::is_valid(&schema, &invalid));
1675 /// ```
1676 ///
1677 /// # Panics
1678 ///
1679 /// Panics if `schema` cannot be compiled into a Draft 4 validator.
1680 #[must_use]
1681 pub fn is_valid(schema: &Value, instance: &Value) -> bool {
1682 new(schema).expect("Invalid schema").is_valid(instance)
1683 }
1684 /// Validate an instance against a schema using Draft 4 specifications without creating a validator.
1685 ///
1686 /// # Examples
1687 ///
1688 /// ```rust
1689 /// use serde_json::json;
1690 ///
1691 /// let schema = json!({"minimum": 5});
1692 /// let valid = json!(42);
1693 /// let invalid = json!(3);
1694 ///
1695 /// assert!(jsonschema::draft4::validate(&schema, &valid).is_ok());
1696 /// assert!(jsonschema::draft4::validate(&schema, &invalid).is_err());
1697 /// ```
1698 ///
1699 /// # Errors
1700 ///
1701 /// Returns the first [`ValidationError`] when `instance` violates the schema.
1702 ///
1703 /// # Panics
1704 ///
1705 /// Panics if `schema` cannot be compiled into a Draft 4 validator.
1706 pub fn validate<'i>(schema: &Value, instance: &'i Value) -> Result<(), ValidationError<'i>> {
1707 new(schema).expect("Invalid schema").validate(instance)
1708 }
1709 /// Creates a [`ValidationOptions`] builder pre-configured for JSON Schema Draft 4.
1710 ///
1711 /// This function provides a shorthand for `jsonschema::options().with_draft(Draft::Draft4)`.
1712 ///
1713 /// # Examples
1714 ///
1715 /// ```
1716 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
1717 /// use serde_json::json;
1718 ///
1719 /// let schema = json!({"type": "string", "format": "ends-with-42"});
1720 /// let validator = jsonschema::draft4::options()
1721 /// .with_format("ends-with-42", |s| s.ends_with("42"))
1722 /// .should_validate_formats(true)
1723 /// .build(&schema)?;
1724 ///
1725 /// assert!(validator.is_valid(&json!("Hello 42")));
1726 /// assert!(!validator.is_valid(&json!("No!")));
1727 /// # Ok(())
1728 /// # }
1729 /// ```
1730 ///
1731 /// See [`ValidationOptions`] for all available configuration options.
1732 #[must_use]
1733 pub fn options() -> ValidationOptions {
1734 crate::options().with_draft(Draft::Draft4)
1735 }
1736
1737 /// Functionality for validating JSON Schema Draft 4 documents.
1738 pub mod meta {
1739 use crate::{meta::MetaValidator, ValidationError};
1740 use serde_json::Value;
1741
1742 /// Returns a handle to the Draft 4 meta-schema validator. Native targets borrow cached
1743 /// statics while `wasm32` builds an owned validator.
1744 #[must_use]
1745 pub fn validator() -> MetaValidator<'static> {
1746 crate::meta::validator_for_draft(super::Draft::Draft4)
1747 }
1748
1749 /// Validate a JSON Schema document against Draft 4 meta-schema and get a `true` if the schema is valid
1750 /// and `false` otherwise.
1751 ///
1752 /// # Examples
1753 ///
1754 /// ```rust
1755 /// use serde_json::json;
1756 ///
1757 /// let schema = json!({
1758 /// "type": "string",
1759 /// "maxLength": 5
1760 /// });
1761 /// assert!(jsonschema::draft4::meta::is_valid(&schema));
1762 /// ```
1763 #[must_use]
1764 #[inline]
1765 pub fn is_valid(schema: &Value) -> bool {
1766 validator().as_ref().is_valid(schema)
1767 }
1768
1769 /// Validate a JSON Schema document against Draft 4 meta-schema and return the first error if any.
1770 ///
1771 /// # Examples
1772 ///
1773 /// ```rust
1774 /// use serde_json::json;
1775 ///
1776 /// let schema = json!({
1777 /// "type": "string",
1778 /// "maxLength": 5
1779 /// });
1780 /// assert!(jsonschema::draft4::meta::validate(&schema).is_ok());
1781 ///
1782 /// // Invalid schema
1783 /// let invalid_schema = json!({
1784 /// "type": "invalid_type"
1785 /// });
1786 /// assert!(jsonschema::draft4::meta::validate(&invalid_schema).is_err());
1787 /// ```
1788 ///
1789 /// # Errors
1790 ///
1791 /// Returns the first [`ValidationError`] describing why the schema violates the Draft 4 meta-schema.
1792 #[inline]
1793 pub fn validate(schema: &Value) -> Result<(), ValidationError<'_>> {
1794 validator().as_ref().validate(schema)
1795 }
1796 }
1797 }
1798
1799 /// Functionality specific to JSON Schema Draft 6.
1800 ///
1801 /// [![Draft 6](https://img.shields.io/endpoint?url=https%3A%2F%2Fbowtie.report%2Fbadges%2Frust-jsonschema%2Fcompliance%2Fdraft6.json)](https://bowtie.report/#/implementations/rust-jsonschema)
1802 ///
1803 /// This module provides functions for creating validators and performing validation
1804 /// according to the JSON Schema Draft 6 specification.
1805 ///
1806 /// # Examples
1807 ///
1808 /// ```rust
1809 /// use serde_json::json;
1810 ///
1811 /// let schema = json!({"type": "string", "format": "uri"});
1812 /// let instance = json!("https://www.example.com");
1813 ///
1814 /// assert!(jsonschema::draft6::is_valid(&schema, &instance));
1815 /// ```
1816 pub mod draft6 {
1817 use super::{Draft, ValidationError, ValidationOptions, Validator, Value};
1818
1819 /// Create a new JSON Schema validator using Draft 6 specifications.
1820 ///
1821 /// # Examples
1822 ///
1823 /// ```rust
1824 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
1825 /// use serde_json::json;
1826 ///
1827 /// let schema = json!({"minimum": 5});
1828 /// let instance = json!(42);
1829 ///
1830 /// let validator = jsonschema::draft6::new(&schema)?;
1831 /// assert!(validator.is_valid(&instance));
1832 /// # Ok(())
1833 /// # }
1834 /// ```
1835 ///
1836 /// # Errors
1837 ///
1838 /// Returns an error if the schema is not a valid Draft 6 document or if referenced resources
1839 /// cannot be resolved.
1840 pub fn new(schema: &Value) -> Result<Validator, ValidationError<'static>> {
1841 options().build(schema)
1842 }
1843 /// Validate an instance against a schema using Draft 6 specifications without creating a validator.
1844 ///
1845 /// # Examples
1846 ///
1847 /// ```rust
1848 /// use serde_json::json;
1849 ///
1850 /// let schema = json!({"minimum": 5});
1851 /// let valid = json!(42);
1852 /// let invalid = json!(3);
1853 ///
1854 /// assert!(jsonschema::draft6::is_valid(&schema, &valid));
1855 /// assert!(!jsonschema::draft6::is_valid(&schema, &invalid));
1856 /// ```
1857 ///
1858 /// # Panics
1859 ///
1860 /// Panics if `schema` cannot be compiled into a Draft 6 validator.
1861 #[must_use]
1862 pub fn is_valid(schema: &Value, instance: &Value) -> bool {
1863 new(schema).expect("Invalid schema").is_valid(instance)
1864 }
1865 /// Validate an instance against a schema using Draft 6 specifications without creating a validator.
1866 ///
1867 /// # Examples
1868 ///
1869 /// ```rust
1870 /// use serde_json::json;
1871 ///
1872 /// let schema = json!({"minimum": 5});
1873 /// let valid = json!(42);
1874 /// let invalid = json!(3);
1875 ///
1876 /// assert!(jsonschema::draft6::validate(&schema, &valid).is_ok());
1877 /// assert!(jsonschema::draft6::validate(&schema, &invalid).is_err());
1878 /// ```
1879 ///
1880 /// # Errors
1881 ///
1882 /// Returns the first [`ValidationError`] when `instance` violates the schema.
1883 ///
1884 /// # Panics
1885 ///
1886 /// Panics if `schema` cannot be compiled into a Draft 6 validator.
1887 pub fn validate<'i>(schema: &Value, instance: &'i Value) -> Result<(), ValidationError<'i>> {
1888 new(schema).expect("Invalid schema").validate(instance)
1889 }
1890 /// Creates a [`ValidationOptions`] builder pre-configured for JSON Schema Draft 6.
1891 ///
1892 /// This function provides a shorthand for `jsonschema::options().with_draft(Draft::Draft6)`.
1893 ///
1894 /// # Examples
1895 ///
1896 /// ```
1897 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
1898 /// use serde_json::json;
1899 ///
1900 /// let schema = json!({"type": "string", "format": "ends-with-42"});
1901 /// let validator = jsonschema::draft6::options()
1902 /// .with_format("ends-with-42", |s| s.ends_with("42"))
1903 /// .should_validate_formats(true)
1904 /// .build(&schema)?;
1905 ///
1906 /// assert!(validator.is_valid(&json!("Hello 42")));
1907 /// assert!(!validator.is_valid(&json!("No!")));
1908 /// # Ok(())
1909 /// # }
1910 /// ```
1911 ///
1912 /// See [`ValidationOptions`] for all available configuration options.
1913 #[must_use]
1914 pub fn options() -> ValidationOptions {
1915 crate::options().with_draft(Draft::Draft6)
1916 }
1917
1918 /// Functionality for validating JSON Schema Draft 6 documents.
1919 pub mod meta {
1920 use crate::{meta::MetaValidator, ValidationError};
1921 use serde_json::Value;
1922
1923 /// Returns a handle to the Draft 6 meta-schema validator. Native targets borrow cached
1924 /// statics while `wasm32` builds an owned validator.
1925 #[must_use]
1926 pub fn validator() -> MetaValidator<'static> {
1927 crate::meta::validator_for_draft(super::Draft::Draft6)
1928 }
1929
1930 /// Validate a JSON Schema document against Draft 6 meta-schema and get a `true` if the schema is valid
1931 /// and `false` otherwise.
1932 ///
1933 /// # Examples
1934 ///
1935 /// ```rust
1936 /// use serde_json::json;
1937 ///
1938 /// let schema = json!({
1939 /// "type": "string",
1940 /// "maxLength": 5
1941 /// });
1942 /// assert!(jsonschema::draft6::meta::is_valid(&schema));
1943 /// ```
1944 #[must_use]
1945 #[inline]
1946 pub fn is_valid(schema: &Value) -> bool {
1947 validator().as_ref().is_valid(schema)
1948 }
1949
1950 /// Validate a JSON Schema document against Draft 6 meta-schema and return the first error if any.
1951 ///
1952 /// # Examples
1953 ///
1954 /// ```rust
1955 /// use serde_json::json;
1956 ///
1957 /// let schema = json!({
1958 /// "type": "string",
1959 /// "maxLength": 5
1960 /// });
1961 /// assert!(jsonschema::draft6::meta::validate(&schema).is_ok());
1962 ///
1963 /// // Invalid schema
1964 /// let invalid_schema = json!({
1965 /// "type": "invalid_type"
1966 /// });
1967 /// assert!(jsonschema::draft6::meta::validate(&invalid_schema).is_err());
1968 /// ```
1969 ///
1970 /// # Errors
1971 ///
1972 /// Returns the first [`ValidationError`] describing why the schema violates the Draft 6 meta-schema.
1973 #[inline]
1974 pub fn validate(schema: &Value) -> Result<(), ValidationError<'_>> {
1975 validator().as_ref().validate(schema)
1976 }
1977 }
1978 }
1979
1980 /// Functionality specific to JSON Schema Draft 7.
1981 ///
1982 /// [![Draft 7](https://img.shields.io/endpoint?url=https%3A%2F%2Fbowtie.report%2Fbadges%2Frust-jsonschema%2Fcompliance%2Fdraft7.json)](https://bowtie.report/#/implementations/rust-jsonschema)
1983 ///
1984 /// This module provides functions for creating validators and performing validation
1985 /// according to the JSON Schema Draft 7 specification.
1986 ///
1987 /// # Examples
1988 ///
1989 /// ```rust
1990 /// use serde_json::json;
1991 ///
1992 /// let schema = json!({"type": "string", "pattern": "^[a-zA-Z0-9]+$"});
1993 /// let instance = json!("abc123");
1994 ///
1995 /// assert!(jsonschema::draft7::is_valid(&schema, &instance));
1996 /// ```
1997 pub mod draft7 {
1998 use super::{Draft, ValidationError, ValidationOptions, Validator, Value};
1999
2000 /// Create a new JSON Schema validator using Draft 7 specifications.
2001 ///
2002 /// # Examples
2003 ///
2004 /// ```rust
2005 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
2006 /// use serde_json::json;
2007 ///
2008 /// let schema = json!({"minimum": 5});
2009 /// let instance = json!(42);
2010 ///
2011 /// let validator = jsonschema::draft7::new(&schema)?;
2012 /// assert!(validator.is_valid(&instance));
2013 /// # Ok(())
2014 /// # }
2015 /// ```
2016 ///
2017 /// # Errors
2018 ///
2019 /// Returns an error if the schema is not a valid Draft 7 document or if referenced resources
2020 /// cannot be resolved.
2021 pub fn new(schema: &Value) -> Result<Validator, ValidationError<'static>> {
2022 options().build(schema)
2023 }
2024 /// Validate an instance against a schema using Draft 7 specifications without creating a validator.
2025 ///
2026 /// # Examples
2027 ///
2028 /// ```rust
2029 /// use serde_json::json;
2030 ///
2031 /// let schema = json!({"minimum": 5});
2032 /// let valid = json!(42);
2033 /// let invalid = json!(3);
2034 ///
2035 /// assert!(jsonschema::draft7::is_valid(&schema, &valid));
2036 /// assert!(!jsonschema::draft7::is_valid(&schema, &invalid));
2037 /// ```
2038 ///
2039 /// # Panics
2040 ///
2041 /// Panics if `schema` cannot be compiled into a Draft 7 validator.
2042 #[must_use]
2043 pub fn is_valid(schema: &Value, instance: &Value) -> bool {
2044 new(schema).expect("Invalid schema").is_valid(instance)
2045 }
2046 /// Validate an instance against a schema using Draft 7 specifications without creating a validator.
2047 ///
2048 /// # Examples
2049 ///
2050 /// ```rust
2051 /// use serde_json::json;
2052 ///
2053 /// let schema = json!({"minimum": 5});
2054 /// let valid = json!(42);
2055 /// let invalid = json!(3);
2056 ///
2057 /// assert!(jsonschema::draft7::validate(&schema, &valid).is_ok());
2058 /// assert!(jsonschema::draft7::validate(&schema, &invalid).is_err());
2059 /// ```
2060 ///
2061 /// # Errors
2062 ///
2063 /// Returns the first [`ValidationError`] when `instance` violates the schema.
2064 ///
2065 /// # Panics
2066 ///
2067 /// Panics if `schema` cannot be compiled into a Draft 7 validator.
2068 pub fn validate<'i>(schema: &Value, instance: &'i Value) -> Result<(), ValidationError<'i>> {
2069 new(schema).expect("Invalid schema").validate(instance)
2070 }
2071 /// Creates a [`ValidationOptions`] builder pre-configured for JSON Schema Draft 7.
2072 ///
2073 /// This function provides a shorthand for `jsonschema::options().with_draft(Draft::Draft7)`.
2074 ///
2075 /// # Examples
2076 ///
2077 /// ```
2078 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
2079 /// use serde_json::json;
2080 ///
2081 /// let schema = json!({"type": "string", "format": "ends-with-42"});
2082 /// let validator = jsonschema::draft7::options()
2083 /// .with_format("ends-with-42", |s| s.ends_with("42"))
2084 /// .should_validate_formats(true)
2085 /// .build(&schema)?;
2086 ///
2087 /// assert!(validator.is_valid(&json!("Hello 42")));
2088 /// assert!(!validator.is_valid(&json!("No!")));
2089 /// # Ok(())
2090 /// # }
2091 /// ```
2092 ///
2093 /// See [`ValidationOptions`] for all available configuration options.
2094 #[must_use]
2095 pub fn options() -> ValidationOptions {
2096 crate::options().with_draft(Draft::Draft7)
2097 }
2098
2099 /// Functionality for validating JSON Schema Draft 7 documents.
2100 pub mod meta {
2101 use crate::{meta::MetaValidator, ValidationError};
2102 use serde_json::Value;
2103
2104 /// Returns a handle to the Draft 7 meta-schema validator. Native targets borrow cached
2105 /// statics while `wasm32` builds an owned validator.
2106 #[must_use]
2107 pub fn validator() -> MetaValidator<'static> {
2108 crate::meta::validator_for_draft(super::Draft::Draft7)
2109 }
2110
2111 /// Validate a JSON Schema document against Draft 7 meta-schema and get a `true` if the schema is valid
2112 /// and `false` otherwise.
2113 ///
2114 /// # Examples
2115 ///
2116 /// ```rust
2117 /// use serde_json::json;
2118 ///
2119 /// let schema = json!({
2120 /// "type": "string",
2121 /// "maxLength": 5
2122 /// });
2123 /// assert!(jsonschema::draft7::meta::is_valid(&schema));
2124 /// ```
2125 #[must_use]
2126 #[inline]
2127 pub fn is_valid(schema: &Value) -> bool {
2128 validator().as_ref().is_valid(schema)
2129 }
2130
2131 /// Validate a JSON Schema document against Draft 7 meta-schema and return the first error if any.
2132 ///
2133 /// # Examples
2134 ///
2135 /// ```rust
2136 /// use serde_json::json;
2137 ///
2138 /// let schema = json!({
2139 /// "type": "string",
2140 /// "maxLength": 5
2141 /// });
2142 /// assert!(jsonschema::draft7::meta::validate(&schema).is_ok());
2143 ///
2144 /// // Invalid schema
2145 /// let invalid_schema = json!({
2146 /// "type": "invalid_type"
2147 /// });
2148 /// assert!(jsonschema::draft7::meta::validate(&invalid_schema).is_err());
2149 /// ```
2150 ///
2151 /// # Errors
2152 ///
2153 /// Returns the first [`ValidationError`] describing why the schema violates the Draft 7 meta-schema.
2154 #[inline]
2155 pub fn validate(schema: &Value) -> Result<(), ValidationError<'_>> {
2156 validator().as_ref().validate(schema)
2157 }
2158 }
2159 }
2160
2161 /// Functionality specific to JSON Schema Draft 2019-09.
2162 ///
2163 /// [![Draft 2019-09](https://img.shields.io/endpoint?url=https%3A%2F%2Fbowtie.report%2Fbadges%2Frust-jsonschema%2Fcompliance%2Fdraft2019-09.json)](https://bowtie.report/#/implementations/rust-jsonschema)
2164 ///
2165 /// This module provides functions for creating validators and performing validation
2166 /// according to the JSON Schema Draft 2019-09 specification.
2167 ///
2168 /// # Examples
2169 ///
2170 /// ```rust
2171 /// use serde_json::json;
2172 ///
2173 /// let schema = json!({"type": "array", "minItems": 2, "uniqueItems": true});
2174 /// let instance = json!([1, 2]);
2175 ///
2176 /// assert!(jsonschema::draft201909::is_valid(&schema, &instance));
2177 /// ```
2178 pub mod draft201909 {
2179 use super::{Draft, ValidationError, ValidationOptions, Validator, Value};
2180
2181 /// Create a new JSON Schema validator using Draft 2019-09 specifications.
2182 ///
2183 /// # Examples
2184 ///
2185 /// ```rust
2186 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
2187 /// use serde_json::json;
2188 ///
2189 /// let schema = json!({"minimum": 5});
2190 /// let instance = json!(42);
2191 ///
2192 /// let validator = jsonschema::draft201909::new(&schema)?;
2193 /// assert!(validator.is_valid(&instance));
2194 /// # Ok(())
2195 /// # }
2196 /// ```
2197 ///
2198 /// # Errors
2199 ///
2200 /// Returns an error if the schema is not a valid Draft 2019-09 document or if referenced resources
2201 /// cannot be resolved.
2202 pub fn new(schema: &Value) -> Result<Validator, ValidationError<'static>> {
2203 options().build(schema)
2204 }
2205 /// Validate an instance against a schema using Draft 2019-09 specifications without creating a validator.
2206 ///
2207 /// # Examples
2208 ///
2209 /// ```rust
2210 /// use serde_json::json;
2211 ///
2212 /// let schema = json!({"minimum": 5});
2213 /// let valid = json!(42);
2214 /// let invalid = json!(3);
2215 ///
2216 /// assert!(jsonschema::draft201909::is_valid(&schema, &valid));
2217 /// assert!(!jsonschema::draft201909::is_valid(&schema, &invalid));
2218 /// ```
2219 ///
2220 /// # Panics
2221 ///
2222 /// Panics if `schema` cannot be compiled into a Draft 2019-09 validator.
2223 #[must_use]
2224 pub fn is_valid(schema: &Value, instance: &Value) -> bool {
2225 new(schema).expect("Invalid schema").is_valid(instance)
2226 }
2227 /// Validate an instance against a schema using Draft 2019-09 specifications without creating a validator.
2228 ///
2229 /// # Examples
2230 ///
2231 /// ```rust
2232 /// use serde_json::json;
2233 ///
2234 /// let schema = json!({"minimum": 5});
2235 /// let valid = json!(42);
2236 /// let invalid = json!(3);
2237 ///
2238 /// assert!(jsonschema::draft201909::validate(&schema, &valid).is_ok());
2239 /// assert!(jsonschema::draft201909::validate(&schema, &invalid).is_err());
2240 /// ```
2241 ///
2242 /// # Errors
2243 ///
2244 /// Returns the first [`ValidationError`] when `instance` violates the schema.
2245 ///
2246 /// # Panics
2247 ///
2248 /// Panics if `schema` cannot be compiled into a Draft 2019-09 validator.
2249 pub fn validate<'i>(schema: &Value, instance: &'i Value) -> Result<(), ValidationError<'i>> {
2250 new(schema).expect("Invalid schema").validate(instance)
2251 }
2252 /// Creates a [`ValidationOptions`] builder pre-configured for JSON Schema Draft 2019-09.
2253 ///
2254 /// This function provides a shorthand for `jsonschema::options().with_draft(Draft::Draft201909)`.
2255 ///
2256 /// # Examples
2257 ///
2258 /// ```
2259 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
2260 /// use serde_json::json;
2261 ///
2262 /// let schema = json!({"type": "string", "format": "ends-with-42"});
2263 /// let validator = jsonschema::draft201909::options()
2264 /// .with_format("ends-with-42", |s| s.ends_with("42"))
2265 /// .should_validate_formats(true)
2266 /// .build(&schema)?;
2267 ///
2268 /// assert!(validator.is_valid(&json!("Hello 42")));
2269 /// assert!(!validator.is_valid(&json!("No!")));
2270 /// # Ok(())
2271 /// # }
2272 /// ```
2273 ///
2274 /// See [`ValidationOptions`] for all available configuration options.
2275 #[must_use]
2276 pub fn options() -> ValidationOptions {
2277 crate::options().with_draft(Draft::Draft201909)
2278 }
2279
2280 /// Functionality for validating JSON Schema Draft 2019-09 documents.
2281 pub mod meta {
2282 use crate::{meta::MetaValidator, ValidationError};
2283 use serde_json::Value;
2284
2285 /// Returns a handle to the Draft 2019-09 meta-schema validator. Native targets borrow cached
2286 /// statics while `wasm32` builds an owned validator.
2287 #[must_use]
2288 pub fn validator() -> MetaValidator<'static> {
2289 crate::meta::validator_for_draft(super::Draft::Draft201909)
2290 }
2291 /// Validate a JSON Schema document against Draft 2019-09 meta-schema and get a `true` if the schema is valid
2292 /// and `false` otherwise.
2293 ///
2294 /// # Examples
2295 ///
2296 /// ```rust
2297 /// use serde_json::json;
2298 ///
2299 /// let schema = json!({
2300 /// "type": "string",
2301 /// "maxLength": 5
2302 /// });
2303 /// assert!(jsonschema::draft201909::meta::is_valid(&schema));
2304 /// ```
2305 #[must_use]
2306 #[inline]
2307 pub fn is_valid(schema: &Value) -> bool {
2308 validator().as_ref().is_valid(schema)
2309 }
2310
2311 /// Validate a JSON Schema document against Draft 2019-09 meta-schema and return the first error if any.
2312 ///
2313 /// # Examples
2314 ///
2315 /// ```rust
2316 /// use serde_json::json;
2317 ///
2318 /// let schema = json!({
2319 /// "type": "string",
2320 /// "maxLength": 5
2321 /// });
2322 /// assert!(jsonschema::draft201909::meta::validate(&schema).is_ok());
2323 ///
2324 /// // Invalid schema
2325 /// let invalid_schema = json!({
2326 /// "type": "invalid_type"
2327 /// });
2328 /// assert!(jsonschema::draft201909::meta::validate(&invalid_schema).is_err());
2329 /// ```
2330 ///
2331 /// # Errors
2332 ///
2333 /// Returns the first [`ValidationError`] describing why the schema violates the Draft 2019-09 meta-schema.
2334 #[inline]
2335 pub fn validate(schema: &Value) -> Result<(), ValidationError<'_>> {
2336 validator().as_ref().validate(schema)
2337 }
2338 }
2339 }
2340
2341 /// Functionality specific to JSON Schema Draft 2020-12.
2342 ///
2343 /// [![Draft 2020-12](https://img.shields.io/endpoint?url=https%3A%2F%2Fbowtie.report%2Fbadges%2Frust-jsonschema%2Fcompliance%2Fdraft2020-12.json)](https://bowtie.report/#/implementations/rust-jsonschema)
2344 ///
2345 /// This module provides functions for creating validators and performing validation
2346 /// according to the JSON Schema Draft 2020-12 specification.
2347 ///
2348 /// # Examples
2349 ///
2350 /// ```rust
2351 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
2352 /// use serde_json::json;
2353 ///
2354 /// let schema = json!({"type": "object", "properties": {"name": {"type": "string"}}, "required": ["name"]});
2355 /// let instance = json!({"name": "John Doe"});
2356 ///
2357 /// assert!(jsonschema::draft202012::is_valid(&schema, &instance));
2358 /// # Ok(())
2359 /// # }
2360 /// ```
2361 pub mod draft202012 {
2362 use super::{Draft, ValidationError, ValidationOptions, Validator, Value};
2363
2364 /// Create a new JSON Schema validator using Draft 2020-12 specifications.
2365 ///
2366 /// # Examples
2367 ///
2368 /// ```rust
2369 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
2370 /// use serde_json::json;
2371 ///
2372 /// let schema = json!({"minimum": 5});
2373 /// let instance = json!(42);
2374 ///
2375 /// let validator = jsonschema::draft202012::new(&schema)?;
2376 /// assert!(validator.is_valid(&instance));
2377 /// # Ok(())
2378 /// # }
2379 /// ```
2380 ///
2381 /// # Errors
2382 ///
2383 /// Returns an error if the schema is not a valid Draft 2020-12 document or if referenced resources
2384 /// cannot be resolved.
2385 pub fn new(schema: &Value) -> Result<Validator, ValidationError<'static>> {
2386 options().build(schema)
2387 }
2388 /// Validate an instance against a schema using Draft 2020-12 specifications without creating a validator.
2389 ///
2390 /// # Examples
2391 ///
2392 /// ```rust
2393 /// use serde_json::json;
2394 ///
2395 /// let schema = json!({"minimum": 5});
2396 /// let valid = json!(42);
2397 /// let invalid = json!(3);
2398 ///
2399 /// assert!(jsonschema::draft202012::is_valid(&schema, &valid));
2400 /// assert!(!jsonschema::draft202012::is_valid(&schema, &invalid));
2401 /// ```
2402 ///
2403 /// # Panics
2404 ///
2405 /// Panics if `schema` cannot be compiled into a Draft 2020-12 validator.
2406 #[must_use]
2407 pub fn is_valid(schema: &Value, instance: &Value) -> bool {
2408 new(schema).expect("Invalid schema").is_valid(instance)
2409 }
2410 /// Validate an instance against a schema using Draft 2020-12 specifications without creating a validator.
2411 ///
2412 /// # Examples
2413 ///
2414 /// ```rust
2415 /// use serde_json::json;
2416 ///
2417 /// let schema = json!({"minimum": 5});
2418 /// let valid = json!(42);
2419 /// let invalid = json!(3);
2420 ///
2421 /// assert!(jsonschema::draft202012::validate(&schema, &valid).is_ok());
2422 /// assert!(jsonschema::draft202012::validate(&schema, &invalid).is_err());
2423 /// ```
2424 ///
2425 /// # Errors
2426 ///
2427 /// Returns the first [`ValidationError`] when `instance` violates the schema.
2428 ///
2429 /// # Panics
2430 ///
2431 /// Panics if `schema` cannot be compiled into a Draft 2020-12 validator.
2432 pub fn validate<'i>(schema: &Value, instance: &'i Value) -> Result<(), ValidationError<'i>> {
2433 new(schema).expect("Invalid schema").validate(instance)
2434 }
2435 /// Creates a [`ValidationOptions`] builder pre-configured for JSON Schema Draft 2020-12.
2436 ///
2437 /// This function provides a shorthand for `jsonschema::options().with_draft(Draft::Draft202012)`.
2438 ///
2439 /// # Examples
2440 ///
2441 /// ```
2442 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
2443 /// use serde_json::json;
2444 ///
2445 /// let schema = json!({"type": "string", "format": "ends-with-42"});
2446 /// let validator = jsonschema::draft202012::options()
2447 /// .with_format("ends-with-42", |s| s.ends_with("42"))
2448 /// .should_validate_formats(true)
2449 /// .build(&schema)?;
2450 ///
2451 /// assert!(validator.is_valid(&json!("Hello 42")));
2452 /// assert!(!validator.is_valid(&json!("No!")));
2453 /// # Ok(())
2454 /// # }
2455 /// ```
2456 ///
2457 /// See [`ValidationOptions`] for all available configuration options.
2458 #[must_use]
2459 pub fn options() -> ValidationOptions {
2460 crate::options().with_draft(Draft::Draft202012)
2461 }
2462
2463 /// Functionality for validating JSON Schema Draft 2020-12 documents.
2464 pub mod meta {
2465 use crate::{meta::MetaValidator, ValidationError};
2466 use serde_json::Value;
2467
2468 /// Returns a handle to the Draft 2020-12 meta-schema validator. Native targets borrow
2469 /// cached statics while `wasm32` builds an owned validator.
2470 #[must_use]
2471 pub fn validator() -> MetaValidator<'static> {
2472 crate::meta::validator_for_draft(super::Draft::Draft202012)
2473 }
2474
2475 /// Validate a JSON Schema document against Draft 2020-12 meta-schema and get a `true` if the schema is valid
2476 /// and `false` otherwise.
2477 ///
2478 /// # Examples
2479 ///
2480 /// ```rust
2481 /// use serde_json::json;
2482 ///
2483 /// let schema = json!({
2484 /// "type": "string",
2485 /// "maxLength": 5
2486 /// });
2487 /// assert!(jsonschema::draft202012::meta::is_valid(&schema));
2488 /// ```
2489 #[must_use]
2490 #[inline]
2491 pub fn is_valid(schema: &Value) -> bool {
2492 validator().as_ref().is_valid(schema)
2493 }
2494
2495 /// Validate a JSON Schema document against Draft 2020-12 meta-schema and return the first error if any.
2496 ///
2497 /// # Examples
2498 ///
2499 /// ```rust
2500 /// use serde_json::json;
2501 ///
2502 /// let schema = json!({
2503 /// "type": "string",
2504 /// "maxLength": 5
2505 /// });
2506 /// assert!(jsonschema::draft202012::meta::validate(&schema).is_ok());
2507 ///
2508 /// // Invalid schema
2509 /// let invalid_schema = json!({
2510 /// "type": "invalid_type"
2511 /// });
2512 /// assert!(jsonschema::draft202012::meta::validate(&invalid_schema).is_err());
2513 /// ```
2514 ///
2515 /// # Errors
2516 ///
2517 /// Returns the first [`ValidationError`] describing why the schema violates the Draft 2020-12 meta-schema.
2518 #[inline]
2519 pub fn validate(schema: &Value) -> Result<(), ValidationError<'_>> {
2520 validator().as_ref().validate(schema)
2521 }
2522 }
2523 }
2524
2525 #[cfg(test)]
2526 pub(crate) mod tests_util {
2527 use super::Validator;
2528 use crate::ValidationError;
2529 use serde_json::Value;
2530
2531 #[track_caller]
2532 pub(crate) fn is_not_valid_with(validator: &Validator, instance: &Value) {
2533 assert!(
2534 !validator.is_valid(instance),
2535 "{instance} should not be valid (via is_valid)",
2536 );
2537 assert!(
2538 validator.validate(instance).is_err(),
2539 "{instance} should not be valid (via validate)",
2540 );
2541 assert!(
2542 validator.iter_errors(instance).next().is_some(),
2543 "{instance} should not be valid (via validate)",
2544 );
2545 let evaluation = validator.evaluate(instance);
2546 assert!(
2547 !evaluation.flag().valid,
2548 "{instance} should not be valid (via evaluate)",
2549 );
2550 }
2551
2552 #[track_caller]
2553 pub(crate) fn is_not_valid(schema: &Value, instance: &Value) {
2554 let validator = crate::options()
2555 .should_validate_formats(true)
2556 .build(schema)
2557 .expect("Invalid schema");
2558 is_not_valid_with(&validator, instance);
2559 }
2560
2561 pub(crate) fn expect_errors(schema: &Value, instance: &Value, errors: &[&str]) {
2562 assert_eq!(
2563 crate::validator_for(schema)
2564 .expect("Should be a valid schema")
2565 .iter_errors(instance)
2566 .map(|e| e.to_string())
2567 .collect::<Vec<String>>(),
2568 errors
2569 );
2570 }
2571
2572 #[track_caller]
2573 pub(crate) fn is_valid_with(validator: &Validator, instance: &Value) {
2574 if let Some(first) = validator.iter_errors(instance).next() {
2575 panic!(
2576 "{} should be valid (via validate). Error: {} at {}",
2577 instance,
2578 first,
2579 first.instance_path()
2580 );
2581 }
2582 assert!(
2583 validator.is_valid(instance),
2584 "{instance} should be valid (via is_valid)",
2585 );
2586 assert!(
2587 validator.validate(instance).is_ok(),
2588 "{instance} should be valid (via is_valid)",
2589 );
2590 let evaluation = validator.evaluate(instance);
2591 assert!(
2592 evaluation.flag().valid,
2593 "{instance} should be valid (via evaluate)",
2594 );
2595 }
2596
2597 #[track_caller]
2598 pub(crate) fn is_valid(schema: &Value, instance: &Value) {
2599 let validator = crate::options()
2600 .should_validate_formats(true)
2601 .build(schema)
2602 .expect("Invalid schema");
2603 is_valid_with(&validator, instance);
2604 }
2605
2606 #[track_caller]
2607 pub(crate) fn validate(schema: &Value, instance: &Value) -> ValidationError<'static> {
2608 let validator = crate::options()
2609 .should_validate_formats(true)
2610 .build(schema)
2611 .expect("Invalid schema");
2612 let err = validator
2613 .validate(instance)
2614 .expect_err("Should be an error")
2615 .to_owned();
2616 err
2617 }
2618
2619 #[track_caller]
2620 pub(crate) fn assert_schema_location(schema: &Value, instance: &Value, expected: &str) {
2621 let error = validate(schema, instance);
2622 assert_eq!(error.schema_path().as_str(), expected);
2623 }
2624
2625 #[track_caller]
2626 pub(crate) fn assert_locations(schema: &Value, instance: &Value, expected: &[&str]) {
2627 let validator = crate::validator_for(schema).unwrap();
2628 let errors = validator.iter_errors(instance);
2629 for (error, location) in errors.into_iter().zip(expected) {
2630 assert_eq!(error.schema_path().as_str(), *location);
2631 }
2632 }
2633
2634 #[track_caller]
2635 pub(crate) fn assert_keyword_location(
2636 validator: &Validator,
2637 instance: &Value,
2638 instance_pointer: &str,
2639 keyword_pointer: &str,
2640 ) {
2641 fn pointer_from_schema_location(location: &str) -> &str {
2642 location
2643 .split_once('#')
2644 .map_or(location, |(_, fragment)| fragment)
2645 }
2646
2647 let evaluation = validator.evaluate(instance);
2648 let serialized =
2649 serde_json::to_value(evaluation.list()).expect("List output should be serializable");
2650 let details = serialized
2651 .get("details")
2652 .and_then(|value| value.as_array())
2653 .expect("List output must contain details");
2654 let mut available = Vec::new();
2655 for entry in details {
2656 let Some(instance_location) = entry
2657 .get("instanceLocation")
2658 .and_then(|value| value.as_str())
2659 else {
2660 continue;
2661 };
2662 if instance_location != instance_pointer {
2663 continue;
2664 }
2665 let schema_location = entry
2666 .get("schemaLocation")
2667 .and_then(|value| value.as_str())
2668 .unwrap_or("");
2669 let pointer = pointer_from_schema_location(schema_location);
2670 if pointer == keyword_pointer {
2671 return;
2672 }
2673 available.push(pointer.to_string());
2674 }
2675
2676 panic!(
2677 "No annotation for instance pointer `{instance_pointer}` with keyword location `{keyword_pointer}`. Available keyword locations for pointer: {available:?}"
2678 );
2679 }
2680 }
2681
2682 #[cfg(test)]
2683 mod tests {
2684 use crate::{validator_for, ValidationError};
2685 use referencing::{Registry, Resource};
2686
2687 use super::Draft;
2688 use serde_json::json;
2689 use test_case::test_case;
2690
2691 #[test_case(crate::is_valid ; "autodetect")]
2692 #[test_case(crate::draft4::is_valid ; "draft4")]
2693 #[test_case(crate::draft6::is_valid ; "draft6")]
2694 #[test_case(crate::draft7::is_valid ; "draft7")]
2695 #[test_case(crate::draft201909::is_valid ; "draft201909")]
2696 #[test_case(crate::draft202012::is_valid ; "draft202012")]
2697 fn test_is_valid(is_valid_fn: fn(&serde_json::Value, &serde_json::Value) -> bool) {
2698 let schema = json!({
2699 "type": "object",
2700 "properties": {
2701 "name": {"type": "string"},
2702 "age": {"type": "integer", "minimum": 0}
2703 },
2704 "required": ["name"]
2705 });
2706
2707 let valid_instance = json!({
2708 "name": "John Doe",
2709 "age": 30
2710 });
2711
2712 let invalid_instance = json!({
2713 "age": -5
2714 });
2715
2716 assert!(is_valid_fn(&schema, &valid_instance));
2717 assert!(!is_valid_fn(&schema, &invalid_instance));
2718 }
2719
2720 #[test_case(crate::validate ; "autodetect")]
2721 #[test_case(crate::draft4::validate ; "draft4")]
2722 #[test_case(crate::draft6::validate ; "draft6")]
2723 #[test_case(crate::draft7::validate ; "draft7")]
2724 #[test_case(crate::draft201909::validate ; "draft201909")]
2725 #[test_case(crate::draft202012::validate ; "draft202012")]
2726 fn test_validate(
2727 validate_fn: for<'i> fn(
2728 &serde_json::Value,
2729 &'i serde_json::Value,
2730 ) -> Result<(), ValidationError<'i>>,
2731 ) {
2732 let schema = json!({
2733 "type": "object",
2734 "properties": {
2735 "name": {"type": "string"},
2736 "age": {"type": "integer", "minimum": 0}
2737 },
2738 "required": ["name"]
2739 });
2740
2741 let valid_instance = json!({
2742 "name": "John Doe",
2743 "age": 30
2744 });
2745
2746 let invalid_instance = json!({
2747 "age": -5
2748 });
2749
2750 assert!(validate_fn(&schema, &valid_instance).is_ok());
2751 assert!(validate_fn(&schema, &invalid_instance).is_err());
2752 }
2753
2754 #[test]
2755 fn test_evaluate() {
2756 let schema = json!({
2757 "type": "object",
2758 "properties": {
2759 "name": {"type": "string"},
2760 "age": {"type": "integer", "minimum": 0}
2761 },
2762 "required": ["name"]
2763 });
2764
2765 let valid_instance = json!({
2766 "name": "John Doe",
2767 "age": 30
2768 });
2769
2770 let invalid_instance = json!({
2771 "age": -5
2772 });
2773
2774 let valid_eval = crate::evaluate(&schema, &valid_instance);
2775 assert!(valid_eval.flag().valid);
2776
2777 let invalid_eval = crate::evaluate(&schema, &invalid_instance);
2778 assert!(!invalid_eval.flag().valid);
2779 let errors: Vec<_> = invalid_eval.iter_errors().collect();
2780 assert!(!errors.is_empty());
2781 }
2782
2783 #[test_case(crate::meta::validate, crate::meta::is_valid ; "autodetect")]
2784 #[test_case(crate::draft4::meta::validate, crate::draft4::meta::is_valid ; "draft4")]
2785 #[test_case(crate::draft6::meta::validate, crate::draft6::meta::is_valid ; "draft6")]
2786 #[test_case(crate::draft7::meta::validate, crate::draft7::meta::is_valid ; "draft7")]
2787 #[test_case(crate::draft201909::meta::validate, crate::draft201909::meta::is_valid ; "draft201909")]
2788 #[test_case(crate::draft202012::meta::validate, crate::draft202012::meta::is_valid ; "draft202012")]
2789 fn test_meta_validation(
2790 validate_fn: fn(&serde_json::Value) -> Result<(), ValidationError>,
2791 is_valid_fn: fn(&serde_json::Value) -> bool,
2792 ) {
2793 let valid = json!({
2794 "type": "object",
2795 "properties": {
2796 "name": {"type": "string"},
2797 "age": {"type": "integer", "minimum": 0}
2798 },
2799 "required": ["name"]
2800 });
2801
2802 let invalid = json!({
2803 "type": "invalid_type",
2804 "minimum": "not_a_number",
2805 "required": true // should be an array
2806 });
2807
2808 assert!(validate_fn(&valid).is_ok());
2809 assert!(validate_fn(&invalid).is_err());
2810 assert!(is_valid_fn(&valid));
2811 assert!(!is_valid_fn(&invalid));
2812 }
2813
2814 #[test]
2815 fn test_exclusive_minimum_across_drafts() {
2816 // In Draft 4, exclusiveMinimum is a boolean modifier for minimum
2817 let draft4_schema = json!({
2818 "$schema": "http://json-schema.org/draft-04/schema#",
2819 "minimum": 5,
2820 "exclusiveMinimum": true
2821 });
2822 assert!(crate::meta::is_valid(&draft4_schema));
2823 assert!(crate::meta::validate(&draft4_schema).is_ok());
2824
2825 // This is invalid in Draft 4 (exclusiveMinimum must be boolean)
2826 let invalid_draft4 = json!({
2827 "$schema": "http://json-schema.org/draft-04/schema#",
2828 "exclusiveMinimum": 5
2829 });
2830 assert!(!crate::meta::is_valid(&invalid_draft4));
2831 assert!(crate::meta::validate(&invalid_draft4).is_err());
2832
2833 // In Draft 6 and later, exclusiveMinimum is a numeric value
2834 let drafts = [
2835 "http://json-schema.org/draft-06/schema#",
2836 "http://json-schema.org/draft-07/schema#",
2837 "https://json-schema.org/draft/2019-09/schema",
2838 "https://json-schema.org/draft/2020-12/schema",
2839 ];
2840
2841 for uri in drafts {
2842 // Valid in Draft 6+ (numeric exclusiveMinimum)
2843 let valid_schema = json!({
2844 "$schema": uri,
2845 "exclusiveMinimum": 5
2846 });
2847 assert!(
2848 crate::meta::is_valid(&valid_schema),
2849 "Schema should be valid for {uri}"
2850 );
2851 assert!(
2852 crate::meta::validate(&valid_schema).is_ok(),
2853 "Schema validation should succeed for {uri}",
2854 );
2855
2856 // Invalid in Draft 6+ (can't use boolean with minimum)
2857 let invalid_schema = json!({
2858 "$schema": uri,
2859 "minimum": 5,
2860 "exclusiveMinimum": true
2861 });
2862 assert!(
2863 !crate::meta::is_valid(&invalid_schema),
2864 "Schema should be invalid for {uri}",
2865 );
2866 assert!(
2867 crate::meta::validate(&invalid_schema).is_err(),
2868 "Schema validation should fail for {uri}",
2869 );
2870 }
2871 }
2872
2873 #[test_case(
2874 "http://json-schema.org/draft-04/schema#",
2875 true,
2876 5,
2877 true ; "draft4 valid"
2878 )]
2879 #[test_case(
2880 "http://json-schema.org/draft-04/schema#",
2881 5,
2882 true,
2883 false ; "draft4 invalid"
2884 )]
2885 #[test_case(
2886 "http://json-schema.org/draft-06/schema#",
2887 5,
2888 true,
2889 false ; "draft6 invalid"
2890 )]
2891 #[test_case(
2892 "http://json-schema.org/draft-07/schema#",
2893 5,
2894 true,
2895 false ; "draft7 invalid"
2896 )]
2897 #[test_case(
2898 "https://json-schema.org/draft/2019-09/schema",
2899 5,
2900 true,
2901 false ; "draft2019-09 invalid"
2902 )]
2903 #[test_case(
2904 "https://json-schema.org/draft/2020-12/schema",
2905 5,
2906 true,
2907 false ; "draft2020-12 invalid"
2908 )]
2909 fn test_exclusive_minimum_detection(
2910 schema_uri: &str,
2911 exclusive_minimum: impl Into<serde_json::Value>,
2912 minimum: impl Into<serde_json::Value>,
2913 expected: bool,
2914 ) {
2915 let schema = json!({
2916 "$schema": schema_uri,
2917 "minimum": minimum.into(),
2918 "exclusiveMinimum": exclusive_minimum.into()
2919 });
2920
2921 let is_valid_result = crate::meta::is_valid(&schema);
2922 assert_eq!(is_valid_result, expected);
2923
2924 let validate_result = crate::meta::validate(&schema);
2925 assert_eq!(validate_result.is_ok(), expected);
2926 }
2927
2928 #[test]
2929 fn test_invalid_schema_uri() {
2930 let schema = json!({
2931 "$schema": "invalid-uri",
2932 "type": "string"
2933 });
2934
2935 let result = crate::options().without_schema_validation().build(&schema);
2936
2937 assert!(result.is_err());
2938 let error = result.unwrap_err();
2939 assert!(error.to_string().contains("Unknown meta-schema"));
2940 assert!(error.to_string().contains("invalid-uri"));
2941 }
2942
2943 #[test]
2944 fn test_invalid_schema_keyword() {
2945 let schema = json!({
2946 // Note `htt`, not `http`
2947 "$schema": "htt://json-schema.org/draft-07/schema",
2948 "type": "string"
2949 });
2950
2951 // Without registering the meta-schema, this should fail
2952 let result = crate::options().without_schema_validation().build(&schema);
2953
2954 assert!(result.is_err());
2955 let error = result.unwrap_err();
2956 assert!(error.to_string().contains("Unknown meta-schema"));
2957 assert!(error
2958 .to_string()
2959 .contains("htt://json-schema.org/draft-07/schema"));
2960 }
2961
2962 #[test_case(Draft::Draft4)]
2963 #[test_case(Draft::Draft6)]
2964 #[test_case(Draft::Draft7)]
2965 fn meta_schemas(draft: Draft) {
2966 // See GH-258
2967 for schema in [json!({"enum": [0, 0.0]}), json!({"enum": []})] {
2968 assert!(crate::options().with_draft(draft).build(&schema).is_ok());
2969 }
2970 }
2971
2972 #[test]
2973 fn incomplete_escape_in_pattern() {
2974 // See GH-253
2975 let schema = json!({"pattern": "\\u"});
2976 assert!(crate::validator_for(&schema).is_err());
2977 }
2978
2979 #[test]
2980 fn validation_error_propagation() {
2981 fn foo() -> Result<(), Box<dyn std::error::Error>> {
2982 let schema = json!({});
2983 let validator = validator_for(&schema)?;
2984 let _ = validator.is_valid(&json!({}));
2985 Ok(())
2986 }
2987 let _ = foo();
2988 }
2989
2990 #[test]
2991 fn test_meta_validation_with_unknown_schema() {
2992 let schema = json!({
2993 "$schema": "json-schema:///custom",
2994 "type": "string"
2995 });
2996
2997 // Meta-validation now errors when the meta-schema is unknown/unregistered
2998 assert!(crate::meta::validate(&schema).is_err());
2999
3000 // Building a validator also fails without registration
3001 let result = crate::validator_for(&schema);
3002 assert!(result.is_err());
3003 }
3004
3005 #[test]
3006 #[cfg(all(not(target_arch = "wasm32"), feature = "resolve-file"))]
3007 fn test_meta_validation_respects_metaschema_draft() {
3008 use std::io::Write;
3009
3010 let mut temp_file = tempfile::NamedTempFile::new().expect("Failed to create temp file");
3011 let meta_schema_draft7 = json!({
3012 "$id": "http://example.com/meta/draft7",
3013 "$schema": "http://json-schema.org/draft-07/schema",
3014 "type": ["object", "boolean"],
3015 "properties": {
3016 "$schema": { "type": "string" },
3017 "type": {},
3018 "properties": { "type": "object" }
3019 },
3020 "additionalProperties": false
3021 });
3022 write!(temp_file, "{meta_schema_draft7}").expect("Failed to write to temp file");
3023
3024 let uri = crate::retriever::path_to_uri(temp_file.path());
3025
3026 let schema_using_draft7_meta = json!({
3027 "$schema": uri,
3028 "type": "object",
3029 "properties": {
3030 "name": { "type": "string" }
3031 },
3032 "unevaluatedProperties": false
3033 });
3034
3035 let schema_valid_for_draft7_meta = json!({
3036 "$schema": uri,
3037 "type": "object",
3038 "properties": {
3039 "name": { "type": "string" }
3040 }
3041 });
3042
3043 assert!(crate::meta::is_valid(&meta_schema_draft7));
3044 assert!(!crate::meta::is_valid(&schema_using_draft7_meta));
3045 assert!(crate::meta::is_valid(&schema_valid_for_draft7_meta));
3046 }
3047
3048 #[test]
3049 #[cfg(all(not(target_arch = "wasm32"), feature = "resolve-file"))]
3050 fn test_meta_schema_chain_resolution() {
3051 use std::io::Write;
3052
3053 // Create intermediate meta-schema pointing to Draft 2020-12
3054 let mut intermediate_file =
3055 tempfile::NamedTempFile::new().expect("Failed to create temp file");
3056 let intermediate_meta = json!({
3057 "$id": "http://example.com/meta/intermediate",
3058 "$schema": "https://json-schema.org/draft/2020-12/schema",
3059 "type": "object"
3060 });
3061 write!(intermediate_file, "{intermediate_meta}").expect("Failed to write to temp file");
3062 let intermediate_uri = crate::retriever::path_to_uri(intermediate_file.path());
3063
3064 // Create custom meta-schema with unknown draft that points to intermediate
3065 // This triggers the chain resolution code path in resolve_meta_schema_chain
3066 let mut custom_file = tempfile::NamedTempFile::new().expect("Failed to create temp file");
3067 let custom_meta = json!({
3068 "$id": "http://example.com/meta/custom",
3069 "$schema": intermediate_uri,
3070 "type": "object"
3071 });
3072 write!(custom_file, "{custom_meta}").expect("Failed to write to temp file");
3073 let custom_uri = crate::retriever::path_to_uri(custom_file.path());
3074
3075 let schema = json!({
3076 "$schema": custom_uri,
3077 "type": "string"
3078 });
3079
3080 // Should successfully resolve through the chain and detect Draft 2020-12
3081 assert!(crate::meta::is_valid(&schema));
3082 }
3083
3084 #[test]
3085 #[cfg(all(not(target_arch = "wasm32"), feature = "resolve-file"))]
3086 fn test_circular_meta_schema_reference() {
3087 use std::io::Write;
3088
3089 // Create meta-schema A pointing to meta-schema B
3090 let mut meta_a_file = tempfile::NamedTempFile::new().expect("Failed to create temp file");
3091 let meta_a_uri = crate::retriever::path_to_uri(meta_a_file.path());
3092
3093 // Create meta-schema B pointing back to meta-schema A
3094 let mut meta_b_file = tempfile::NamedTempFile::new().expect("Failed to create temp file");
3095 let meta_b_uri = crate::retriever::path_to_uri(meta_b_file.path());
3096
3097 let meta_a = json!({
3098 "$id": "http://example.com/meta/a",
3099 "$schema": &meta_b_uri,
3100 "type": "object"
3101 });
3102 write!(meta_a_file, "{meta_a}").expect("Failed to write to temp file");
3103
3104 let meta_b = json!({
3105 "$id": "http://example.com/meta/b",
3106 "$schema": &meta_a_uri,
3107 "type": "object"
3108 });
3109 write!(meta_b_file, "{meta_b}").expect("Failed to write to temp file");
3110
3111 let schema = json!({
3112 "$schema": meta_a_uri.clone(),
3113 "type": "string"
3114 });
3115
3116 // Should return a circular meta-schema error
3117 let result = crate::meta::options().validate(&schema);
3118 assert!(result.is_err());
3119 assert!(result
3120 .unwrap_err()
3121 .to_string()
3122 .contains("Circular meta-schema reference"));
3123 }
3124
3125 #[test]
3126 fn simple_schema_with_unknown_draft() {
3127 // Define a custom meta-schema
3128 let meta_schema = json!({
3129 "$schema": "https://json-schema.org/draft/2020-12/schema",
3130 "$id": "http://custom.example.com/schema",
3131 "$vocabulary": {
3132 "https://json-schema.org/draft/2020-12/vocab/core": true,
3133 "https://json-schema.org/draft/2020-12/vocab/applicator": true,
3134 "https://json-schema.org/draft/2020-12/vocab/validation": true,
3135 }
3136 });
3137
3138 // Schema using the custom meta-schema
3139 let schema = json!({
3140 "$schema": "http://custom.example.com/schema",
3141 "type": "object",
3142 "properties": {
3143 "name": { "type": "string" }
3144 }
3145 });
3146
3147 // Register the custom meta-schema as a resource
3148 let resources = vec![(
3149 "http://custom.example.com/schema".to_string(),
3150 Resource::from_contents(meta_schema),
3151 )];
3152
3153 let validator = crate::options()
3154 .without_schema_validation()
3155 .with_resources(resources.into_iter())
3156 .build(&schema)
3157 .expect("Should build validator");
3158
3159 // Valid instance
3160 assert!(validator.is_valid(&json!({"name": "test"})));
3161
3162 // Invalid instance - name should be string, not number
3163 assert!(!validator.is_valid(&json!({"name": 123})));
3164
3165 // Also verify type validation works
3166 assert!(!validator.is_valid(&json!("not an object")));
3167 }
3168
3169 #[test]
3170 fn custom_meta_schema_support() {
3171 // Define a custom meta-schema that extends Draft 2020-12
3172 let meta_schema = json!({
3173 "$id": "http://example.com/meta/schema",
3174 "$schema": "https://json-schema.org/draft/2020-12/schema",
3175 "title": "Core schema definition",
3176 "type": "object",
3177 "allOf": [
3178 {
3179 "$ref": "#/$defs/editable"
3180 },
3181 {
3182 "$ref": "#/$defs/core"
3183 }
3184 ],
3185 "properties": {
3186 "properties": {
3187 "type": "object",
3188 "patternProperties": {
3189 ".*": {
3190 "type": "object",
3191 "properties": {
3192 "type": {
3193 "type": "string",
3194 "enum": [
3195 "array",
3196 "boolean",
3197 "integer",
3198 "number",
3199 "object",
3200 "string",
3201 "null"
3202 ]
3203 }
3204 }
3205 }
3206 },
3207 "propertyNames": {
3208 "type": "string",
3209 "pattern": "^[A-Za-z_][A-Za-z0-9_]*$"
3210 }
3211 }
3212 },
3213 "unevaluatedProperties": false,
3214 "required": [
3215 "properties"
3216 ],
3217 "$defs": {
3218 "core": {
3219 "type": "object",
3220 "properties": {
3221 "$id": {
3222 "type": "string"
3223 },
3224 "$schema": {
3225 "type": "string"
3226 },
3227 "type": {
3228 "const": "object"
3229 },
3230 "title": {
3231 "type": "string"
3232 },
3233 "description": {
3234 "type": "string"
3235 },
3236 "additionalProperties": {
3237 "type": "boolean",
3238 "const": false
3239 }
3240 },
3241 "required": [
3242 "$id",
3243 "$schema",
3244 "type"
3245 ]
3246 },
3247 "editable": {
3248 "type": "object",
3249 "properties": {
3250 "creationDate": {
3251 "type": "string",
3252 "format": "date-time"
3253 },
3254 "updateDate": {
3255 "type": "string",
3256 "format": "date-time"
3257 }
3258 },
3259 "required": [
3260 "creationDate"
3261 ]
3262 }
3263 }
3264 });
3265
3266 // A schema that uses the custom meta-schema
3267 let element_schema = json!({
3268 "$schema": "http://example.com/meta/schema",
3269 "$id": "http://example.com/schemas/element",
3270 "title": "Element",
3271 "description": "An element",
3272 "creationDate": "2024-12-31T12:31:53+01:00",
3273 "properties": {
3274 "value": {
3275 "type": "string"
3276 }
3277 },
3278 "type": "object"
3279 });
3280
3281 // Build the validator with both the meta-schema and the element schema as resources
3282 let resources = vec![
3283 (
3284 "http://example.com/meta/schema".to_string(),
3285 referencing::Resource::from_contents(meta_schema),
3286 ),
3287 (
3288 "http://example.com/schemas/element".to_string(),
3289 referencing::Resource::from_contents(element_schema.clone()),
3290 ),
3291 ];
3292
3293 let validator = crate::options()
3294 .without_schema_validation()
3295 .with_resources(resources.into_iter())
3296 .build(&element_schema)
3297 .expect("Should successfully build validator with custom meta-schema");
3298
3299 let valid_instance = json!({
3300 "value": "test string"
3301 });
3302 assert!(validator.is_valid(&valid_instance));
3303
3304 let invalid_instance = json!({
3305 "value": 123
3306 });
3307 assert!(!validator.is_valid(&invalid_instance));
3308 }
3309
3310 #[test]
3311 fn custom_meta_schema_with_fragment_finds_vocabularies() {
3312 // Custom meta-schema URIs with trailing # should be found in registry
3313 let custom_meta = json!({
3314 "$id": "http://example.com/custom-with-unevaluated",
3315 "$schema": "https://json-schema.org/draft/2020-12/schema",
3316 "$vocabulary": {
3317 "https://json-schema.org/draft/2020-12/vocab/core": true,
3318 "https://json-schema.org/draft/2020-12/vocab/applicator": true,
3319 "https://json-schema.org/draft/2020-12/vocab/validation": true,
3320 "https://json-schema.org/draft/2020-12/vocab/unevaluated": true
3321 }
3322 });
3323
3324 let registry = Registry::try_new(
3325 "http://example.com/custom-with-unevaluated",
3326 Resource::from_contents(custom_meta),
3327 )
3328 .expect("Should create registry");
3329
3330 let schema = json!({
3331 "$schema": "http://example.com/custom-with-unevaluated#",
3332 "type": "object",
3333 "properties": {
3334 "foo": { "type": "string" }
3335 },
3336 "unevaluatedProperties": false
3337 });
3338
3339 let validator = crate::options()
3340 .without_schema_validation()
3341 .with_registry(registry)
3342 .build(&schema)
3343 .expect("Should build validator");
3344
3345 assert!(validator.is_valid(&json!({"foo": "bar"})));
3346 assert!(!validator.is_valid(&json!({"foo": "bar", "extra": "value"})));
3347 }
3348
3349 #[test]
3350 fn strict_meta_schema_catches_typos() {
3351 // Issue #764: Use strict meta-schema with unevaluatedProperties: false
3352 // to catch typos in schema keywords
3353
3354 let strict_meta = json!({
3355 "$schema": "https://json-schema.org/draft/2020-12/schema",
3356 "$id": "https://json-schema.org/draft/2020-12/strict",
3357 "$dynamicAnchor": "meta",
3358 "$ref": "https://json-schema.org/draft/2020-12/schema",
3359 "unevaluatedProperties": false
3360 });
3361
3362 let registry = Registry::try_new(
3363 "https://json-schema.org/draft/2020-12/strict",
3364 Resource::from_contents(strict_meta),
3365 )
3366 .expect("Should create registry");
3367
3368 // Valid schema - all keywords are recognized
3369 let valid_schema = json!({
3370 "$schema": "https://json-schema.org/draft/2020-12/strict",
3371 "type": "object",
3372 "properties": {
3373 "name": {"type": "string", "minLength": 1}
3374 }
3375 });
3376
3377 assert!(crate::meta::options()
3378 .with_registry(registry.clone())
3379 .is_valid(&valid_schema));
3380
3381 // Invalid schema - top-level typo "typ" instead of "type"
3382 let invalid_schema_top_level = json!({
3383 "$schema": "https://json-schema.org/draft/2020-12/strict",
3384 "typ": "string" // Typo
3385 });
3386
3387 assert!(!crate::meta::options()
3388 .with_registry(registry.clone())
3389 .is_valid(&invalid_schema_top_level));
3390
3391 // Invalid schema - nested invalid keyword "minSize" (not a real JSON Schema keyword)
3392 let invalid_schema_nested = json!({
3393 "$schema": "https://json-schema.org/draft/2020-12/strict",
3394 "type": "object",
3395 "properties": {
3396 "name": {"type": "string", "minSize": 1} // Invalid keyword in nested schema
3397 }
3398 });
3399
3400 assert!(!crate::meta::options()
3401 .with_registry(registry)
3402 .is_valid(&invalid_schema_nested));
3403 }
3404
3405 #[test]
3406 fn custom_meta_schema_preserves_underlying_draft_behavior() {
3407 // Regression test: Custom meta-schemas should preserve the draft-specific
3408 // behavior of their underlying draft, not default to Draft 2020-12
3409 // Draft 7 specific behavior: $ref siblings are ignored
3410
3411 let custom_meta_draft7 = json!({
3412 "$id": "http://example.com/meta/draft7-custom",
3413 "$schema": "http://json-schema.org/draft-07/schema#",
3414 "type": "object",
3415 "properties": {
3416 "customKeyword": {"type": "string"}
3417 }
3418 });
3419
3420 let registry = Registry::try_new(
3421 "http://example.com/meta/draft7-custom",
3422 Resource::from_contents(custom_meta_draft7),
3423 )
3424 .expect("Should create registry");
3425
3426 let schema = json!({
3427 "$schema": "http://example.com/meta/draft7-custom",
3428 "$ref": "#/$defs/positiveNumber",
3429 "maximum": 5,
3430 "$defs": {
3431 "positiveNumber": {
3432 "type": "number",
3433 "minimum": 0
3434 }
3435 }
3436 });
3437
3438 let validator = crate::options()
3439 .without_schema_validation()
3440 .with_registry(registry)
3441 .build(&schema)
3442 .expect("Should build validator");
3443
3444 // In Draft 7: siblings of $ref are ignored, so maximum: 5 has no effect
3445 // In Draft 2020-12: siblings are evaluated, so maximum: 5 would apply
3446 assert!(validator.is_valid(&json!(10)));
3447 }
3448
3449 mod meta_options_tests {
3450 use super::*;
3451 use crate::{Registry, Resource};
3452
3453 #[test]
3454 fn test_meta_options_with_registry_valid_schema() {
3455 let custom_meta = Resource::from_contents(json!({
3456 "$schema": "https://json-schema.org/draft/2020-12/schema",
3457 "type": "object",
3458 "properties": {
3459 "$schema": { "type": "string" },
3460 "type": { "type": "string" },
3461 "maxLength": { "type": "integer" }
3462 },
3463 "additionalProperties": false
3464 }));
3465
3466 let registry = Registry::try_new("http://example.com/meta", custom_meta).unwrap();
3467
3468 let schema = json!({
3469 "$schema": "http://example.com/meta",
3470 "type": "string",
3471 "maxLength": 10
3472 });
3473
3474 assert!(crate::meta::options()
3475 .with_registry(registry.clone())
3476 .is_valid(&schema));
3477
3478 assert!(crate::meta::options()
3479 .with_registry(registry)
3480 .validate(&schema)
3481 .is_ok());
3482 }
3483
3484 #[test]
3485 fn test_meta_options_with_registry_invalid_schema() {
3486 let custom_meta = Resource::from_contents(json!({
3487 "$schema": "https://json-schema.org/draft/2020-12/schema",
3488 "type": "object",
3489 "properties": {
3490 "type": { "type": "string" }
3491 },
3492 "additionalProperties": false
3493 }));
3494
3495 let registry = Registry::try_new("http://example.com/meta", custom_meta).unwrap();
3496
3497 // Schema has disallowed property
3498 let schema = json!({
3499 "$schema": "http://example.com/meta",
3500 "type": "string",
3501 "maxLength": 10 // Not allowed by custom meta-schema
3502 });
3503
3504 assert!(!crate::meta::options()
3505 .with_registry(registry.clone())
3506 .is_valid(&schema));
3507
3508 assert!(crate::meta::options()
3509 .with_registry(registry)
3510 .validate(&schema)
3511 .is_err());
3512 }
3513
3514 #[test]
3515 fn test_meta_options_with_registry_chain() {
3516 // Create a chain: custom-meta -> draft2020-12
3517 let custom_meta = Resource::from_contents(json!({
3518 "$schema": "https://json-schema.org/draft/2020-12/schema",
3519 "type": "object"
3520 }));
3521
3522 let registry = Registry::try_new("http://example.com/custom", custom_meta).unwrap();
3523
3524 let schema = json!({
3525 "$schema": "http://example.com/custom",
3526 "type": "string"
3527 });
3528
3529 assert!(crate::meta::options()
3530 .with_registry(registry)
3531 .is_valid(&schema));
3532 }
3533
3534 #[test]
3535 fn test_meta_options_with_registry_multi_level_chain() {
3536 // Create chain: schema -> meta-level-2 -> meta-level-1 -> draft2020-12
3537 let meta_level_1 = Resource::from_contents(json!({
3538 "$id": "http://example.com/meta/level1",
3539 "$schema": "https://json-schema.org/draft/2020-12/schema",
3540 "type": "object",
3541 "properties": {
3542 "customProp": { "type": "boolean" }
3543 }
3544 }));
3545
3546 let meta_level_2 = Resource::from_contents(json!({
3547 "$id": "http://example.com/meta/level2",
3548 "$schema": "http://example.com/meta/level1",
3549 "type": "object",
3550 "customProp": true
3551 }));
3552
3553 let registry = Registry::try_from_resources([
3554 ("http://example.com/meta/level1", meta_level_1),
3555 ("http://example.com/meta/level2", meta_level_2),
3556 ])
3557 .unwrap();
3558
3559 let schema = json!({
3560 "$schema": "http://example.com/meta/level2",
3561 "type": "string",
3562 "customProp": true
3563 });
3564
3565 assert!(crate::meta::options()
3566 .with_registry(registry)
3567 .is_valid(&schema));
3568 }
3569
3570 #[test]
3571 fn test_meta_options_with_registry_multi_document_meta_schema() {
3572 let shared_constraints = Resource::from_contents(json!({
3573 "$id": "http://example.com/meta/shared",
3574 "$schema": "https://json-schema.org/draft/2020-12/schema",
3575 "type": "object",
3576 "properties": {
3577 "maxLength": { "type": "integer", "minimum": 0 }
3578 }
3579 }));
3580
3581 let root_meta = Resource::from_contents(json!({
3582 "$id": "http://example.com/meta/root",
3583 "$schema": "https://json-schema.org/draft/2020-12/schema",
3584 "type": "object",
3585 "properties": {
3586 "$schema": { "type": "string" },
3587 "type": { "type": "string" }
3588 },
3589 "allOf": [
3590 { "$ref": "http://example.com/meta/shared" }
3591 ]
3592 }));
3593
3594 let registry = Registry::try_from_resources([
3595 ("http://example.com/meta/root", root_meta),
3596 ("http://example.com/meta/shared", shared_constraints),
3597 ])
3598 .unwrap();
3599
3600 let schema = json!({
3601 "$schema": "http://example.com/meta/root",
3602 "type": "string",
3603 "maxLength": 5
3604 });
3605
3606 let result = crate::meta::options()
3607 .with_registry(registry.clone())
3608 .validate(&schema);
3609
3610 assert!(
3611 result.is_ok(),
3612 "meta validation failed even though registry contains all meta-schemas: {}",
3613 result.unwrap_err()
3614 );
3615
3616 assert!(crate::meta::options()
3617 .with_registry(registry)
3618 .is_valid(&schema));
3619 }
3620
3621 #[test]
3622 fn test_meta_options_without_registry_unknown_metaschema() {
3623 let schema = json!({
3624 "$schema": "http://0.0.0.0/nonexistent",
3625 "type": "string"
3626 });
3627
3628 // Without registry, should fail to resolve
3629 let result = crate::meta::options().validate(&schema);
3630 assert!(result.is_err());
3631 }
3632
3633 #[test]
3634 #[should_panic(expected = "Failed to resolve meta-schema")]
3635 fn test_meta_options_is_valid_panics_on_missing_metaschema() {
3636 let schema = json!({
3637 "$schema": "http://0.0.0.0/nonexistent",
3638 "type": "string"
3639 });
3640
3641 // is_valid() should panic if meta-schema cannot be resolved
3642 let _ = crate::meta::options().is_valid(&schema);
3643 }
3644
3645 #[test]
3646 fn test_meta_options_with_registry_missing_metaschema() {
3647 let custom_meta = Resource::from_contents(json!({
3648 "$schema": "https://json-schema.org/draft/2020-12/schema",
3649 "type": "object"
3650 }));
3651
3652 let registry = Registry::try_new("http://example.com/meta1", custom_meta).unwrap();
3653
3654 // Schema references a different meta-schema not in registry
3655 let schema = json!({
3656 "$schema": "http://example.com/meta2",
3657 "type": "string"
3658 });
3659
3660 let result = crate::meta::options()
3661 .with_registry(registry)
3662 .validate(&schema);
3663
3664 assert!(result.is_err());
3665 }
3666
3667 #[test]
3668 fn test_meta_options_circular_reference_detection() {
3669 // Create a circular reference: meta1 -> meta2 -> meta1
3670 let meta1 = Resource::from_contents(json!({
3671 "$id": "http://example.com/meta1",
3672 "$schema": "http://example.com/meta2",
3673 "type": "object"
3674 }));
3675
3676 let meta2 = Resource::from_contents(json!({
3677 "$id": "http://example.com/meta2",
3678 "$schema": "http://example.com/meta1",
3679 "type": "object"
3680 }));
3681
3682 let registry = Registry::try_from_resources([
3683 ("http://example.com/meta1", meta1),
3684 ("http://example.com/meta2", meta2),
3685 ])
3686 .unwrap();
3687
3688 let schema = json!({
3689 "$schema": "http://example.com/meta1",
3690 "type": "string"
3691 });
3692
3693 let result = crate::meta::options()
3694 .with_registry(registry)
3695 .validate(&schema);
3696
3697 assert!(result.is_err());
3698 // Check it's specifically a circular error
3699 let err = result.unwrap_err();
3700 assert!(err.to_string().contains("Circular"));
3701 }
3702
3703 #[test]
3704 fn test_meta_options_standard_drafts_without_registry() {
3705 // Standard drafts should work without registry
3706 let schemas = vec![
3707 json!({ "$schema": "http://json-schema.org/draft-04/schema#", "type": "string" }),
3708 json!({ "$schema": "http://json-schema.org/draft-06/schema#", "type": "string" }),
3709 json!({ "$schema": "http://json-schema.org/draft-07/schema#", "type": "string" }),
3710 json!({ "$schema": "https://json-schema.org/draft/2019-09/schema", "type": "string" }),
3711 json!({ "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "string" }),
3712 ];
3713
3714 for schema in schemas {
3715 assert!(
3716 crate::meta::options().is_valid(&schema),
3717 "Failed for schema: {schema}"
3718 );
3719 }
3720 }
3721
3722 #[test]
3723 fn test_meta_options_validate_returns_specific_errors() {
3724 let custom_meta = Resource::from_contents(json!({
3725 "$schema": "https://json-schema.org/draft/2020-12/schema",
3726 "type": "object",
3727 "required": ["type"]
3728 }));
3729
3730 let registry = Registry::try_new("http://example.com/meta", custom_meta).unwrap();
3731
3732 // Schema missing required property
3733 let schema = json!({
3734 "$schema": "http://example.com/meta",
3735 "properties": {
3736 "name": { "type": "string" }
3737 }
3738 });
3739
3740 let result = crate::meta::options()
3741 .with_registry(registry)
3742 .validate(&schema);
3743
3744 assert!(result.is_err());
3745 let err = result.unwrap_err();
3746 assert!(err.to_string().contains("required") || err.to_string().contains("type"));
3747 }
3748
3749 #[test]
3750 fn test_meta_options_builds_validator_with_resolved_draft() {
3751 let custom_meta = Resource::from_contents(json!({
3752 "$id": "http://example.com/meta/draft7-based",
3753 "$schema": "http://json-schema.org/draft-07/schema#",
3754 "type": "object",
3755 "properties": {
3756 "$schema": { "type": "string" },
3757 "type": { "type": "string" },
3758 "minLength": { "type": "integer" }
3759 },
3760 "additionalProperties": false
3761 }));
3762
3763 let registry =
3764 Registry::try_new("http://example.com/meta/draft7-based", custom_meta).unwrap();
3765
3766 let schema = json!({
3767 "$schema": "http://example.com/meta/draft7-based",
3768 "type": "string",
3769 "minLength": 5
3770 });
3771
3772 let result = crate::meta::options()
3773 .with_registry(registry)
3774 .validate(&schema);
3775
3776 assert!(result.is_ok());
3777 }
3778
3779 #[test]
3780 fn test_meta_options_validator_uses_correct_draft() {
3781 let custom_meta_draft6 = Resource::from_contents(json!({
3782 "$id": "http://example.com/meta/draft6-based",
3783 "$schema": "http://json-schema.org/draft-06/schema#",
3784 "type": "object",
3785 "properties": {
3786 "$schema": { "type": "string" },
3787 "type": { "type": "string" },
3788 "exclusiveMinimum": { "type": "number" }
3789 },
3790 "additionalProperties": false
3791 }));
3792
3793 let registry =
3794 Registry::try_new("http://example.com/meta/draft6-based", custom_meta_draft6)
3795 .unwrap();
3796
3797 let schema_valid_for_draft6 = json!({
3798 "$schema": "http://example.com/meta/draft6-based",
3799 "type": "number",
3800 "exclusiveMinimum": 0
3801 });
3802
3803 let result = crate::meta::options()
3804 .with_registry(registry)
3805 .validate(&schema_valid_for_draft6);
3806
3807 assert!(result.is_ok());
3808 }
3809
3810 #[test]
3811 fn test_meta_options_without_schema_validation_in_built_validator() {
3812 let custom_meta = Resource::from_contents(json!({
3813 "$id": "http://example.com/meta/custom",
3814 "$schema": "https://json-schema.org/draft/2020-12/schema",
3815 "type": "object",
3816 "properties": {
3817 "$schema": { "type": "string" },
3818 "type": { "type": "string" }
3819 },
3820 "additionalProperties": false
3821 }));
3822
3823 let registry =
3824 Registry::try_new("http://example.com/meta/custom", custom_meta).unwrap();
3825
3826 let schema = json!({
3827 "$schema": "http://example.com/meta/custom",
3828 "type": "string"
3829 });
3830
3831 let result = crate::meta::options()
3832 .with_registry(registry)
3833 .validate(&schema);
3834
3835 assert!(result.is_ok());
3836 }
3837
3838 #[test]
3839 fn test_meta_validation_uses_resolved_draft_from_chain() {
3840 // Chain: user-schema -> custom-meta -> Draft 4
3841 // Validator should use Draft 4 rules to validate the schema
3842 let custom_meta = Resource::from_contents(json!({
3843 "$id": "http://example.com/meta/draft4-based",
3844 "$schema": "http://json-schema.org/draft-04/schema#",
3845 "type": "object",
3846 "properties": {
3847 "$schema": { "type": "string" },
3848 "type": { "type": "string" },
3849 "enum": { "type": "array" },
3850 "const": { "type": "string" }
3851 },
3852 "additionalProperties": false
3853 }));
3854
3855 let registry =
3856 Registry::try_new("http://example.com/meta/draft4-based", custom_meta).unwrap();
3857
3858 let schema = json!({
3859 "$schema": "http://example.com/meta/draft4-based",
3860 "type": "string",
3861 "const": "foo"
3862 });
3863
3864 let result = crate::meta::options()
3865 .with_registry(registry)
3866 .validate(&schema);
3867
3868 assert!(result.is_ok());
3869 }
3870
3871 #[test]
3872 fn test_meta_validation_multi_level_chain_uses_resolved_draft() {
3873 // Multi-level chain: user-schema -> meta-2 -> meta-1 -> Draft 4
3874 let meta_level_1 = Resource::from_contents(json!({
3875 "$id": "http://example.com/meta/level1",
3876 "$schema": "http://json-schema.org/draft-04/schema#",
3877 "type": "object",
3878 "properties": {
3879 "customKeyword": { "type": "boolean" }
3880 }
3881 }));
3882
3883 let meta_level_2 = Resource::from_contents(json!({
3884 "$id": "http://example.com/meta/level2",
3885 "$schema": "http://example.com/meta/level1",
3886 "type": "object",
3887 "properties": {
3888 "$schema": { "type": "string" },
3889 "type": { "type": "string" },
3890 "minimum": { "type": "number" },
3891 "exclusiveMinimum": { "type": "boolean" }
3892 },
3893 "customKeyword": true,
3894 "additionalProperties": false
3895 }));
3896
3897 let registry = Registry::try_from_resources([
3898 ("http://example.com/meta/level1", meta_level_1),
3899 ("http://example.com/meta/level2", meta_level_2),
3900 ])
3901 .unwrap();
3902
3903 let schema = json!({
3904 "$schema": "http://example.com/meta/level2",
3905 "type": "number",
3906 "minimum": 5,
3907 "exclusiveMinimum": true
3908 });
3909
3910 let result = crate::meta::options()
3911 .with_registry(registry)
3912 .validate(&schema);
3913
3914 assert!(result.is_ok());
3915 }
3916 }
3917
3918 #[test]
3919 fn test_meta_validator_for_valid_schema() {
3920 let schema = json!({
3921 "type": "string",
3922 "maxLength": 5
3923 });
3924
3925 let validator = crate::meta::validator_for(&schema).expect("Valid meta-schema");
3926 assert!(validator.is_valid(&schema));
3927 }
3928
3929 #[test]
3930 fn test_meta_validator_for_invalid_schema() {
3931 let schema = json!({
3932 "type": "invalid_type"
3933 });
3934
3935 let validator = crate::meta::validator_for(&schema).expect("Valid meta-schema");
3936 assert!(!validator.is_valid(&schema));
3937 }
3938
3939 #[test]
3940 fn test_meta_validator_for_evaluate_api() {
3941 let schema = json!({
3942 "type": "string",
3943 "maxLength": 5
3944 });
3945
3946 let validator = crate::meta::validator_for(&schema).expect("Valid meta-schema");
3947 let evaluation = validator.evaluate(&schema);
3948
3949 let flag = evaluation.flag();
3950 assert!(flag.valid);
3951 }
3952
3953 #[test]
3954 fn test_meta_validator_for_evaluate_api_invalid() {
3955 let schema = json!({
3956 "type": "invalid_type",
3957 "minimum": "not a number"
3958 });
3959
3960 let validator = crate::meta::validator_for(&schema).expect("Valid meta-schema");
3961 let evaluation = validator.evaluate(&schema);
3962
3963 let flag = evaluation.flag();
3964 assert!(!flag.valid);
3965 }
3966
3967 #[test]
3968 fn test_meta_validator_for_all_drafts() {
3969 let schemas = vec![
3970 json!({ "$schema": "http://json-schema.org/draft-04/schema#", "type": "string" }),
3971 json!({ "$schema": "http://json-schema.org/draft-06/schema#", "type": "string" }),
3972 json!({ "$schema": "http://json-schema.org/draft-07/schema#", "type": "string" }),
3973 json!({ "$schema": "https://json-schema.org/draft/2019-09/schema", "type": "string" }),
3974 json!({ "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "string" }),
3975 ];
3976
3977 for schema in schemas {
3978 let validator = crate::meta::validator_for(&schema).unwrap();
3979 assert!(validator.is_valid(&schema));
3980 }
3981 }
3982
3983 #[test]
3984 fn test_meta_validator_for_iter_errors() {
3985 let schema = json!({
3986 "type": "invalid_type",
3987 "minimum": "not a number"
3988 });
3989
3990 let validator = crate::meta::validator_for(&schema).expect("Valid meta-schema");
3991 let errors: Vec<_> = validator.iter_errors(&schema).collect();
3992 assert!(!errors.is_empty());
3993 }
3994 }
3995
3996 #[cfg(all(test, feature = "resolve-async", not(target_family = "wasm")))]
3997 mod async_tests {
3998 use referencing::Resource;
3999 use std::{collections::HashMap, sync::Arc};
4000
4001 use serde_json::json;
4002
4003 use crate::{AsyncRetrieve, Draft, Uri};
4004
4005 /// Mock async retriever for testing
4006 #[derive(Clone)]
4007 struct TestRetriever {
4008 schemas: HashMap<String, serde_json::Value>,
4009 }
4010
4011 impl TestRetriever {
4012 fn new() -> Self {
4013 let mut schemas = HashMap::new();
4014 schemas.insert(
4015 "https://example.com/user.json".to_string(),
4016 json!({
4017 "type": "object",
4018 "properties": {
4019 "name": {"type": "string"},
4020 "age": {"type": "integer", "minimum": 0}
4021 },
4022 "required": ["name"]
4023 }),
4024 );
4025 Self { schemas }
4026 }
4027 }
4028
4029 #[cfg_attr(target_family = "wasm", async_trait::async_trait(?Send))]
4030 #[cfg_attr(not(target_family = "wasm"), async_trait::async_trait)]
4031 impl AsyncRetrieve for TestRetriever {
4032 async fn retrieve(
4033 &self,
4034 uri: &Uri<String>,
4035 ) -> Result<serde_json::Value, Box<dyn std::error::Error + Send + Sync>> {
4036 self.schemas
4037 .get(uri.as_str())
4038 .cloned()
4039 .ok_or_else(|| "Schema not found".into())
4040 }
4041 }
4042
4043 #[tokio::test]
4044 async fn test_async_validator_for() {
4045 let schema = json!({
4046 "$ref": "https://example.com/user.json"
4047 });
4048
4049 let validator = crate::async_options()
4050 .with_retriever(TestRetriever::new())
4051 .build(&schema)
4052 .await
4053 .unwrap();
4054
4055 // Valid instance
4056 assert!(validator.is_valid(&json!({
4057 "name": "John Doe",
4058 "age": 30
4059 })));
4060
4061 // Invalid instances
4062 assert!(!validator.is_valid(&json!({
4063 "age": -5
4064 })));
4065 assert!(!validator.is_valid(&json!({
4066 "name": 123,
4067 "age": 30
4068 })));
4069 }
4070
4071 #[tokio::test]
4072 async fn test_async_options_with_draft() {
4073 let schema = json!({
4074 "$ref": "https://example.com/user.json"
4075 });
4076
4077 let validator = crate::async_options()
4078 .with_draft(Draft::Draft202012)
4079 .with_retriever(TestRetriever::new())
4080 .build(&schema)
4081 .await
4082 .unwrap();
4083
4084 assert!(validator.is_valid(&json!({
4085 "name": "John Doe",
4086 "age": 30
4087 })));
4088 }
4089
4090 #[tokio::test]
4091 async fn test_async_retrieval_failure() {
4092 let schema = json!({
4093 "$ref": "https://example.com/nonexistent.json"
4094 });
4095
4096 let result = crate::async_options()
4097 .with_retriever(TestRetriever::new())
4098 .build(&schema)
4099 .await;
4100
4101 assert!(result.is_err());
4102 assert!(result.unwrap_err().to_string().contains("Schema not found"));
4103 }
4104
4105 #[tokio::test]
4106 async fn test_async_nested_references() {
4107 let mut retriever = TestRetriever::new();
4108 retriever.schemas.insert(
4109 "https://example.com/nested.json".to_string(),
4110 json!({
4111 "type": "object",
4112 "properties": {
4113 "user": { "$ref": "https://example.com/user.json" }
4114 }
4115 }),
4116 );
4117
4118 let schema = json!({
4119 "$ref": "https://example.com/nested.json"
4120 });
4121
4122 let validator = crate::async_options()
4123 .with_retriever(retriever)
4124 .build(&schema)
4125 .await
4126 .unwrap();
4127
4128 // Valid nested structure
4129 assert!(validator.is_valid(&json!({
4130 "user": {
4131 "name": "John Doe",
4132 "age": 30
4133 }
4134 })));
4135
4136 // Invalid nested structure
4137 assert!(!validator.is_valid(&json!({
4138 "user": {
4139 "age": -5
4140 }
4141 })));
4142 }
4143
4144 #[tokio::test]
4145 async fn test_async_with_registry() {
4146 use crate::Registry;
4147
4148 // Create a registry with initial schemas
4149 let registry = Registry::options()
4150 .async_retriever(TestRetriever::new())
4151 .build([(
4152 "https://example.com/user.json",
4153 Resource::from_contents(json!({
4154 "type": "object",
4155 "properties": {
4156 "name": {"type": "string"},
4157 "age": {"type": "integer", "minimum": 0}
4158 },
4159 "required": ["name"]
4160 })),
4161 )])
4162 .await
4163 .unwrap();
4164
4165 // Create a validator using the pre-populated registry
4166 let validator = crate::async_options()
4167 .with_registry(registry)
4168 .build(&json!({
4169 "$ref": "https://example.com/user.json"
4170 }))
4171 .await
4172 .unwrap();
4173
4174 // Verify that validation works with the registry
4175 assert!(validator.is_valid(&json!({
4176 "name": "John Doe",
4177 "age": 30
4178 })));
4179 assert!(!validator.is_valid(&json!({
4180 "age": -5
4181 })));
4182 }
4183
4184 #[tokio::test]
4185 async fn test_async_validator_for_basic() {
4186 let schema = json!({"type": "integer"});
4187
4188 let validator = crate::async_validator_for(&schema).await.unwrap();
4189
4190 assert!(validator.is_valid(&json!(42)));
4191 assert!(!validator.is_valid(&json!("abc")));
4192 }
4193
4194 #[tokio::test]
4195 async fn test_async_build_future_is_send() {
4196 let schema = Arc::new(json!({
4197 "$ref": "https://example.com/user.json"
4198 }));
4199 let retriever = TestRetriever::new();
4200
4201 let handle = tokio::spawn({
4202 let schema = Arc::clone(&schema);
4203 let retriever = retriever.clone();
4204 async move {
4205 crate::async_options()
4206 .with_retriever(retriever)
4207 .build(&schema)
4208 .await
4209 }
4210 });
4211
4212 let validator = handle.await.unwrap().unwrap();
4213 assert!(validator.is_valid(&json!({
4214 "name": "John Doe",
4215 "age": 30
4216 })));
4217 }
4218 }