jsonschema 0.46.0

JSON schema validaton library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
//! Building a JSON Schema validator.
//! The main idea is to create a tree from the input JSON Schema. This tree will contain
//! everything needed to perform such validation in runtime.
use crate::{
    error::{error, no_error, ErrorIterator},
    evaluation::{Annotations, ErrorDescription, Evaluation, EvaluationNode},
    node::SchemaNode,
    paths::{LazyLocation, Location, RefTracker},
    Draft, ValidationError, ValidationOptions,
};
use ahash::AHashMap;
use serde_json::Value;

// Re-export LazyEvaluationPath from paths module
pub(crate) use crate::paths::LazyEvaluationPath;

/// Validation state for cycle detection and memoization.
#[derive(Default)]
pub struct ValidationContext {
    validating: Vec<(usize, usize)>,
    /// Lazy-initialized cache for recursive schema validation.
    is_valid_cache: Option<AHashMap<(usize, usize), bool>>,
    /// Lazy-initialized cache for ECMA regex transformation results during format "regex" validation.
    ecma_regex_cache: Option<AHashMap<String, bool>>,
}

impl ValidationContext {
    pub(crate) fn new() -> Self {
        Self::default()
    }

    /// Returns `true` if cycle detected.
    #[inline]
    pub(crate) fn enter(&mut self, node_id: usize, instance: &Value) -> bool {
        let key = (node_id, std::ptr::from_ref::<Value>(instance) as usize);
        if self.validating.contains(&key) {
            return true;
        }
        self.validating.push(key);
        false
    }

    #[inline]
    pub(crate) fn exit(&mut self, node_id: usize, instance: &Value) {
        let key = (node_id, std::ptr::from_ref::<Value>(instance) as usize);
        let popped = self.validating.pop();
        debug_assert_eq!(
            popped,
            Some(key),
            "ValidationContext::exit called out of order"
        );
    }

    /// Only caches arrays/objects to avoid false hits from stack address reuse.
    #[inline]
    pub(crate) fn get_cached_result(&self, node_id: usize, instance: &Value) -> Option<bool> {
        if !matches!(instance, Value::Array(_) | Value::Object(_)) {
            return None;
        }
        let cache = self.is_valid_cache.as_ref()?;
        let key = (node_id, std::ptr::from_ref::<Value>(instance) as usize);
        cache.get(&key).copied()
    }

    /// Only caches arrays/objects to avoid false hits from stack address reuse.
    #[inline]
    pub(crate) fn cache_result(&mut self, node_id: usize, instance: &Value, result: bool) {
        if !matches!(instance, Value::Array(_) | Value::Object(_)) {
            return;
        }
        let key = (node_id, std::ptr::from_ref::<Value>(instance) as usize);
        self.is_valid_cache
            .get_or_insert_with(AHashMap::new)
            .insert(key, result);
    }
    /// Check if an ECMA regex pattern is valid.
    pub(crate) fn is_valid_ecma_regex(&mut self, pattern: &str) -> bool {
        if let Some(cache) = &self.ecma_regex_cache {
            if let Some(&result) = cache.get(pattern) {
                return result;
            }
        }
        let result = crate::ecma::to_rust_regex(pattern).is_ok();
        self.ecma_regex_cache
            .get_or_insert_with(AHashMap::new)
            .insert(pattern.to_owned(), result);
        result
    }
}

/// The Validate trait represents a predicate over some JSON value. Some validators are very simple
/// predicates such as "a value which is a string", whereas others may be much more complex,
/// consisting of several other validators composed together in various ways.
///
/// Much of the time all an application cares about is whether the predicate returns true or false,
/// in that case the `is_valid` function is sufficient. Sometimes applications will want more
/// detail about why a schema has failed, in which case the `validate` method can be used to
/// iterate over the errors produced by this validator. Finally, applications may be interested in
/// annotations produced by schemas over valid results, in this case the `evaluate` method can be used
/// to obtain this information.
///
/// If you are implementing `Validate` it is often sufficient to implement `validate` and
/// `is_valid`. `evaluate` is only necessary for validators which compose other validators. See the
/// documentation for `evaluate` for more information.
///
/// # Context Types
///
/// - `is_valid` takes `LightweightContext`: Only cycle detection, zero path tracking overhead.
/// - `validate`, `iter_errors`, `evaluate` take `ValidationContext`: Cycle detection + evaluation path tracking.
pub(crate) trait Validate: Send + Sync {
    fn iter_errors<'i>(
        &self,
        instance: &'i Value,
        location: &LazyLocation,
        tracker: Option<&RefTracker>,
        ctx: &mut ValidationContext,
    ) -> ErrorIterator<'i> {
        match self.validate(instance, location, tracker, ctx) {
            Ok(()) => no_error(),
            Err(err) => error(err),
        }
    }

    fn is_valid(&self, instance: &Value, ctx: &mut ValidationContext) -> bool;

    fn validate<'i>(
        &self,
        instance: &'i Value,
        location: &LazyLocation,
        tracker: Option<&RefTracker>,
        ctx: &mut ValidationContext,
    ) -> Result<(), ValidationError<'i>>;

    fn evaluate(
        &self,
        instance: &Value,
        location: &LazyLocation,
        tracker: Option<&RefTracker>,
        ctx: &mut ValidationContext,
    ) -> EvaluationResult {
        let errors: Vec<ErrorDescription> = self
            .iter_errors(instance, location, tracker, ctx)
            .map(|e| ErrorDescription::from_validation_error(&e))
            .collect();
        if errors.is_empty() {
            EvaluationResult::valid_empty()
        } else {
            EvaluationResult::invalid_empty(errors)
        }
    }

    /// Returns the canonical location for this validator's schemaLocation output.
    ///
    /// Per JSON Schema spec, schemaLocation "MUST NOT include by-reference applicators
    /// such as `$ref` or `$dynamicRef`". For most validators, the keyword location is the
    /// canonical location, so this returns `None` by default.
    ///
    /// `RefValidator` and similar by-reference validators override this to return
    /// the target schema's canonical location (e.g., `/$defs/item` instead of
    /// `/properties/foo/$ref`).
    fn canonical_location(&self) -> Option<&Location> {
        None
    }
}

/// The result of evaluating a validator against an instance. This is a "partial" result because it does not include information about
/// where the error or annotation occurred.
#[derive(PartialEq)]
pub(crate) enum EvaluationResult {
    Valid {
        /// Annotations produced by this validator
        annotations: Option<Annotations>,
        /// Children evaluation nodes
        children: Vec<EvaluationNode>,
    },
    Invalid {
        /// Errors which caused this schema to be invalid
        errors: Vec<ErrorDescription>,
        /// Children evaluation nodes
        children: Vec<EvaluationNode>,
        /// Potential annotations that should be reported as dropped on failure
        annotations: Option<Annotations>,
    },
}

impl EvaluationResult {
    /// Create an empty `EvaluationResult` which is valid
    pub(crate) fn valid_empty() -> EvaluationResult {
        EvaluationResult::Valid {
            annotations: None,
            children: Vec::new(),
        }
    }

    /// Create an empty `EvaluationResult` which is invalid
    pub(crate) fn invalid_empty(errors: Vec<ErrorDescription>) -> EvaluationResult {
        EvaluationResult::Invalid {
            errors,
            children: Vec::new(),
            annotations: None,
        }
    }

    /// Set the annotation that will be returned for the current validator. If this
    /// `EvaluationResult` is invalid then this method does nothing
    pub(crate) fn annotate(&mut self, new_annotations: Annotations) {
        match self {
            Self::Valid { annotations, .. } | Self::Invalid { annotations, .. } => {
                *annotations = Some(new_annotations);
            }
        }
    }

    /// Set the error that will be returned for the current validator. If this
    /// `EvaluationResult` is valid then this method converts this application into
    /// `EvaluationResult::Invalid`
    pub(crate) fn mark_errored(&mut self, error: ErrorDescription) {
        match self {
            Self::Invalid { errors, .. } => errors.push(error),
            Self::Valid {
                annotations,
                children,
            } => {
                *self = Self::Invalid {
                    errors: vec![error],
                    children: std::mem::take(children),
                    annotations: annotations.take(),
                }
            }
        }
    }

    pub(crate) fn from_children(children: Vec<EvaluationNode>) -> EvaluationResult {
        if children.iter().any(|node| !node.valid) {
            EvaluationResult::Invalid {
                errors: Vec::new(),
                children,
                annotations: None,
            }
        } else {
            EvaluationResult::Valid {
                annotations: None,
                children,
            }
        }
    }
}

impl From<EvaluationNode> for EvaluationResult {
    fn from(node: EvaluationNode) -> Self {
        if node.valid {
            EvaluationResult::Valid {
                annotations: None,
                children: vec![node],
            }
        } else {
            EvaluationResult::Invalid {
                errors: Vec::new(),
                children: vec![node],
                annotations: None,
            }
        }
    }
}

/// A compiled JSON Schema validator.
///
/// This structure represents a JSON Schema that has been parsed and compiled into
/// an efficient internal representation for validation. It contains the root node
/// of the schema tree and the configuration options used during compilation.
#[derive(Clone, Debug)]
pub struct Validator {
    pub(crate) root: SchemaNode,
    pub(crate) draft: Draft,
}

impl Validator {
    /// Create a default [`ValidationOptions`] for configuring JSON Schema validation.
    ///
    /// Use this to set the draft version and other validation parameters.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use jsonschema::Draft;
    /// # let schema = serde_json::json!({});
    /// let validator = jsonschema::options()
    ///     .with_draft(Draft::Draft7)
    ///     .build(&schema);
    /// ```
    #[must_use]
    pub fn options<'i>() -> ValidationOptions<'i> {
        ValidationOptions::default()
    }
    /// Create a default [`ValidationOptions`] configured for async validation.
    ///
    /// Use this to set the draft version and other validation parameters when working
    /// with schemas that require async reference resolution.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use serde_json::json;
    /// # use jsonschema::Draft;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let schema = json!({
    ///     "$ref": "https://example.com/schema.json"
    /// });
    ///
    /// let validator = jsonschema::async_options()
    ///     .with_draft(Draft::Draft202012)
    ///     .build(&schema)
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// For sync validation, use [`options()`](crate::options()) instead.
    #[cfg(feature = "resolve-async")]
    #[must_use]
    pub fn async_options<'i>(
    ) -> ValidationOptions<'i, std::sync::Arc<dyn referencing::AsyncRetrieve>> {
        ValidationOptions::default()
    }
    /// Create a validator using the default options.
    ///
    /// # Errors
    ///
    /// Returns an error if the supplied `schema` is invalid for the selected draft or references cannot be resolved.
    pub fn new(schema: &Value) -> Result<Validator, ValidationError<'static>> {
        Self::options().build(schema)
    }
    /// Create a validator using the default async options.
    #[cfg(feature = "resolve-async")]
    ///
    /// # Errors
    ///
    /// Returns an error if the supplied `schema` is invalid for the selected draft or references cannot be resolved.
    pub async fn async_new(schema: &Value) -> Result<Validator, ValidationError<'static>> {
        Self::async_options().build(schema).await
    }
    /// Validate `instance` against `schema` and return the first error if any.
    ///
    /// # Errors
    ///
    /// Returns the first [`ValidationError`] describing why `instance` does not satisfy the schema.
    #[inline]
    pub fn validate<'i>(&self, instance: &'i Value) -> Result<(), ValidationError<'i>> {
        let mut ctx = ValidationContext::new();
        self.root
            .validate(instance, &LazyLocation::new(), None, &mut ctx)
    }
    /// Run validation against `instance` and return an iterator over [`ValidationError`] in the error case.
    #[inline]
    #[must_use]
    pub fn iter_errors<'i>(&'i self, instance: &'i Value) -> ErrorIterator<'i> {
        let mut ctx = ValidationContext::new();
        self.root
            .iter_errors(instance, &LazyLocation::new(), None, &mut ctx)
    }
    /// Run validation against `instance` but return a boolean result instead of an iterator.
    /// It is useful for cases, where it is important to only know the fact if the data is valid or not.
    /// This approach is much faster, than [`Validator::validate`].
    #[must_use]
    #[inline]
    pub fn is_valid(&self, instance: &Value) -> bool {
        let mut ctx = ValidationContext::new();
        self.root.is_valid(instance, &mut ctx)
    }
    /// Evaluate the schema and expose structured output formats.
    #[must_use]
    #[inline]
    pub fn evaluate(&self, instance: &Value) -> Evaluation {
        let mut ctx = ValidationContext::new();
        let root = self
            .root
            .evaluate_instance(instance, &LazyLocation::new(), None, &mut ctx);
        Evaluation::new(root)
    }
    /// The [`Draft`] which was used to build this validator.
    #[must_use]
    pub fn draft(&self) -> Draft {
        self.draft
    }
}

/// A map of compiled JSON Schema validators keyed by URI-fragment JSON pointers.
///
/// Built via [`ValidationOptions::build_map`] or the [`validator_map_for`](crate::validator_map_for)
/// convenience function.
///
/// Each key is a URI-fragment JSON pointer (e.g. `"#"`, `"#/$defs/User"`).
/// The root schema is always present under the key `"#"`.
#[derive(Debug)]
pub struct ValidatorMap {
    pub(crate) validators: AHashMap<String, Validator>,
}

impl ValidatorMap {
    /// Returns the validator for the given URI-fragment pointer, or `None` if not found.
    #[must_use]
    pub fn get(&self, pointer: &str) -> Option<&Validator> {
        self.validators.get(pointer)
    }

    /// Returns `true` if the map contains a validator for the given pointer.
    #[must_use]
    pub fn contains_key(&self, pointer: &str) -> bool {
        self.validators.contains_key(pointer)
    }

    /// Returns an iterator over all URI-fragment pointers in the map.
    pub fn keys(&self) -> impl Iterator<Item = &str> {
        self.validators.keys().map(String::as_str)
    }

    /// Returns the number of compiled subschema validators in the map.
    #[must_use]
    pub fn len(&self) -> usize {
        self.validators.len()
    }

    /// Returns `true` if the map contains no validators.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.validators.is_empty()
    }
}

impl std::ops::Index<&str> for ValidatorMap {
    type Output = Validator;

    /// # Panics
    ///
    /// Panics if the pointer is not found in the map.
    fn index(&self, pointer: &str) -> &Validator {
        self.validators
            .get(pointer)
            .unwrap_or_else(|| panic!("JSON pointer '{pointer}' not found in ValidatorMap"))
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        error::ValidationError, keywords::custom::Keyword, paths::Location, Validator, ValidatorMap,
    };
    use fancy_regex::Regex;
    use num_cmp::NumCmp;
    use serde_json::{json, Map, Value};
    use std::sync::LazyLock;

    #[cfg(not(target_arch = "wasm32"))]
    fn load(path: &str, idx: usize) -> Value {
        use std::{fs::File, io::Read, path::Path};
        let path = Path::new(path);
        let mut file = File::open(path).unwrap();
        let mut content = String::new();
        file.read_to_string(&mut content).ok().unwrap();
        let data: Value = serde_json::from_str(&content).unwrap();
        let case = &data.as_array().unwrap()[idx];
        case.get("schema").unwrap().clone()
    }

    #[test]
    fn only_keyword() {
        // When only one keyword is specified
        let schema = json!({"type": "string"});
        let validator = crate::validator_for(&schema).unwrap();
        let value1 = json!("AB");
        let value2 = json!(1);
        // And only this validator
        assert_eq!(validator.root.validators().len(), 1);
        assert!(validator.validate(&value1).is_ok());
        assert!(validator.validate(&value2).is_err());
    }

    #[test]
    #[cfg(not(target_arch = "wasm32"))]
    fn validate_ref() {
        let schema = load("tests/suite/tests/draft7/ref.json", 1);
        let value = json!({"bar": 3});
        let validator = crate::validator_for(&schema).unwrap();
        assert!(validator.validate(&value).is_ok());
        let value = json!({"bar": true});
        assert!(validator.validate(&value).is_err());
    }

    #[test]
    fn wrong_schema_type() {
        let schema = json!([1]);
        let validator = crate::validator_for(&schema);
        assert!(validator.is_err());
    }

    #[test]
    fn multiple_errors() {
        let schema = json!({"minProperties": 2, "propertyNames": {"minLength": 3}});
        let value = json!({"a": 3});
        let validator = crate::validator_for(&schema).unwrap();
        let errors: Vec<_> = validator.iter_errors(&value).collect();
        assert_eq!(errors.len(), 2);
        assert_eq!(
            errors[0].to_string(),
            r#"{"a":3} has less than 2 properties"#
        );
        assert_eq!(errors[1].to_string(), r#""a" is shorter than 3 characters"#);
    }

    #[test]
    fn custom_keyword_definition() {
        // Define a custom validator that verifies the object's keys consist of
        // only ASCII representable characters.
        // NOTE: This could be done with `propertyNames` + `pattern` but will be slower due to
        // regex usage.
        struct CustomObjectValidator;
        impl Keyword for CustomObjectValidator {
            fn validate<'i>(&self, instance: &'i Value) -> Result<(), ValidationError<'i>> {
                for key in instance.as_object().unwrap().keys() {
                    if !key.is_ascii() {
                        return Err(ValidationError::custom("Key is not ASCII"));
                    }
                }
                Ok(())
            }

            fn is_valid(&self, instance: &Value) -> bool {
                for (key, _value) in instance.as_object().unwrap() {
                    if !key.is_ascii() {
                        return false;
                    }
                }
                true
            }
        }

        fn custom_object_type_factory<'a>(
            _: &'a Map<String, Value>,
            schema: &'a Value,
            _path: Location,
        ) -> Result<Box<dyn Keyword>, ValidationError<'a>> {
            const EXPECTED: &str = "ascii-keys";
            if schema.as_str() == Some(EXPECTED) {
                Ok(Box::new(CustomObjectValidator))
            } else {
                Err(ValidationError::schema(format!(
                    "Expected '{EXPECTED}', got {schema}"
                )))
            }
        }

        // Define a JSON schema that enforces the top level object has ASCII keys and has at least 1 property
        let schema =
            json!({ "custom-object-type": "ascii-keys", "type": "object", "minProperties": 1 });
        let validator = crate::options()
            .with_keyword("custom-object-type", custom_object_type_factory)
            .build(&schema)
            .unwrap();

        // Verify schema validation detects object with too few properties
        let instance = json!({});
        assert!(validator.validate(&instance).is_err());
        assert!(!validator.is_valid(&instance));

        // Verify validator succeeds on a valid custom-object-type
        let instance = json!({ "a" : 1 });
        assert!(validator.validate(&instance).is_ok());
        assert!(validator.is_valid(&instance));

        // Verify validator detects invalid custom-object-type
        let instance = json!({ "Ã¥" : 1 });
        let error = validator.validate(&instance).expect_err("Should fail");
        assert_eq!(error.to_string(), "Key is not ASCII");
        assert!(!validator.is_valid(&instance));
    }

    #[test]
    fn custom_format_and_override_keyword() {
        // Check that a string has some number of digits followed by a dot followed by exactly 2 digits.
        fn currency_format_checker(s: &str) -> bool {
            static CURRENCY_RE: LazyLock<Regex> = LazyLock::new(|| {
                Regex::new("^(0|([1-9]+[0-9]*))(\\.[0-9]{2})$").expect("Invalid regex")
            });
            CURRENCY_RE.is_match(s).expect("Invalid regex")
        }
        // A custom keyword validator that overrides "minimum"
        // so that "minimum" may apply to "currency"-formatted strings as well.
        struct CustomMinimumValidator {
            limit: f64,
            with_currency_format: bool,
        }

        impl Keyword for CustomMinimumValidator {
            fn validate<'i>(&self, instance: &'i Value) -> Result<(), ValidationError<'i>> {
                if self.is_valid(instance) {
                    Ok(())
                } else {
                    Err(ValidationError::custom(format!(
                        "value is less than the minimum of {}",
                        self.limit
                    )))
                }
            }

            fn is_valid(&self, instance: &Value) -> bool {
                match instance {
                    // Numeric comparison should happen just like original behavior
                    Value::Number(instance) => {
                        if let Some(item) = instance.as_u64() {
                            !NumCmp::num_lt(item, self.limit)
                        } else if let Some(item) = instance.as_i64() {
                            !NumCmp::num_lt(item, self.limit)
                        } else {
                            let item = instance.as_f64().expect("Always valid");
                            !NumCmp::num_lt(item, self.limit)
                        }
                    }
                    // String comparison should cast currency-formatted
                    Value::String(instance) => {
                        if self.with_currency_format && currency_format_checker(instance) {
                            // all preconditions for minimum applying are met
                            let value = instance
                                .parse::<f64>()
                                .expect("format validated by regex checker");
                            !NumCmp::num_lt(value, self.limit)
                        } else {
                            true
                        }
                    }
                    // In all other cases, the "minimum" keyword should not apply
                    _ => true,
                }
            }
        }

        // Build a validator that overrides the standard `minimum` keyword
        fn custom_minimum_factory<'a>(
            parent: &'a Map<String, Value>,
            schema: &'a Value,
            _path: Location,
        ) -> Result<Box<dyn Keyword>, ValidationError<'a>> {
            let limit = if let Value::Number(limit) = schema {
                limit.as_f64().expect("Always valid")
            } else {
                return Err(ValidationError::schema("minimum must be a number"));
            };
            let with_currency_format = parent
                .get("format")
                .is_some_and(|format| format == "currency");
            Ok(Box::new(CustomMinimumValidator {
                limit,
                with_currency_format,
            }))
        }

        // Schema includes both the custom format and the overridden keyword
        let schema = json!({ "minimum": 2, "type": "string", "format": "currency" });
        let validator = crate::options()
            .with_format("currency", currency_format_checker)
            .with_keyword("minimum", custom_minimum_factory)
            .with_keyword("minimum-2", custom_minimum_factory)
            .should_validate_formats(true)
            .build(&schema)
            .expect("Invalid schema");

        // Control: verify schema validation rejects non-string types
        let instance = json!(15);
        assert!(validator.validate(&instance).is_err());
        assert!(!validator.is_valid(&instance));

        // Control: verify validator rejects ill-formatted strings
        let instance = json!("not a currency");
        assert!(validator.validate(&instance).is_err());
        assert!(!validator.is_valid(&instance));

        // Verify validator allows properly formatted strings that conform to custom keyword
        let instance = json!("3.00");
        assert!(validator.validate(&instance).is_ok());
        assert!(validator.is_valid(&instance));

        // Verify validator rejects properly formatted strings that do not conform to custom keyword
        let instance = json!("1.99");
        assert!(validator.validate(&instance).is_err());
        assert!(!validator.is_valid(&instance));

        // Define another schema that applies "minimum" to an integer to ensure original behavior
        let schema = json!({ "minimum": 2, "type": "integer" });
        let validator = crate::options()
            .with_format("currency", currency_format_checker)
            .with_keyword("minimum", custom_minimum_factory)
            .build(&schema)
            .expect("Invalid schema");

        // Verify schema allows integers greater than 2
        let instance = json!(3);
        assert!(validator.validate(&instance).is_ok());
        assert!(validator.is_valid(&instance));

        // Verify schema rejects integers less than 2
        let instance = json!(1);
        assert!(validator.validate(&instance).is_err());
        assert!(!validator.is_valid(&instance));

        // Invalid `minimum` value - meta-schema validation catches this first
        let schema = json!({ "minimum": "foo" });
        let error = crate::options()
            .with_keyword("minimum", custom_minimum_factory)
            .build(&schema)
            .expect_err("Should fail");
        // The meta-schema validates before our factory runs, so we get a type error
        assert_eq!(error.to_string(), "\"foo\" is not of type \"number\"");
    }

    #[test]
    fn custom_keyword_validation_error_paths() {
        struct AlwaysFailValidator;
        impl Keyword for AlwaysFailValidator {
            fn validate<'i>(&self, _instance: &'i Value) -> Result<(), ValidationError<'i>> {
                Err(ValidationError::custom("always fails"))
            }
            fn is_valid(&self, _instance: &Value) -> bool {
                false
            }
        }

        fn always_fail_factory<'a>(
            _: &'a Map<String, Value>,
            _: &'a Value,
            _: Location,
        ) -> Result<Box<dyn Keyword>, ValidationError<'a>> {
            Ok(Box::new(AlwaysFailValidator))
        }

        let schema = json!({
            "properties": {
                "name": { "alwaysFail": true }
            }
        });
        let validator = crate::options()
            .with_keyword("alwaysFail", always_fail_factory)
            .build(&schema)
            .expect("Valid schema");

        let instance = json!({"name": "test"});
        let error = validator.validate(&instance).expect_err("Should fail");
        assert_eq!(error.instance_path().as_str(), "/name");
        assert_eq!(error.schema_path().as_str(), "/properties/name/alwaysFail");
        assert_eq!(
            error.evaluation_path().as_str(),
            "/properties/name/alwaysFail"
        );
        assert_eq!(error.kind().keyword(), "alwaysFail");
    }

    #[test]
    fn custom_keyword_factory_error_schema_path() {
        fn failing_factory<'a>(
            _: &'a Map<String, Value>,
            _: &'a Value,
            _: Location,
        ) -> Result<Box<dyn Keyword>, ValidationError<'a>> {
            Err(ValidationError::schema("invalid schema value"))
        }

        let schema = json!({
            "properties": {
                "field": { "myKeyword": "bad-value" }
            }
        });
        let error = crate::options()
            .with_keyword("myKeyword", failing_factory)
            .build(&schema)
            .expect_err("Should fail");
        assert_eq!(error.to_string(), "invalid schema value");
        assert_eq!(error.schema_path().as_str(), "/properties/field/myKeyword");
    }

    #[test]
    fn test_validator_is_send_and_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<Validator>();
    }

    #[test]
    fn test_validator_map_is_send_and_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<ValidatorMap>();
    }

    #[test]
    fn test_validator_clone() {
        let schema = json!({"type": "string", "minLength": 3});
        let validator = crate::validator_for(&schema).expect("Valid schema");

        // Clone the validator
        let cloned = validator.clone();

        // Both validators should work independently
        assert!(validator.is_valid(&json!("hello")));
        assert!(!validator.is_valid(&json!("hi")));

        assert!(cloned.is_valid(&json!("hello")));
        assert!(!cloned.is_valid(&json!("hi")));

        // Verify they validate the same way
        assert_eq!(
            validator.is_valid(&json!("test")),
            cloned.is_valid(&json!("test"))
        );
    }

    #[test]
    fn ref_with_required_multiple_missing_clones_deferred_eval_path() {
        // Tests the Deferred branch of LazyEvaluationPath::clone()
        // When $ref is involved and multiple required properties are missing,
        // the eval_path is cloned for each error
        let schema = json!({
            "$defs": {
                "Person": {
                    "type": "object",
                    "required": ["name", "age", "email"]
                }
            },
            "$ref": "#/$defs/Person"
        });
        let validator = crate::validator_for(&schema).expect("Valid schema");
        let instance = json!({});

        let errors: Vec<_> = validator.iter_errors(&instance).collect();

        // Should have 3 errors for the 3 missing required properties
        assert_eq!(errors.len(), 3);

        // All errors should have evaluation paths that include the $ref traversal
        for error in &errors {
            assert_eq!(error.schema_path().as_str(), "/$defs/Person/required");
            assert_eq!(error.evaluation_path().as_str(), "/$ref/required");
        }
    }

    #[test]
    fn test_validator_map_get_existing() {
        let schema = json!({
            "$defs": {
                "User": {"type": "object", "required": ["name"]}
            }
        });
        let map = crate::validator_map_for(&schema).unwrap();
        let v = map.get("#/$defs/User").unwrap();
        assert!(v.is_valid(&json!({"name": "Alice"})));
        assert!(!v.is_valid(&json!({})));
    }

    #[test]
    fn test_validator_map_root_always_present() {
        let schema = json!({"type": "string"});
        let map = crate::validator_map_for(&schema).unwrap();
        assert!(map.get("#").unwrap().is_valid(&json!("hello")));
        assert!(!map.get("#").unwrap().is_valid(&json!(42)));
    }

    #[test]
    fn test_validator_map_get_missing_returns_none() {
        let schema = json!({"type": "object"});
        let map = crate::validator_map_for(&schema).unwrap();
        assert!(map.get("#/nonexistent").is_none());
    }

    #[test]
    fn test_validator_map_contains_key() {
        let schema = json!({"$defs": {"Foo": {"type": "string"}}});
        let map = crate::validator_map_for(&schema).unwrap();
        assert!(map.contains_key("#/$defs/Foo"));
        assert!(!map.contains_key("#/missing"));
    }

    #[test]
    fn test_validator_map_keys_includes_root_and_defs() {
        let schema = json!({
            "type": "object",
            "$defs": {"Foo": {"type": "string"}}
        });
        let map = crate::validator_map_for(&schema).unwrap();
        let keys: std::collections::HashSet<&str> = map.keys().collect();
        assert!(keys.contains("#"));
        assert!(keys.contains("#/$defs/Foo"));
    }

    #[test]
    fn test_validator_map_index() {
        let schema = json!({"$defs": {"Bar": {"type": "integer"}}});
        let map = crate::validator_map_for(&schema).unwrap();
        assert!(map["#/$defs/Bar"].is_valid(&json!(42)));
        assert!(!map["#/$defs/Bar"].is_valid(&json!("nope")));
    }

    #[test]
    #[should_panic(expected = "JSON pointer '#/nonexistent' not found in ValidatorMap")]
    fn test_validator_map_index_panics_on_missing() {
        let schema = json!({"type": "object"});
        let map = crate::validator_map_for(&schema).unwrap();
        let _ = &map["#/nonexistent"];
    }

    #[test]
    fn test_validator_map_via_options() {
        let schema = json!({"$defs": {"S": {"type": "string"}}});
        let map = crate::options().build_map(&schema).unwrap();
        assert!(map.get("#/$defs/S").unwrap().is_valid(&json!("hello")));
    }

    #[cfg(all(feature = "resolve-async", not(target_family = "wasm")))]
    #[tokio::test]
    async fn test_async_validator_map_for() {
        let schema = json!({"$defs": {"T": {"type": "string"}}});
        let map = crate::async_validator_map_for(&schema).await.unwrap();
        assert!(map["#/$defs/T"].is_valid(&json!("hello")));
        assert!(!map["#/$defs/T"].is_valid(&json!(42)));
    }

    #[cfg(all(feature = "resolve-async", not(target_family = "wasm")))]
    #[tokio::test]
    async fn test_async_build_map_via_options() {
        let schema = json!({"$defs": {"N": {"type": "integer"}}});
        let map = crate::async_options().build_map(&schema).await.unwrap();
        assert!(map["#/$defs/N"].is_valid(&json!(7)));
        assert!(!map["#/$defs/N"].is_valid(&json!("not an int")));
    }

    #[test]
    fn test_validator_map_len() {
        let schema = json!({
            "$defs": {
                "A": {"type": "string"},
                "B": {"type": "integer"}
            }
        });
        let map = crate::validator_map_for(&schema).unwrap();
        assert!(map.len() >= 3); // root + A + B
    }

    #[test]
    fn test_validator_map_is_empty_false() {
        let schema = json!({"type": "string"});
        let map = crate::validator_map_for(&schema).unwrap();
        assert!(!map.is_empty());
    }

    #[test]
    fn test_validator_map_nested_pointer() {
        let schema = json!({
            "properties": {
                "name": {"type": "string", "minLength": 2}
            }
        });
        let map = crate::validator_map_for(&schema).unwrap();
        assert!(map["#/properties/name"].is_valid(&json!("Al")));
        assert!(!map["#/properties/name"].is_valid(&json!("A")));
    }

    #[test]
    fn test_validator_map_with_registry() {
        let address_schema = json!({
            "type": "object",
            "properties": {
                "city": {"type": "string"},
                "zip": {"type": "string"}
            },
            "required": ["city"]
        });
        let registry = crate::Registry::new()
            .add("https://example.com/address.json", &address_schema)
            .expect("valid resource")
            .prepare()
            .expect("registry build failed");

        let schema = json!({
            "$defs": {
                "Address": {"$ref": "https://example.com/address.json"}
            }
        });
        let map = crate::options()
            .with_registry(&registry)
            .build_map(&schema)
            .unwrap();

        let v = map.get("#/$defs/Address").unwrap();
        assert!(v.is_valid(&json!({"city": "NYC", "zip": "10001"})));
        assert!(!v.is_valid(&json!({"zip": "10001"}))); // missing required "city"
    }

    #[test]
    fn test_validator_map_with_registry_multiple_refs() {
        let user_schema = json!({
            "type": "object",
            "properties": {"name": {"type": "string"}},
            "required": ["name"]
        });
        let role_schema = json!({
            "type": "string",
            "enum": ["admin", "user", "guest"]
        });
        let registry = crate::Registry::new()
            .add("https://example.com/user.json", &user_schema)
            .expect("valid resource")
            .add("https://example.com/role.json", &role_schema)
            .expect("valid resource")
            .prepare()
            .expect("registry build failed");

        let schema = json!({
            "$defs": {
                "User": {"$ref": "https://example.com/user.json"},
                "Role": {"$ref": "https://example.com/role.json"}
            }
        });
        let map = crate::options()
            .with_registry(&registry)
            .build_map(&schema)
            .unwrap();

        assert!(map["#/$defs/User"].is_valid(&json!({"name": "Alice"})));
        assert!(!map["#/$defs/User"].is_valid(&json!({})));
        assert!(map["#/$defs/Role"].is_valid(&json!("admin")));
        assert!(!map["#/$defs/Role"].is_valid(&json!("superuser")));
    }

    #[cfg(all(feature = "resolve-async", not(target_family = "wasm")))]
    #[tokio::test]
    async fn test_async_validator_map_with_registry() {
        let address_schema = json!({
            "type": "object",
            "properties": {"city": {"type": "string"}},
            "required": ["city"]
        });
        let registry = crate::Registry::new()
            .add("https://example.com/address.json", &address_schema)
            .expect("valid resource")
            .prepare()
            .expect("registry build failed");

        let schema = json!({
            "$defs": {
                "Address": {"$ref": "https://example.com/address.json"}
            }
        });
        let map = crate::async_options()
            .with_registry(&registry)
            .build_map(&schema)
            .await
            .unwrap();

        let v = map.get("#/$defs/Address").unwrap();
        assert!(v.is_valid(&json!({"city": "NYC"})));
        assert!(!v.is_valid(&json!({})));
    }

    #[cfg(all(feature = "resolve-async", not(target_family = "wasm")))]
    #[tokio::test]
    async fn test_async_validator_map_with_registry_multiple_refs() {
        let user_schema = json!({
            "type": "object",
            "properties": {"name": {"type": "string"}},
            "required": ["name"]
        });
        let role_schema = json!({
            "type": "string",
            "enum": ["admin", "user", "guest"]
        });
        let registry = crate::Registry::new()
            .add("https://example.com/user.json", &user_schema)
            .expect("valid resource")
            .add("https://example.com/role.json", &role_schema)
            .expect("valid resource")
            .prepare()
            .expect("registry build failed");

        let schema = json!({
            "$defs": {
                "User": {"$ref": "https://example.com/user.json"},
                "Role": {"$ref": "https://example.com/role.json"}
            }
        });
        let map = crate::async_options()
            .with_registry(&registry)
            .build_map(&schema)
            .await
            .unwrap();

        assert!(map["#/$defs/User"].is_valid(&json!({"name": "Alice"})));
        assert!(!map["#/$defs/User"].is_valid(&json!({})));
        assert!(map["#/$defs/Role"].is_valid(&json!("admin")));
        assert!(!map["#/$defs/Role"].is_valid(&json!("superuser")));
    }
}